nlohmann json has a string member called name, how can I check it is null or valid string - linux

I know that I have this:
json var["thirdName"].get<std::string>().c_str();
It is used in C++. The protocol says this member is mandatory, but lots of people don't have third name.
I got exception if it is
nullptr;
, because I can say
var["thirdName"] = nullptr;
How can I easily check if it is valid or not?
I've found only one very complex form.

You can use the count method:
if (var.count("thirdName") > 0) {
...
}
Personally, I would omit the > 0:
if (var.count("thirdName")) {
...
}

Related

get attributes, even if they do not exist

Please don't hate me, yes I want to do something really stupid.
I want to get null on every attribute if it does not exist. I found out that I can create the propertyMissing method:
class User {
String name = "A"
}
Object.metaClass.propertyMissing() {
null
}
u = new User();
println u?.name
println u?.namee
This prints:
A
null
Now I have the "great" Hybris system in my back :D
If I add the propertyMissing part on top of my script and run this in the Hybris groovy console, I still get the MissingPropertyException.
Is there another way to avoid the MissingPropertyException exception without having to work with hundreds of try catch? (or hundreds of println u?.namee ? u.namee : null isn't working)
/Edit: 1
I have the following use case (for the Hybris system):
I want to get all necessary information in a dynamic output from some pages. Why dynamic? Some page components have the attribute headline other teaserHeadline and some other title. To avoid to create each time an try catch or if else, I created a function which loops through possible attributes and if it's null it skips that one. For that I need to return null on attributes which doesn't exist.
Here is an example which should work, but it doesn't (don't run it on your live system):
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.search.SearchResult;
flexibleSearch = spring.getBean("flexibleSearchService")
FlexibleSearchQuery query = new FlexibleSearchQuery("select {pk} from {ContentPage}");
SearchResult searchResult = flexibleSearch.search(query);
def i = 0;
def max = 1;
searchResult.result.each { page ->
if (i < max) {
gatherCMSPageInformation(page)
}
i++;
}
def gatherCMSPageInformation(page) {
page.class.metaClass.propertyMissing() {
null
}
println page.title2
}
Weird thing is, that if I run it a few times in a small interval, it starts to work. But I can't overwrite "null" to something else like "a". Also I noticed, to overwrite the Object class isn't working at all in Hybris.
/Edit 2:
I noticed, that I'm fighting against the groovy cache. Just try the first example, change null with a and then try to change it again to b in the same context, without restarting the system.
Is there a way to clear the cache?
why don't you use the groovy elvis operator?
println u?.namee ?: null

Spotify API-Net ResumePlayback - Error With Code Example From Documentation

The documentation at Spotiy API_NET for ResumePlayback
gives the following example:
ErrorResponse error = _spotify.ResumePlayback(uris: new List<string> { "spotify:track:4iV5W9uYEdYUVa79Axb7Rh" });
When I try that code in C#, I get the following code error which prevents me building:
Error CS0121 The call is ambiguous between the following methods or properties: 'SpotifyWebAPI.ResumePlayback(string, string, List, int?)' and 'SpotifyWebAPI.ResumePlayback(string, string, List, string)'
Can anyone tell me what is wrong with this?
Also, what is the simplest way to simply resume the existing player at the point where it was paused?
Edit
#rene answered the first part of my question.
In regard to the second part, how to resume the existing player at the point where it was paused, I got the answer through the library's Github site, it's simply:
_spotify.ResumePlayback(offset: "")
The ResumePlayback method has two overloads that take these parameters:
ErrorResponse ResumePlayback(string deviceId = "",
string contextUri = "",
List<string> uris = null,
int? offset = null)
and
ErrorResponse ResumePlayback(string deviceId = "",
string contextUri = "",
List<string> uris = null,
string offset = "")
When the compiler comes across this line
ErrorResponse error = _spotify.ResumePlayback(
uris: new List<string> { "spotify:track:4iV5W9uYEdYUVa79Axb7Rh" });
it has to decide which ResumePlayback it is going to call and it doesn't want to take a guess or roll a dice.
It looks at which parameters are going to be provided and you only give it uris (that is the third parameter). It will assume the defaults for the other parameters. For both methods these defaults (null for strings or for the Nullable<int> (int?)) apply so the compiler can't decide which method it should bind to. It shows you an error.
Provide more parameters so the compiler can pick an unique overload.
ErrorResponse error = _spotify.ResumePlayback(
uris: new List<string> { "spotify:track:4iV5W9uYEdYUVa79Axb7Rh" }
,
offset: 0
);
Adding that named parameter offset and setting it to the int value of 0 is enough for the compiler to pick this overload to bind to:
ResumePlayback(string deviceId, string contextUri, List<string> uris, int? offset)

