I am having trouble adding elements to a referenced vector of a map - dictionary

EDIT: Forgot to mention that my programming language is C++, and my IDE is Qt Creator.
I don't understand why I am having trouble adding elements to a referenced vector of a map (i.e. sometimes it works and sometimes it fails).
For example:
class C_html4_tags {
public:
C_html4_tags();
//.......
typedef std::vector<S_html_attr_value> TYPE_attr_values;
//.....
};
//...
C_html4_tags::C_html4_tags() {
//........
map<S_browser, TYPE_attr_values> attr_supported_attr_values_map;
S_browser dummy_browser; //a fake browser key for referencing a fully Html 4.01-compliant supported attr values list
dummy_browser.name = "Dummy";
//.....
TYPE_attr_values& attr_supported_attr_values = attr_supported_attr_values_map[dummy_browser];
//......
**attr_supported_attr_values = attr_supported_attr_values_map[dummy_browser];**
//...
**attr_supported_attr_values.clear();
attr_supported_attr_values_map.clear();**
//......
**attr_supported_attr_values = attr_supported_attr_values_map[dummy_browser];**
//...
**attr_supported_attr_values.clear();
attr_supported_attr_values_map.clear();**
}
I do the bolded lines multiple times with a bunch of different attributes, with very little difference between them, without a problem until reaching this one attribute (a_tabindex_attr), in which the IDE doesn't report anything wrong when running it normally (except "The program has unexpectedly finished." However, when debugging it, it now reports:
Signal received
The inferior stopped because it received a signal from the Operating
System.
Signal name : SIGSEGV Signal meaning : Segmentation fault
And the backtrace points to the attribute I mentioned above, on the line of code which does this:
attr_supported_attr_values.clear();
Now, after adding some debugging cout lines to the code, I learned that what's happening is, for some reason, even after doing:
attr_supported_attr_values.push_back(attr_value);
the vector object which is the returned mapped value of:
attr_supported_attr_values = attr_supported_attr_values_map[dummy_browser];
is not actually being changed when I push_back an S_html_attr_value object to the referenced vector. Now, I don't why that is, since I do pretty much the exact same thing in a bunch of other attributes' code before this one, without any problem, but for some reason now, on this one, it ain't adding the object to attr_supported_attr_values (which is a reference to the returned mapped value of 'dummy_browser'). And I know this for a fact, because I outputted the size of the internal mapped value object of the map (using an iterator for the map), and it was 0 after the call to push_back(). However, what is even more odd is, I ALSO outputted attr_supported_attr_values.size() after the call to push_back(), and that was 1! Now how could that be since they're both supposed to be the same object??
Note:
The full code of what I'm talking about is below (or at least the attribute code, minus the debugging statements...):
//a_tabindex_attr:
attr_desc = "Specifies the position of an <a> element in the\n"
"tabbing order for the current document.\n"
"The tabbing order defines the order in which\n"
"elements will receive focus when navigated by\n"
"the user via the keyboard. The tabbing order\n"
"may include elements nested within other elements.\n"
"Elements that may receive focus based on tabindex\n"
"adhere to the following rules:\n\n"
"1. Those elements that support this attribute and\n"
"assign a positive value to it are navigated first.\n"
"Navigation proceeds from the element with the\n"
"lowest tabindex value to the element with the\n"
"highest value. Values need not be sequential\n"
"nor must they begin with any particular value.\n"
"Elements that have identical tabindex values\n"
"should be navigated in the order they appear\n"
"in the character stream.\n"
"2. Those elements that do not support this\n"
"attribute or support it and assign it a value\n"
"of \"0\" are navigated next. These elements are\n"
"navigated in the order they appear in the\n"
"character stream.\n"
"3. Elements that are disabled do not participate\n"
"in the tabbing order.";
attr_supported_attr_values = attr_supported_attr_values_map[dummy_browser];
attr_value_desc = "A number you specify for the tab index/order.\n"
"It must be a value between 0 and 32767.";
attr_value_content = "<i>number</i>";
attr_value = C_html4_attributes_obj.getAttrValue(attr_value_desc, attr_value_content,
attr_value_supported_browsers,
attr_value_required, attr_value_deprecated,
attr_value_notes, attr_value_tips);
attr_value.is_relative = true;
attr_supported_attr_values.push_back(attr_value);
try {
N_init_class_members::initAttr(C_html4_attributes::attr_tabindex, a_tabindex_attr, attr_desc,
attr_supported_browsers, attr_supported_attr_values_map, attr_required,
attr_deprecated, attr_notes, attr_tips);
}
catch (const char* exc) {
string exc_str = "Error! Call to N_init_class_members::initAttr() from\n"
"constructor of C_html4_tags class. That function\n"
"reported the following exception:\n\n";
exc_str += exc;
throw (exc_str.c_str()); //re-throw exception
}
a_tabindex_attr.is_standard_attr = true;
a_tabindex_attr.is_optional_attr = true;
//cleanup from attribute operations so we can begin working on the next attribute:
C_html4_attributes_obj.clear(); //wipes the slate clean for all the supported attributes' properties except content
attr_desc.clear();
attr_supported_attr_values.clear();
attr_supported_attr_values_map.clear();
attr_value_desc.clear();
attr_value_content.clear();

