Accessing elements of a map when using a variable key in Groovy - dictionary

I'm trying to replace some characters in a String From a map
Case 1
​map= ['O':'0', 'L':'1', 'Z':'2', 'E':'3']
"Hey".toUpperCase().toCharArray().each{
print map.get(it,it)
}
The result is
HEY
Case 2 : I dont use toCharArray()
"Hey".toUpperCase().each{
print map.get(it,it)
}
The result is like expected
H3Y
So I tried several alternatives when using toCharArray(), and the only way to access the value is to use map."$it"
Why i can only use map."$it" to access my map when using toCharArray() ?

Because you are trying to get a value from a map using a char whilst every key there are String, and they are not equals:
assert !'E'.equals('E' as char)
$it works because it is converted to String:
e = 'E' as char
assert "$e".toString().equals('E')
(Note the toString() is needed, otherwise the comparison will happen between String and GStringImpl which are not equals)

Related

Create correct Criteria Operator

Trying to create a Criteria.Parse operator when I have to convert the string field to an Int.
Operation fails at the follwing:
Message=Parser error at line 0, character 15: syntax error;
("Convert.ToInt16{FAILED HERE}(awayML)>130")
Here is my code:
XPCollection collection = new XPCollection(session1, typeof(TodaysGame), CriteriaOperator.Parse("Convert.ToInt16(awayML)>130"));
int ct = collection.Count;
How do I form the Criteria using the Convert.ToInt16 function?
Criteria operators have their own syntax to convert string literals to int values. You need to use them instead of system Convert.ToInt function:
Function
Description
Example
ToInt(Value)
Converts Value to an equivalent 32-bit signed integer.
ToInt([Value])
ToLong(Value)
Converts Value to an equivalent 64-bit signed integer.
ToLong([Value])
You can check the full reference of DevExpress criteria syntax here
The correct way to build a Criteria like that would be:
CriteriaOperator.Parse("ToInt([awayML]) > 130");

Swiftui: how do you assign the value in a "String?" object to a "String" object?

Swiftui dictionaries have the feature that the value returned by using key access is always of type "optional". For example, a dictionary that has type String keys and type String values is tricky to access because each returned value is of type optional.
An obvious need is to assign x=myDictionary[key] where you are trying to get the String of the dictionary "value" into the String variable x.
Well this is tricky because the String value is always returned as an Optional String, usually identified as type String?.
So how is it possible to convert the String?-type value returned by the dictionary access into a plain String-type that can be assigned to a plain String-type variable?
I guess the problem is that there is no way to know for sure that there exists a dictionary value for the key. The key used to access the dictionary could be anything so somehow you have to deal with that.
As described in #jnpdx answer to this SO question (How do you assign a String?-type object to a String-type variable?), there are at least three ways to convert a String? to a String:
import SwiftUI
var x: Double? = 6.0
var a = 2.0
if x != nil {
a = x!
}
if let b = x {
a = x!
}
a = x ?? 0.0
Two key concepts:
Check the optional to see if it is nil
if the optional is not equal to nil, then go ahead
In the first method above, "if x != nil" explicitly checks to make sure x is not nil be fore the closure is executed.
In the second method above, "if let a = b" will execute the closure as long as b is not equal to nil.
In the third method above, the "nil-coalescing" operator ?? is employed. If x=nil, then the default value after ?? is assigned to a.
The above code will run in a playground.
Besides the three methods above, there is at least one other method using "guard let" but I am uncertain of the syntax.
I believe that the three above methods also apply to variables other than String? and String.

Using Rascal MAP

I am trying to create an empty map, that will be then populated within a for loop. Not sure how to proceed in Rascal. For testing purpose, I tried:
rascal>map[int, list[int]] x;
ok
Though, when I try to populate "x" using:
rascal>x += (1, [1,2,3])
>>>>>>>;
>>>>>>>;
^ Parse error here
I got a parse error.
To start, it would be best to assign it an initial value. You don't have to do this at the console, but this is required if you declare the variable inside a script. Also, if you are going to use +=, it has to already have an assigned value.
rascal>map[int,list[int]] x = ( );
map[int, list[int]]: ()
Then, when you are adding items into the map, the key and the value are separated by a :, not by a ,, so you want something like this instead:
rascal>x += ( 1 : [1,2,3]);
map[int, list[int]]: (1:[1,2,3])
rascal>x[1];
list[int]: [1,2,3]
An easier way to do this is to use similar notation to the lookup shown just above:
rascal>x[1] = [1,2,3];
map[int, list[int]]: (1:[1,2,3])
Generally, if you are just setting the value for one key, or are assigning keys inside a loop, x[key] = value is better, += is better if you are adding two existing maps together and saving the result into one of them.
I also like this solution sometimes, where you instead of joining maps just update the value of a certain key:
m = ();
for (...whatever...) {
m[key]?[] += [1,2,3];
}
In this code, when the key is not yet present in the map, then it starts with the [] empty list and then concatenates [1,2,3] to it, or if the key is present already, let's say it's already at [1,2,3], then this will create [1,2,3,1,2,3] at the specific key in the map.