ANTLR4: getFirstChildWithType with a ParseTree

I've been playing around with ANTLR4, trying to convert an ANTLR3 project.
I have generated a lexer, a parser and a visitor class from an ANLTR4 grammar coming from the official repository. In the visitor, I am calling one of my classes using the ctx available from the visitor:
myFunction(ctx.getChild(0))
Then, in myFunction, I want to retrieve the first child having a specific type, so I tried doing:
final ParseTree classNameElement =
(ParseTree) ((GrammarAST) node).getFirstChildWithType(MyParser.IDENTIFIER);
where node is the argument of myFunction, thus a ParseTree. getFirstChildWithType seems to be available only in GrammarAST, hence the cast.
I am getting the error: cannot be cast to org.antlr.v4.tool.ast.GrammarAST
So maybe this is not possible as is and I must have missed something, but I want to find the first child having a specific type from a ParseTree.
Thank you!
Notice that GrammarAST is in the ANTLR tool hierarchy. With a generated parse-tree, you should be dealing exclusively with the runtime.
To search a parse-tree node for a child of a given type:
public ParseTree getFirstChildOfType(ParseTree node, int tokentype) {
for (int idx = 0; idx < node.getChildCount(); idx++) {
ParseTree child = node.getChild(idx);
if (child instanceof TerminalNode) {
Token token = (Token) child.getPayload();
if (token.getType() == tokentype) {
return child;
}
}
}
return null;
}
This will get the first direct, i.e., child terminal, of the given type. Will need to recurse into non-TerminalNodes if the absolute first of type is desired.
If the latter is actually the desired function, there may be a better/more direct use of parse-tree walker to obtain the desired overall goal.

how to retrieve nested properties in groovy

I'm wondering what is the best way to retrieve nested properties in Groovy, taking a given Object and arbitrary "property" String. I would like to something like this:
someGroovyObject.getProperty("property1.property2")
I've had a hard time finding an example of others wanting to do this, so maybe I'm not understanding some basic Groovy concept. It seems like there must be some elegant way to do this.
As reference, there is a feature in Wicket that is exactly what I'm looking for, called the PropertyResolver:
http://wicket.apache.org/apidocs/1.4/org/apache/wicket/util/lang/PropertyResolver.html
Any hints would be appreciated!
I don't know if Groovy has a built-in way to do this, but here are 2 solutions. Run this code in the Groovy Console to test it.
def getProperty(object, String property) {
property.tokenize('.').inject object, {obj, prop ->
obj[prop]
}
}
// Define some classes to use in the test
class Name {
String first
String second
}
class Person {
Name name
}
// Create an object to use in the test
Person person = new Person(name: new Name(first: 'Joe', second: 'Bloggs'))
// Run the test
assert 'Joe' == getProperty(person, 'name.first')
/////////////////////////////////////////
// Alternative Implementation
/////////////////////////////////////////
def evalProperty(object, String property) {
Eval.x(object, 'x.' + property)
}
// Test the alternative implementation
assert 'Bloggs' == evalProperty(person, 'name.second')
Groovy Beans let you access fields directly. You do not have to define getter/setter methods. They get generated for you. Whenever you access a bean property the getter/setter method is called internally. You can bypass this behavior by using the .# operator. See the following example:
class Person {
String name
Address address
List<Account> accounts = []
}
class Address {
String street
Integer zip
}
class Account {
String bankName
Long balance
}
def person = new Person(name: 'Richardson Heights', address: new Address(street: 'Baker Street', zip: 22222))
person.accounts << new Account(bankName: 'BOA', balance: 450)
person.accounts << new Account(bankName: 'CitiBank', balance: 300)
If you are not dealing with collections you can simply just call the field you want to access.
assert 'Richardson Heights' == person.name
assert 'Baker Street' == person.address.street
assert 22222 == person.address.zip
If you want to access a field within a collection you have to select the element:
assert 'BOA' == person.accounts[0].bankName
assert 300 == person.accounts[1].balance​​​​​​​​​
You can also use propertyMissing. This is what you might call Groovy's built-in method.
Declare this in your class:
def propertyMissing(String name) {
if (name.contains(".")) {
def (String propertyname, String subproperty) = name.tokenize(".")
if (this.hasProperty(propertyname) && this."$propertyname".hasProperty(subproperty)) {
return this."$propertyname"."$subproperty"
}
}
}
Then refer to your properties as desired:
def properties = "property1.property2"
assert someGroovyObject."$properties" == someValue
This is automatically recursive, and you don't have to explicitly call a method. This is only a getter, but you can define a second version with parameters to make a setter as well.
The downside is that, as far as I can tell, you can only define one version of propertyMissing, so you have to decide if dynamic path navigation is what you want to use it for.
See
https://stackoverflow.com/a/15632027/2015517
It uses ${} syntax that can be used as part of GString

