I have a mongodb collection with the following document:
{
"_id" : ObjectId("5c879a2f277d8132d6707792"),
"a" : "133",
"b" : "daisy",
"c" : "abc"
}
When I run the following mongocxx code:
auto r = client["DB"]["Collection"].find_one({}).value().view();
isREmpty = r.empty();
rLength = r.length();
isOneInR = r.begin() == r.end();
for (bsoncxx::document::element ele : r) {
std::cout << "Got key" << std::endl;
}
I get isREmpty = false, rLength = 99, isOneInR = true and no output saying Got key.
I was expecting the print of "Got key" because one document returned from find_one.
Why isn't it showing?
You are viewing freed memory. The call to .value() creates a temporary bsoncxx::value object. You then get a view into that temporary object with .view() and attempt to examine the data, but it is too late.
What you want to do instead is capture the cursor returned by find_one:
auto cursor = client["DB"]["Collection"].find_one({});
Please see the examples for more details, but here is a quick example: https://github.com/mongodb/mongo-cxx-driver/blob/master/examples/mongocxx/query.cpp#L43
Lifetime management in the C++ driver requires attention. Please read the doc comments for the methods you use, as they will almost always describe the rules you must follow.
Related
I want to parse a config file which has information like:
[MY_WINDOW_0]
Address = 0xA0B0C0D0
Size = 0x100
Type = cpu0
[MY_WINDOW_1]
Address = 0xB0C0D0A0
Size = 0x200
Type = cpu0
[MY_WINDOW_2]
Address = 0xC0D0A0B0
Size = 0x100
Type = cpu1
into a LUA table as follows
CPU_TRACE_WINDOWS =
{
["cpu0"] = {{address = 0xA0B0C0D0, size = 0x100},{address = 0xB0C0D0A0, size = 0x200},}
["cpu1"] = {{address = 0xC0D0A0B0, size = 0x100},...}
}
I tried my best with some basic LUA string manipulation functions but couldn't get the output that I'm looking for due to repetition of strings in each sections like 'Address',' Size', 'Type' etc. Also my actual config file is huge with 20 such sections.
I got so far, this is basically one section of the code, rest would be just repetition of the logic.
OriginalConfigFile = "test.cfg"
os.execute("cls")
CPU_TRACE_WINDOWS = {}
local bus
for line in io.lines(OriginalConfigFile) do
if string.find(line, "Type") ~= nil then
bus = string.gsub(line, "%a=%a", "")
k,v = string.match(bus, "(%w+) = (%w+)")
table.insert(CPU_TRACE_WINDOWS, v)
end
end
Basically I'm having trouble with coming up with the FINAL TABLE STRUCTURE that I need. v here is the different rvalues of the string "Type". I'm having issues with arranging it in the table. I'm currently working to find a solution but I thought I could ask for help meanwhile.
This should work for you. Just change the filename to wherever you have your config file stored.
f, Address, Size, Type = io.input("configfile"), "", "", ""
CPU_TRACE_WINDOWS = {}
for line in f:lines() do
if line:find("MY_WINDOW") then
Type = ""
Address = ""
Size = ""
elseif line:find("=") then
_G[line:match("^%a+")] = line:match("[%d%a]+$")
if line:match("Type") then
if not CPU_TRACE_WINDOWS[Type] then
CPU_TRACE_WINDOWS[Type] = {}
end
table.insert(CPU_TRACE_WINDOWS[Type], {address = Address, size = Size})
end
end
end
end
It searches for the MY_WINDOW phrase and resets the variable. If the table exists within CPU_TRACE_WINDOWS, then it just appends a new table value, otherwise it just creates it. Note that this is dependent upon Type always being the last entry. If it switches up anywhere, then it will not have all the required information. There may be a cleaner way to do it, but this works (tested on my end).
Edit: Whoops, forgot to change the variables in the middle there if MY_WINDOW matched. That needed to be corrected.
Edit 2: Cleaned up the redundancy with table.insert. Only need it once, just need to make sure the table is created first.
im trying to create a simple 2 functions text-file "database" with LUA. All i need is 2 Functions.
my db should look like that:
varName;varValue
JohnAge;18
JohnCity;Munich
LarissaAge;21
LarissaCity;Berlin
In fact im not stuck to any format! I just don't have a way to save data longterm in my lua enviroment and i need to find a workaround. So if you already have a
similiar solution at hand, please feel free to throw it at me. Thank you very much
Function WriteToDB(varName, varValue)
If database.text contains a line that starts with varName
replace whatever comes after seperator ";" with varValue (but dont go into the next line)
Function ReadFromDB(varName)
If database.text contains a line that starts with varName
take whatever comes after the seperator ";" and return that (but dont go into the next line)
elseif not found print("error")
Save the data as Lua code that builds a table:
return {
JohnAge = 18,
JohnCity = "Munich",
LarissaAge = 21,
LarissaCity = "Berlin",
}
Or better yet
return {
["John"] = {Age = 18, City = "Munich"},
["Larissa"] = {Age = 21, City = "Berlin"},
}
Load the data with
db = dofile"db.lua"
Access the data with
print(db["Larissa"].Age)
or
print(db[name].Age)
I have a variable in groovy like below:
project.Map
{
time.'1 1 * ?' = ['T1']
time.'2 1 * ?' = ['T2']
templates.'T1' = ['Z','X','Y']
templates.'T2' = ['Q']
}
Sorry but I am new to groovy ,when i try to access the individual
variable values in project.map how do i access them
i tried something like below
log.info(grailsApplication.config.project.Map.time[1])
log.info(grailsApplication.config.project.Map.get('time.'2 1 * ?'' ))
log.info(grailsApplication.config.project.Map.get('time[0]' ))
log.info(grailsApplication.config.project.Map.time.get('1 1 * ?'))
but they all print null value or object references.how do i access values for
time and templates both within a for loop and without it.
please see http://grails.org/doc/latest/guide/conf.html#config for the ways the config is allowed to nest. your outer syntax is especially mentioned to not be allowed:
However, you can't nest after using the dot notation. In other words, this won't work:
// Won't work!
foo.bar {
hello = "world"
good = "bye"
}
You have to write it as
project { Map { ... } }
The inner dotted parts (with the assignment) are ok (according to the doc)
background:
I am trying to teach myself Lua and I am having difficulty understanding why a table is being considered nil when it has data inside it. Can anyone break it down for me why I am getting this error message from the code snippet below? It is one of my first programs and i really need to get these few concepts down before moving on to my real project. Thanks!
error message:
C:\Users\<user>\Desktop>lua luaCrap.lua
lua: luaCrap.lua:7: attempt to call global 'entry' (a nil value)
stack traceback:
luaCrap.lua:7: in main chunk
[C]: ?
code:
--this creates the function to print
function fwrite (fmt, ...)
return io.write(string.format(fmt, unpack(arg)))
end
--this is my table of strings to print
entry{
title = "test",
org = "org",
url = "http://www.google.com/",
contact = "someone",
description = [[
test1
test2
test3]]
}
--this is to print the tables first value
fwrite(entry[1])
--failed loop attempt to print table
-- for i = 1, #entry, 1 do
-- local entryPrint = entry[i] or 'Fail'
-- fwrite(entryPrint)
-- end
you are missing the assignment to entry.
you need to change the entry code to this:
entry =
{
title = "test",
org = "org",
url = "http://www.google.com/",
contact = "someone",
description = [[
test1
test2
test3]]
}
to clarify the error message, parens are assumed in certain contexts, like when you have a table directly following a label. the interpreter thinks you're trying to pass a table to a function called entry, which it can't find. it assumes you really meant this:
entry({title = "test", ...})
I have a fairly basic program that is intended to sort a list of numbers via a Linked List.
Where I am getting hung up is when the element needs to be inserted at the beginning of the list. Here is the chunk of code in question
Assume that root->x = 15 and assume that the user inputs 12 when prompted:
void addNode(node *root)
{
int check = 0; //To break the loop
node *current = root; //Starts at the head of the linked list
node *temp = new node;
cout << "Enter a value for x" << endl;
cin >> temp->x;
cin.ignore(100,'\n');
if(temp->x < root->x)
{
cout << "first" << endl;
temp->next=root;
root=temp;
cout << root->x << " " << root->next->x; //Displays 12 15, the correct response
}
But if, after running this function, I try
cout << root->x;
Back in main(), it displays 15 again. So the code
root=temp;
is being lost once I leave the function. Now other changes to *root, such as adding another element to the LL and pointing root->next to it, are being carried over.
Suggestions?
This because you are setting the local node *root variable, you are not modifying the original root but just the parameter passed on stack.
To fix it you need to use a reference to pointer, eg:
void addNode(node*& root)
or a pointer to pointer:
void addNode(node **root)