moving objects in NSMutableArray without changing array size - nsmutablearray

I have a 'MutableArray' that I want to edit by moving different objects in it up and down the index via the method shown here: NSMutablearray move object from index to index.
My problem is that Xcode first takes care of the 'removeObjectAtIndex' method before the 'insertObject:atIndex:' so the array actually shrinks in size which makes certain transitions impossible. An example would be if my 'array' has 3 members and I change the third member's index from 2 to 2 so nothing should happen but actually the app crashes because after the removal the index bound is now [0,1].
Below is the code I am using to implement the move in array, I also get a Parse Issue: Expected identifier error from the compiler at the 'if' statement right behind the queue.count. Any help on both would be much appreciated.
-(void)makeRankChange:(NSMutableArray *)queue{
for (int queueCount =0; queueCount<queue.count; queueCount++) {
QueueMember *member = [queue objectAtIndex:queueCount];
if (member.rank != queueCount+1) {
if ([0<member.rank] && [member.rank < [queue.count(expected identifier here:Im not sure why)]]) {
[queue insertObject:member atIndex:member.rank-1];
[queue removeObjectAtIndex:queueCount];
}
}
}
}

How about replacing the value at the index:
[queue replaceObjectAtIndex:queueCount withObject:member];
The error is most likely from the '[' brackets in the if statement

Related

Populating a std::vector map using the operator[]?

Am I overcomplicating this? Since I recently learned that with std::vector you can use the [] operator and it will add the entry if missing.
I have something a little more detailed:
using WeekendFutureItemHistMap = std::map<CString, std::vector<COleDateTime>>;
using WeekendFutureHistMap = std::map<WeekendHistAssign, WeekendFutureItemHistMap>;
WeekendHistAssign is just an enum class.
In my function I am populating it this way:
if (m_mapScheduleFutureHist[eHistAssign].find(strName) != m_mapScheduleFutureHist[eHistAssign].end())
m_mapScheduleFutureHist[eHistAssign][strName].push_back(datAssign);
else
{
m_mapScheduleFutureHist[eHistAssign].emplace(strName, std::vector<COleDateTime>{datAssign});
}
According to the std::vector operator[] it states:
Returns a reference to the element at specified location pos. No bounds checking is performed.
As a result it seemed the right thing to do is test for the existing first as done.
Did I overcomplicate it?
std::vector<int> v;
v.resize(100);
v[0]=1;
v[1]=10;
...

Change all list items during iteration

Problem
I need to change all list items during a loop. Is it possible?
Code
List<WebElement> elements = driver.findElements(By.xpath('//*[#id="id1"]//tr[td/a]'))
elements.eachWithIndex { element, index ->
...
if(...) {
...
i = index+1
elements = driver.findElements(By.xpath('//*[#id="id1"]//tr[td/a][position()>' + i + ']')) // new list content which must be use by loop
}
}
However, new list is not used by the loop.
Can you help and explain me why?
Thanks
Regards
EDIT 1
I need to retrieve element everytime.
List<WebElement> elements = driver.findElements(By.xpath('//*[#id="dzA26"]//tr[td/a]'))
for(int i = 1; i <= elements.size(); i++) {
WebElement element = driver.findElement(By.xpath('//*[#id="dzA26"]//tr[td/a][' + i + ']'))
...
}
So first of all while iterating over a List, changing or removing elements is not safe to do. It can be possible, but you should avoid it.
That's because you are trying to change the element it is currently iterating at. So the Iterator behind the '.each' closure gets confused and doesn't know where to go on after the current iteration.
If you have to change all elements with the same operation, you could use the List.collect() closure provided by groovy, which will return whatever you like into a new List.
e.g.:
List<WebElement> elements = elements.collect { element ->
return element.doSomething()
}
Edit 1
After your update there is a new Problem, because it seems like you always want to update all Elements int the List.
So why don't you create the List inside the Loop, fill it, and use it, then go to the next iteration.
e.g.:
for(int i = 0;i < threshold; i++) {
List<WebElement> elements = useMethodToRetrieveElementsFori(i);
elements.each {
// Do whatever has to be done with this element.
}
}
Or after looking at it a little longer, it seems obvious to use code reflection at that point. Because you want to dig deeper into the WebElements, you should call a method that calls itself if it needs to go one step further. With your idea, you'd be stuck in an endless loop.
Or we are missing the the whole point of the question.

Token empty when matching grammar although rule matched

