I try to use c++ stl library.
I'd like to transform a vector of string to a map of int, string.
For example: a vector that looks like that:
const char *vinit[] = { "Sunday", "Monday", "Tuesday", "Wednesday" };
vector <string> v(vinit, end(vinit));
Will transform to a map like that:
map<int, string> map = {{ 1, "Sunday" },
{ 2, "Monday" },
{ 3, "Tuesday" },
{ 4, "Wednesday" } };
The point is that I can't use any loops and a global index as an integer.
[EDIT]
you can use map::insert for this:
const char *vinit[] = { "Sunday", "Monday", "Tuesday", "Wednesday" };
vector <string> v(vinit, end(vinit));
std::map<int,string> map;
for(int i = 0; i < v.size(); i++)
{
map.insert (std::pair<int,string>(i+1,v[i]));
}
Related
{
"data": [
{
"id": 10,
"title": "Administration",
"active": true,
"type": {
"id": 2,
"name": "Manager"
}
},
{
"id": 207,
"title": "MCO - Exact Match 1",
"active": true,
"type": {
"id": 128,
"name": "Group"
}
},
{
"id": 1201,
"title": "Regression",
"active": false,
"type": {
"id": 2,
"name": "Manager"
}
}
]
}
i am trying to create a tuple in the below format using linq. not sure how to start with group/aggregate. Any help is appreciated. I went over few threads and could not able to find something similar to this.
var tuple = new List<Tuple<int, List<Dictionary<int,bool>>>();
2 10, true
1201, false
128 207, true
Here is a full working code:
var o = new {
data = new [] {
new {
id = 10,
title = "Administration",
active = true,
type = new {
id = 2,
name = "Manager"
}
},
new {
id = 207,
title = "MCO - Exact Match 1",
active = true,
type = new {
id = 128,
name = "Group"
}
},
new {
id = 1201,
title = "Regression",
active = false,
type = new {
id = 2,
name = "Manager"
}
}
}
};
var result = o.data.GroupBy(
item => item.type.id, // the group key
item => new Dictionary<int, bool>() {{ item.id, item.active }}, // the transformed elements in the group
(id, items) => new Tuple<int, List<Dictionary<int, bool>>>(id, items.ToList()) // transformation of grouping result to the final desired format
).ToList();
// check correctness
foreach (var entry in result) {
Console.Write(entry.Item1);
foreach (var dict in entry.Item2) {
foreach (var kvp in dict)
Console.WriteLine("\t\t" + kvp.Key + "\t" + kvp.Value);
}
}
And this is how it works:
o is the data model, represented using anonymous types. You can obviously use a strongly typed model here, if you already have it;
on o we apply the four-argument version of GroupBy, described in detail in the official docs from Microsoft. Basically:
the first lambda expression selects the group key;
the second lambda defines the elements that are part of each group;
the third lambda transforms each (group key, enumeration of group elements) into the Tuple<int, List<Dictionary<int, bool>>> format;
at the end we call ToList() to compute the result and store it as a list of tuples.
the last part prints the result (did not spend much time prettifying it, but it does its job validating the code).
Can I return something like:
{
"c/12313" = 1,
"c/24223" = 2,
"c/43423" = 3,
...
}
from an AQL query? The idea is something like (this non-working code):
for c in my_collection
return { c._id : c.sortOrder }
where sortOrder is some property on my documents.
Yes, it is possible to have dynamic attribute names:
LET key = "foo"
LET value = "bar"
RETURN { [ key ]: value } // { "foo": "bar" }
An expression to compute the attribute key has to be wrapped in [ square brackets ], like in JavaScript.
This doesn't return quite the desired result however:
FOR c IN my_collection
RETURN { [ c._id ]: c.sortOrder }
[
{ "c/12313": 1 },
{ "c/24223": 2 },
{ "c/43423": 3 },
...
]
To not return separate objects for every key, MERGE() and a subquery are required:
RETURN MERGE(
FOR c IN my_collection
RETURN { [ c._id ]: c.sortOrder }
)
[
{
"c/12313": 1,
"c/24223": 2,
"c/43423": 3,
...
}
]
I have a struct what I need to marshal to consume the webservice, but in my tests I the Marshal function only encode one field:
type DataRows []struct {
mData interface{}
}
type DataColumns []struct {
mColumnName string
mColumnType int
mColumnPrecision int
mColumnScale int
}
type DataTables []struct {
mDataColumns DataColumns
mDataRows DataRows
mIndex int
}
type CFFDataSet struct {
mDataTables DataTables
mUser string
DBServer int
}
func main() {
ds := CFFDataSet{
mDataTables: DataTables{{
mDataColumns: DataColumns{{
mColumnName: "Test",
mColumnType: 1,
mColumnPrecision: 1,
mColumnScale: 1,
}},
mDataRows: DataRows{{
mData: "Test",
}},
mIndex: 0,
}},
mUser: "Teste",
DBServer: 2,
}
marchaled, _ := json.Marshal(ds)
fmt.Println(string(marchaled))
}
is returning
$ go run getrest.go
{"DBServer":2}
Can someone give me a hint why not this working ?
All your other fields are unexported (like private in other languages) and the unmarshaller can't access them. This is designated by the case of the first letter in the field name, needs to be uppercase.
For reference, here's an example using a field name on your struct that differs from the json's field name;
var jsonBlob = []byte(`[
{"Name": "Platypus", "Purchase": "Monotremata"},
{"Name": "Quoll", "Purchase": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string `json:"Purchase"`
}
var animals []Animal
err := json.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
https://play.golang.org/p/iJqaXQY7Ch
In Python I can make any class support indexing by overriding __getitem__ like so:
class Test:
def __getitem__(self, key):
return self.data[key]
Does Dart have a similar construct for this?
Assuming that the __getitem__ thing lets you use the "indexing" syntax (object[index]), yes, Dart lets you do the same by defining operator []. Example:
class Test {
var data = {
"a": 1,
"b": 2
};
operator [](index) => data[index];
}
main() {
var t = new Test();
print(t["a"]);
print(t["b"]);
}
You can also define the "opposite" operator []=:
class Test {
Map data = {
"a": 1,
"b": 2
};
operator [](index) => data[index];
operator []=(index, value) { data[index] = value; }
}
main() {
var t = new Test();
print(t["a"]);
print(t["b"]);
t["c"] = 3;
print(t["c"]);
}
I have a collection of events that look like
{
_id: BSONID
name: "event_name",
values: {a: 10, b: 1000, c: 50}
}
I'm trying to use mapReduce them using
map = function() {
return emit([this.name, this.values['a']], this.values['b']);
}
reduce = function(key, values) {
// stuff
}
collection.mapReduce(map, reduce, { out: { inline: 1 } }, callback);
However, I would like to be able to dynamically change which values I map against. In essence, I'd like to have
var key = 'a';
var value = 'b';
map = function ()
{
return emit([this.name, this.values[key]], this.values[value]);
}
The problem is that the execution context isn't passed to mongodb. Any solution that doesn't rely on using string for functions?
Yes, you can pass a "scope" variable to MapReduce:
scope = {key : "a", value : "b"};
collection.mapReduce(map, reduce, {scope : scope, out: { inline: 1 } }, callback);