Related

.Net Core 3 Preview SequenceReader Length Delimited Parsing

I'm trying to use SequenceReader<T> in .Net Core Preview 8 to parse Guacamole Protocol network traffic.
The traffic might look as follows:
5.error,14.some text here,1.0;
This is a single error instruction. There are 3 fields:
OpCode = error
Reason = some text here
Status = 0 (see Status Codes)
The fields are comma delimited (semi-colon terminated), but they also have the length prefixed on each field. I presume that's so that you could parse something like:
5.error,24.some, text, with, commas,1.0;
To produce Reason = some, text, with, commas.
Simple comma delimited parsing is simple enough to do (with or without SequenceReader). However, to utilise the length I've tried the following:
public static bool TryGetNextElement(this ref SerializationContext context, out ReadOnlySequence<byte> element)
{
element = default;
var start = context.Reader.Position;
if (!context.Reader.TryReadTo(out ReadOnlySequence<byte> lengthSlice, Utf8Bytes.Period, advancePastDelimiter: true))
return false;
if (!lengthSlice.TryGetInt(out var length))
return false;
context.Reader.Advance(length);
element = context.Reader.Sequence.Slice(start, context.Reader.Position);
return true;
}
Based on my understanding of the initial proposal, this should work, though also could be simplified I think because some of the methods in the proposal make life a bit easier than that which is available in .Net Core Preview 8.
However, the problem with this code is that the SequenceReader does not seem to Advance as I would expect. It's Position and Consumed properties remain unchanged when advancing, so the element I slice at the end is always an empty sequence.
What do I need to do in order to parse this protocol correctly?
I'm guessing that .Reader here is a property; this is important because SequenceReader<T> is a mutable struct, but every time you access .SomeProperty you are working with an isolated copy of the reader. It is fine to hide it behind a property, but you'd need to make sure you work with a local and then push back when complete, i.e.
var reader = context.Reader;
var start = reader.Position;
if (!reader.TryReadTo(out ReadOnlySequence<byte> lengthSlice,
Utf8Bytes.Period, advancePastDelimiter: true))
return false;
if (!lengthSlice.TryGetInt(out var length))
return false;
reader.Advance(length);
element = reader.Sequence.Slice(start, reader.Position);
context.Reader = reader; // update position
return true;
Note that a nice feature of this is that in the failure cases (return false), you won't have changed the state yet, because you've only been mutating your local standalone clone.
You could also consider a ref-return property for .Reader.

Getting char value from ComboBox in JavaFX

