How does one convert Local<Name> to a string? - v8

So after being away awhile some things changed. I used to be able to do this:
void ObjectTemplateProxy::GetProperty(Local<String> hName, const PropertyCallbackInfo<Value>& info)
{
auto hStr = hName->ToString();
But now I need an isolate, and the parameter type changed to Local<Name>. Then I tried this:
auto hStr = hName->ToString(info.GetIsolate());
But this still doesn't work because hStr is null. It is null because, as it turns out, the name is actually a Symbol type and NOT String. I don't see any way to convert a symbol to a string, which I need to do to send the name to the C# CLR via P/Invoke to pull the value from a dictionary using string keys.

So, it would seem that there is a Name() function on the Symbol type that returns a String. I was looking for a function on the Symbol type and didn't find one (must have missed it). The code that worked was hName.As<Symbol>()->Name().As<String>();.
As noted below in the comments, Symbol() is not required to have a name, so beware!

Related

Alternate syntax on introspecting modules/classes/etc

I'm rewriting a framework from Perl5 to Perl6 for my work purposes. At some place I need to collect information from other modules/classes by executing a public sub they might provide; or they may not. So, it necessary to find out if the sub is present. This is not a big deal when a module is referenced directly (Foo::<&my-sub>) or by a symbolic name in a string (&::("Foo")::my-sub). But for the simplicity of it I would like to allow to pass module names as-is (lets say collector is the method collecting the info):
self.collector( Foo );
Where Foo could be the following:
module Foo {
use Bar;
use Baz;
our sub my-sub { Bar, 'Baz' }
}
And this is where I'm missing something important from Perl6 syntax because the following:
method collector ( $mod ) {
my $mod-name = $mod.WHO;
my #mods;
with &::($mod-name)::my-sub {
#mods.push: &$_();
}
}
is currently the only way I can perform the task.
I didn't try a type capture yet though. Should work as expected, I guess. So, the question is more about extending my knowelge of the syntax.
The final solution from the exchange with Vadim in the comments on their question. It's arguably insane. They think it's beautiful. And who am I to argue? .oO( Haha, hoho, heehee... )
my $pkg-arg = (Int, 'Int').pick;
my \pkg-sym = $pkg-arg && ::($pkg-arg);
my \sub-ref = &pkg-sym::($subname);
There are two obviously useful ways to refer to a package:
Its symbolic name. Int is the symbolic name of the Int class.
Its string name. 'Int' is the string name of the Int class.
Vadim, reasonably enough, wants a solution for both.
In the solution in this answer I simulate the two types of argument by randomly picking one and assigning it to $pkg-arg:
my $pkg-arg = (Int, 'Int').pick;
Now we need to normalize. If we've got a symbolic name we're good to go. But if it's a string name, we need to turn that into the symbolic name.
Vadim showed a couple ways to do this in the comments on their question. This solution uses a third option:
my \pkg-sym = $pkg-arg && ::($pkg-arg);
If $pkg-arg is a symbolic name, it'll be False. With a False LHS the && short-circuits and returns its LHS. If $pkg-arg is a string name, then the && will instead return its RHS, which is ::($pkg-arg) which is a symbol lookup using $pkg-arg as a string name.
The upshot is that pkg-sym ends up containing a package symbolic name (or a Failure if the lookup failed to find a matching symbolic name).
Which leaves the last line. That looks for a sub named $subname in the package pkg-sym:
my \sub-ref = &pkg-sym::($subname);
The & is needed to ensure the RHS is treated as a reference rather than as an attempt to call a routine. And pkg-sym has to be a sigilless identifier otherwise the code won't work.
At the end of these three lines of code sub-ref contains either a Failure or a reference to the wanted sub.

Converting a string to double in Dart using double.parse()

I am trying to convert coordinates returned from the Google Geo. API into doubles. A simplified part of the response that gets returned is...
{
locationData: {
bounds: {
northeast: 40.222222,
southwest: 38.265987
}
}
}
When I use print(locationData['bounds']['northeast']) my console reads that and understands that the value is 40.222222 However, when I try to use a parse method, I get the following error:
var neLat = double.parse(locationData['bounds']['northeast']);
I/flutter (10537): type 'double' is not a subtype of type 'String' in type cast where
I/flutter (10537): double is from dart:core
I/flutter (10537): String is from dart:core
That error leads me to believe that my parse is not valid, even though it is clearly a double value, just as a string. Am I missing something for this conversion? I have seen conversion in multiple examples using double.parse, I just can't figure out what my issue is..
If the value was parsed from JSON, Dart knows the value is a double and the error is telling me that the value is of type double and the convert expected type string.
So the error is much more clear once I understood!
I was too facing same issue.
I know it is a silly answer but it worked for me. I was using Getx to save states and while converting string to double it was displaying error
String is not subtype of type double
as the state of previous variables was being saved, so I restarted the app and tried type casting and it worked well.

Swift optionals - warning on conditional cast from 'x' to 'x' always succeeds

I was wondering if there is a way to turn off/avoid 'yellow' warnings in xcode on if let...NSUserDefaults constructs where the key is of a known value.
For example:
if let x = NSUserDefaults.standardUserDefaults().integerForKey("myKey") as? Int {...}
Because of the if let I have to use as?. However, as I am using a known value type (in this case integer) the as? Int is effectively redundant - which is why I am getting the 'yellow warning'.
Thoughts? Is there a better way to code these types of constructs?
My suggestion would be to address the issue instead of silencing the warnings. :)
NSUserDefaults.standardUserDefaults().integerForKey("myKey") does not return an Optional, and the type is known, so you don't need neither optional binding with if let nor type casting with as?.
Just this:
let x = NSUserDefaults.standardUserDefaults().integerForKey("myKey")
will suffice, since .integerForKey just returns 0 if it can't get the actual value.
If you don't like this behavior of getting a default value (I don't), then don't use .integerForKey and use objectForKey with optional binding and type casting instead. Like you were doing first but with .objectForKey replacing .integerForKey. That way you'll get an actual nil if the value for the key is unreachable, not a default value.
if let x = NSUserDefaults.standardUserDefaults(). objectForKey("myKey") as? Int {...}
First of all check always the signature:
⌥-click on the symbol integerForKey: or look at Quick Help.
You will see:
func integerForKey(_ defaultName: String) -> Int
It reveals the return value is a non optional.
Non optionals can retrieved directly as described in Eric's answer without any type casting, optional binding causes an error.
That's one of the essential semantics in Swift.