So my rule is
/* Addition and subtraction have the lowest precedence. */
additionExp returns [double value]
: m1=multiplyExp {$value = $m1.value;}
( op=AddOp m2=multiplyExp )* {
if($op != null){ // test if matched
if($op.text == "+" ){
$value += $m2.value;
}else{
$value -= $m2.value;
}
}
}
;
AddOp : '+' | '-' ;
My test ist 3 + 4 but op.text always returns NULL and never a char.
Does anyone know how I can test for the value of AddOp?
In the example from ANTLR4 Actions and Attributes it should work:
stat: ID '=' INT ';'
{
if ( !$block::symbols.contains($ID.text) ) {
System.err.println("undefined variable: "+$ID.text);
}
}
| block
;
Are you sure $op.text is always null? Your comparison appears to check for $op.text=="+" rather than checking for null.
I always start these answers with a suggestion that you migrate all of your action code to listeners and/or visitors when using ANTLR 4. It will clean up your grammar and greatly simplify long-term maintenance of your code.
This is probably the primary problem here: Comparing String objects in Java should be performed using equals: "+".equals($op.text). Notice that I used this ordering to guarantee that you never get a NullPointerException, even if $op.text is null.
I recommend removing the op= label and referencing $AddOp instead.
When you switch to using listeners and visitors, removing the explicit label will marginally reduce the size of the parse tree.
(Only relevant to advanced users) In some edge cases involving syntax errors, labels may not be assigned while the object still exists in the parse tree. In particular, this can happen when a label is assigned to a rule reference (your op label is assigned to a token reference), and an error appears within the labeled rule. If you reference the context object via the automatically generated methods in the listener/visitor, the instances will be available even when the labels weren't assigned, improving your ability to report details of some errors.

string 'w32' == 0 evaluates to true in php. huh?

So I was getting a notice in my php while creating a google product feed.
The notice was
"The following php notice has occurred 4989 times on the _ site today:
PHP Notice: Undefined index: 0 in /xxx/Status.php on line 583"
This was the code in that class
public function inStockLocally($productcode)
{
if($this->_status[$productcode]['status'] == self::IN_STOCK) {
return $this->_status[$productcode]['in_stock_local'];
}
return false;
}
The function was getting a $productcode = 0, but the productcode was infact 'w32', so the key didn't exist.
up the stack where the function was being called I put this in, in order to break on the troublesome product.
if ($productcode == 0) {
$test = 'breakhere';
}
Using netbeans and firebug, it broke on the line when $productcode = 'w32'
So my question is why does 'w32' == 0 evaluate to true?
It is also evaluating to true with other similar structure codes like 'h94'.
Any help would be appreciated as no one in the department can figure out why this is happening.
I guess I didn't put enough info in the q. Two things going on.
1. 'w32' converted to a number = 0 for some reason. 2. [0] is being inserted as my key in the array when the productcode has the structure 'x##';
I'm a little new here, so pardon if this isn't the answer you were expecting, but PHP does a lot of automatic type conversion. So any string that doesn't start with a numeric character (0..9, +, -, etc) will evaluate to zero.
"If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. "
http://php.net/manual/en/language.operators.comparison.php
Additionally, I suppose you have an indexed array, although you expect it to be an associative array:
The array() function is used to create an array.
In PHP, there are three types of arrays:
Indexed arrays - Arrays with numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
Syntax
Syntax for indexed arrays:
array(value1,value2,value3,etc.);
Syntax for associative arrays:
array(key=>value,key=>value,key=>value,etc.);

Predicate syntax when partitioning a vector of pointers (C++)

I have a vector of pointers to objects. I'd like to remove objects from this vector according to an attribute that's reported by a member function.
I'm trying to follow a nice example I found on how to delete certain pointers (and their associated objects) from the vector. The basic idea is to partition the vector, delete the chosen objects, and then delete the pointers to those objects. Below is the example (from Dr. Dobbs):
vector<Object *> v ;
v.push_back( new Object( ... ) ) ;
...
vector<Object *>::iterator last =
partition( v.begin(), v.end(), not1(predicate()) ) ;
for( vector<Object *>::iterator i = last ; i != v.end() ; ++i )
{
delete *i ;
}
v.erase( last, v.end() ) ;
I'm stumped on the proper syntax for the predicate. My objects are of class Strain, and my vector is vector< Strain * > liveStrains. The predicate should be the Strain member function isExtinct(). The following doesn't work:
vector< Strain * >::iterator last = partition( liveStrains.begin(), liveStrains.end(), not1(std::mem_fun_ref(&Strain::isExtinct)) );
I can see that I am trying to invoke a member function on a pointer to the object rather than the object itself. To get around this, tried changing the & to * (I'm obviously a newbie), and I tried creating a member function for the class Simulation that does the liveStrains updating in a member function. I'm not sure it's worth going into the details of what didn't work. I'm severely confused by the syntactical options available, or if what I'm trying to do is even allowed.
Thanks in advance for any help.
The solution is to use std::mem_fun, which is made for pointers to objects, rather than std::mem_fun_ref.

Resources