I need to get the selected value in a combobox as of a data type char. I know how to get the selected item it's the conversion which I've got stuck on. Any suggestions?
This is the combobox and it content:
idCharCombo = new ComboBox<>();
idCharCombo.getItems().addAll("A","B","G","H","L","M","P","Z");
Now i will be using this data in a method which passes an int and a char (bellow is the use of the method where the second element is still an object rather than a char):
if (checkStaffMemberById(Integer.parseInt(idNoTxtFld.getText()), idCharCombo.getValue()) == true){
AlertBox.display("ID Validation", "ERROR! ID Already Exists.");
hope i arranged adequately
Since your combo box appears to only hold single-character strings, and you want to treat them as chars, the most obvious thing to do is to use a ComboBox<Character> instead of a ComboBox<String>. I.e. replace your declaration, which presumably looks like
ComboBox<String> idCharCombo ;
with
ComboBox<Character> idCharCombo ;
and then you can do
idCharCombo.getItems().addAll('A','B','G','H','L','M','P','Z');
Then
idCharCombo.getValue()
will return a Character which will be autounboxed to a char as needed, so your method call
checkStaffMemberById(Integer.parseInt(idNoTxtFld.getText()), idCharCombo.getValue())
should work as-is.

How does the assignment part work in the following line of code in Angular2?

I am learning from the project angular2-rxjs-chat application ong github. In the code here there is a line of code given below:
threads[message.thread.id] = threads[message.thread.id] ||
message.thread;
where threads has earlier been defined on line 29 in the code as shown below:
let threads: {[key: string]: Thread} = {};
The comments in the code states that "store the message's thread in our acuuculator 'threads'. I need a little bit explanation of how does the assignment works on line 31 as on both sides of the assignment operator we have the same thing i.e., threads[message.thread.id]. If the statement on line 31 was like
(threads[message.thread.id] = message.thread;)
then I would explain it as a value is being assigned to a key in the map "threads". But I don't understand the full line.
This means if threads[message.thread.id] already has a value then keep it, otherwise set the value to meassage.thread.
If the part before || evaluates to a value that is truthy (not null, undefined, false, ...)then the part after||is not evaluated and the result from the part before||is returned otherwise the result from the expression after||` is returned.
You could also write it as
if(!threads[message.thread.id]) {
threads[message.thread.id] = message.thread;
}

"Down arrow" moves cursor to end of line - how to turn it off

In IPython Notebook / Jupyter, arrow up/down keystrokes within a cell are handled by CodeMirror (as far as I can tell). I use these actions a lot (re-bound to control-p / control-n) to move between cells; but at the end of every cell, the cursor moves to end of line first before jumping to the next cell. This is counter-intuitive and, to me, rather distracting.
Is there any way to configure CodeMirror to make this move down to be just that - a move down?
Thanks!
The moving-to-next-cell behavior is defined by IPython wrapper code, which probably checks whether the cursor is at the end of the current cell, and overrides the default CodeMirror behavior in that case. You'll have to find that handler and somehow replace it with one that checks whether the cursor is on the last line. (I don't know much about IPython, only about CodeMirror, so I can't point you at the proper way to find and override the relevant code. They might have bound the Down key, or they might have overridden the goLineDown command.)
Knowing that I wasn't alone in wanting to skip the "going to end of line" behavior when going down from the last line of a code cell, I investigated that behavior and found out that:
it's CodeMirror that goes to the end of line when you type down in the last line of a code cell (file: codemirror.js ; "methods": findPosV and moveV)
and it's IPython that decides what to do with the "down" event after it has been handled by CodeMirror (file: cell.js ; class: Cell ; method: handle_codemirror_keyevent) ; looking at the code, I saw that IPython ignores the event when not at the last character of the last line.
This essentially confirms Marijin's answer.
The primary goal being to jump to the next cell, I think there's no need to prevent CodeMirror from going to the end of that line. The point is to force IPython to handle the event anyway.
My solution was to change the code from Cell.prototype.handle_codemirror_keyevent to this:
Cell.prototype.handle_codemirror_keyevent = function (editor, event) {
var shortcuts = this.keyboard_manager.edit_shortcuts;
var cur = editor.getCursor();
if((cur.line !== 0) && event.keyCode === 38){
// going up, but not from the first line
// don't do anything more with the event
event._ipkmIgnore = true;
}
var nLastLine = editor.lastLine();
if ((event.keyCode === 40) &&
((cur.line !== nLastLine))
) {
// going down, but not from the last line
// don't do anything more with the event
event._ipkmIgnore = true;
}
// if this is an edit_shortcuts shortcut, the global keyboard/shortcut
// manager will handle it
if (shortcuts.handles(event)) {
return true;
}
return false;
};
This code provides the desired behavior for the "down-arrow" key (almost: the cursor still goes to the end of the line, except that we don't see it, as we're already in another cell at that point), and also handles the "up-arrow" key similarly.
To modify the handle_codemirror_keyevent prototype, you have two possibilities:
You edit the cell.js file and change the code of the prototype to the code I gave above. The file is in <python>/Lib/site-packages/IPython/html/static/notebook/js or something similar depending on you distro
Much better, after the page is loaded, you change that prototype dynamically by doing this:
IPython.Cell.prototype.handle_codemirror_keyevent = function (editor, event) {
<same code as above>
};
You can do that in your custom.js for example, or create an extension to do it (that's what I did).

issue with paginated reading datastore

I have a weired issue, I can't believe such a common feature could be broken (the error is certainely on my side), but I can't find how to make it work. I want to use the cursor from datastore to get paginated results, I keep getting all of them whatever i do
FetchOptions fetchOptions = FetchOptions.Builder.withChunkSize(5).prefetchSize(6);
String datastoreCursor = filter.getDatastoreCursor();
if (datastoreCursor != null) {
fetchOptions = fetchOptions.startCursor(Cursor.fromWebSafeString(datastoreCursor));
}
QueryResultList<Entity> result = preparedQuery.asQueryResultList(fetchOptions);
ArrayList<Product> productList = new ArrayList<Product>();
// int count = 0;
for (Entity entity : result) {
// if (++count == PRODUCTS_PER_PAGE)
// break;
Key key = entity.getKey();
productList.add(populateProduct(key.getId(), true, entity));
}
toReturn.setDatastoreCursor(result.getCursor());
Also if I don't read the rows (uncomment the lines with counter) and get the cursor the resulting cursor is the same. I thought it might bring me back to the last read element under the datastabase cursor (thinking result.getCursor() reflects the state of the db cursor)
I'm getting a cursor with this value E-ABAOsB8gEQbW9kaWZpY2F0aW9uRGF0ZfoBCQiIjsfAmKm_AuwBggIhagljaGF0YW1vamVyFAsSB1Byb2R1Y3QYgICAgICosgsMFA that points to no more elements (I have 23 elements for my test that I all receive from the first query)
When you use a QueryResultList, the requested cursor will always point to the end of the list. As specified by the javadoc of QueryResultList#getCursor:
Gets a Cursor that points to the result immediately after the last one in this list.
Even though you provide a prefetch and chunk size, The entire result list will still have all of your results since you have not specified a limit. Thus, the expected cursor is the cursor after the final element.
If you only want a specific number of entities per page, you should set a limit on the FetchOptions using the limit method. Then when you call getCursor(), you'll get a cursor at the end of your page, as opposed to the end of your dataset.
Instead, you could also use a QueryResultIterator. Unlike the QueryResultList, calling getCursor on a QueryResultIterator will result in the cursor that points after the last entity retrieved by calling .next() (javadoc).

Resources