Function parameter error - Missing Argument Label Anomaly - SWIFT

I have a strange issue (which I can overcome however I would like to get a proper understanding of my error).
I have a small random number generator function which I use often:
func ranNum(low: Int, high:Int) -> UInt32 {
var result = arc4random_uniform(UInt32((high+1)-low)) + low
return result
}
When I use this in XCode playgrounds it works just fine if I pass in something like:
ranNum(1, 10)
However, in a regular Swift file it generates the error message : Missing argument label 'hi:' in call. Now I can overcome this by calling the function this way:
ranNum(1, hi:10)
Apart from it just being a little harder to read, it just isn't making sense why it works in Playgrounds but also why it requires only the 2nd argument label and not both. Any help as to what I am not understandinh would be greatly appreciated.
That's called external parameter name, and by default:
global functions: don't have implicit external names
class/struct methods: external names are automatically defined for all parameters after the first
initializers: external names are automatically defined for all parameters
If not explicitly specified, external names take the same name as the local parameter.
You can override that by prefixing a local parameter name with _. In your case:
func ranNum(low: Int, _ high:Int) -> UInt32 {
...
}
You mentioned that in playground calling the function works without any external parameter name - I may argue that:
in playground you have that function as a global function
in other tests, that function is a class/struct method
Am I right?

string was not recognized as a valid datetime. in c#

i am using this code for passing datetime.
Convert.ToDateTime(textBox1.Text)
but the compiler show an error that string was not recognized as a valid datetime. so how to avoid this error and is a datetime field in my database.
Convert.ToDateTime(textBox1.Text)
This code will throw an exception if the string value in textBox1.Text doesn't represent a valid DateTime (or at least can't be parsed into one with default functionality in C#). You can add some defensive programming to handle errors like this.
The DateTime type (as well as most, if not all, common value types in .NET) has a method on it called TryParse() specifically for the purpose to attempting to parse a value into that type without throwing an exception. The method returns true if the parse was successful, false otherwise. And it accepts an out parameter to hold the resulting parsed value (or the original value if parsing is unsuccessful).
So instead of this:
var dateTimeValue = Convert.ToDateTime(textBox1.Text);
You could use something like this:
var dateTimeValue = DateTime.MinValue;
if (DateTime.TryParse(textBox1.Text, out dateTimeValue))
// use the value for something

Resources