how to convert an array of characters to qstring?

I have an array -
char name[256];
sprintf(name, "hello://cert=prv:netid=%d:tsid=%d:pid=%d\0", 1010,1200, 1300);
QString private_data_string = name;
At the last offset of this string i.e. '\0',when I try to do the following.
while(private_data_string.at(offset) != ':' &&
private_data_string.at(offset) != ';' &&
private_data_string.at(offset).isNull() == false)
The application aborts. Looks like that the data pointer is also zero at the string '\'. How can I fix this?
QString doesn't contain terminating character as you expect that is why you are failing assertion out of bounds. This is proper approach:
while(offset<private_data_string.length() &&
private_data_string.at(offset) != ':' &&
private_data_string.at(offset) != ';') {
// ...
}
It looks like you are doing something strange. Looks like your question is wrong. You are asking how to fix your strange solution of some mysterious problem, instead explain what are you trying to do and then as a bonus: how did you try to solve it.
You need to know several facts:
Writing \0 at tge end of your string literal is not necessary. String literals are null-terminated by default. Literal "abc" will actually contain 4 characters including terminating null character. Your string literal has 2 null characters at its end.
You have used the default constructor QString(char*). There is no additional data about buffer's length, so QString reads characters from the buffer until it encounters first null character. It doesn't matter how many null characters are actually at the end. The null character is interpreted as a buffer end marker, not a part of the string.
When you have QString "abc", its size is 3 (it would be surprising to have another value). Null character is not a part of the string. QString::at function can be used for positions 0 <= position < size(). This is explicitly specified in the documentation. So it doesn't matter if QString's internal buffer is null-terminated or not. Either way, you don't have access to null terminator.
If you really want null character to be part of your data, you should use QByteArray instead of QString. It allows to specify buffer size on construction and can contain as many null characters as you want. However, when dealing with strings, it's usually not necessary.
You should use QString::arg instead of sprintf:
QString private_data_string =
QString("hello://cert=prv:netid=%1:tsid=%2:pid=%3")
.arg(netid).arg(tsid).arg(pid);
sprintf is unsafe and can overrun your fixed-size buffer if you're not careful. In C++ there's no good reason to use sprintf.
"A QString that has not been assigned to anything is null, i.e., both the length and data pointer is 0" - this has nothing to do with your situation because you have assigned a value to your string.

What's wrong with groovy math?

This seems quite bizarre to me and totally putting me on the side of people willing to use plain java. While writing a groovy based app I encountered such thing:
int filesDaily1 = (item.filesDaily ==~ /^[0-9]+$/) ?
Integer.parseInt(item.filesDaily) : item.filesDaily.substring(0, item.filesDaily.indexOf('.'))
def filesDaily = (item.filesDaily ==~ /^[0-9]+$/) ?
Integer.parseInt(item.filesDaily) : item.filesDaily.substring(0, item.filesDaily.indexOf('.'))
So, knowing that item.filesDaily is a String with value '1..*' how can it possibly be, that filesDaily1 is equal to 49 and filesDaily is equal to 1?
What's more is that when trying to do something like
int numOfExpectedEntries = filesDaily * item.daysToCheck
an exception is thrown saying that
Cannot cast object '111' with class 'java.lang.String' to class 'int'
pointing to that exact line of code with multiplication. How can that happen?
You're assigning this value to an int:
item.filesDaily.substring(0, item.filesDaily.indexOf('.'))
I'm guessing that Groovy is converting the single-character string "1" into the char '1' and then taking the Unicode value in the normal char-to-int conversion... so you end up with the value 49.
If you want to parse a string as a decimal number, use Integer.parseInt instead of a built-in conversion.
The difference between filesDaily1 and filesDaily here is that you've told Groovy that filesDaily1 is meant to be an int, so it's applying a conversion to int. I suspect that filesDaily is actually the string "1" in your test case.
I suspect you really just want to change the code to something like:
String text = (item.filesDaily ==~ /^[0-9]+$/) ? items.filesDaily :
item.filesDaily.substring(0, item.filesDaily.indexOf('.'))
Integer filesDaily = text.toInteger()
This is a bug in the groovy type conversion code.
int a = '1'
int b = '11'
return different results because different converters are used. In the example a will be 49 while b will be 11. Why?
The single-character-to-int conversion (using String.charAt(0)) has a higher precedence than the integer parser.
The bad news is that this happens for all single character strings. You can even do int a = 'A' which gives you 65.
As long as you have no way of knowing how long the string is, you must use Integer.parseInt() instead of relying on the automatic type conversion.

Resources