DynamicMethod code unverifiable in .Net 4.0 (found ref 'this' pointer... expected ref '<>f__AnonymousType1`)

Was using this solution to convert anonymous types to dictionaries using reflection.emit. Was working fine until I changed to .Net 4.0 from 3.5.
Now, I'm getting the "System.Security.VerificationException: Operation could destabilize the runtime." error.
Converted the anonymously loaded dynamic method to one hosted in a dynamic assembly, saved it, then ran peverify.exe on it to find out what was wrong.
Got: [IL]: Error: [DynamicAssemblyExample.dll : MyDynamicType::MyMethod][offs
et 0x0000000D][found ref ('this' ptr) 'MyDynamicType'][expected ref '<>f__AnonymousType1`3[System.String,System.Int32,System.Byte]'] Unexpected type on the stac
k.
[IL]: Error: [DynamicAssemblyExample.dll : MyDynamicType::MyMethod][offs
et 0x0000000D] Method is not visible.
2 Error(s) Verifying DynamicAssemblyExample.dll
The code:
foreach (PropertyInfo property in itemType.GetProperties(attributes).Where(info => info.CanRead))
{
// load Dictionary (prepare for call later)
methIL.Emit(OpCodes.Ldloc_0);
// load key, i.e. name of the property
methIL.Emit(OpCodes.Ldstr, property.Name);
// load value of property to stack
methIL.Emit(OpCodes.Ldarg_0);
methIL.EmitCall(OpCodes.Callvirt, property.GetGetMethod(), null);
// perform boxing if necessary
if (property.PropertyType.IsValueType)
{
methIL.Emit(OpCodes.Box, property.PropertyType);
}
// stack at this point
// 1. string or null (value)
// 2. string (key)
// 3. dictionary
// ready to call dict.Add(key, value)
methIL.EmitCall(OpCodes.Callvirt, addMethod, null);
}
Is there a way to derefence the pointer to the actual property? Or do I have to cast it somehow? Any pointers?
Regards!
Sorry guys, made a mistake, since the actual dynamic method creates a delegate type that acts on the instance of the anonymous (or non-anonymous) type, the Ldarg_0 code is looking for a something that is not there in this debug implementation.
So I, changed it to OpCodes.Ldnull.
var attributes = BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy;
foreach (PropertyInfo property in itemType.GetProperties(attributes).Where(info => info.CanRead))
{
// load Dictionary (prepare for call later)
methIL.Emit(OpCodes.Ldloc_0);
// load key, i.e. name of the property
methIL.Emit(OpCodes.Ldstr, property.Name);
// load value of property to stack
methIL.Emit(OpCodes.Ldnull);
//methIL.Emit(OpCodes.Castclass, itemType);
methIL.EmitCall(OpCodes.Callvirt, property.GetGetMethod(), null);
// perform boxing if necessary
if (property.PropertyType.IsValueType)
{
methIL.Emit(OpCodes.Box, property.PropertyType);
}
// stack at this point
// 1. string or null (value)
// 2. string (key)
// 3. dictionary
// ready to call dict.Add(key, value)
methIL.EmitCall(OpCodes.Callvirt, addMethod, null);
}
But I still get a method not visible error after peverifying it. Is it that get methods for properties of anonymous types are not visible via reflection?
Just a suggestion, have you tried to rewrite the code that emits IL to actually write to the dictionary - i.e. no Reflection.Emit ? My bet is that the generated IL is not proper in some way, not the code that accesses the anonymous type.

Resources