Strings from NSUserDefaults not visible, xcode 7.3 - xcode7

Today I upgraded to Xcode 7.3, and I also started getting odd behavior from NSUserDefaults. I don't know if they're related. String values I store in defaults are not visible upon retrieval but they have length and support substring extraction:
(lldb) po [[NSUserDefaults standardUserDefaults] objectForKey:UDEmail]
(lldb) po [[[NSUserDefaults standardUserDefaults] objectForKey:UDEmail] length]
0x00000014
(lldb) po [[[NSUserDefaults standardUserDefaults] objectForKey:UDEmail] substringFromIndex:0]
david.uzzell#att.net
Some methods that receive these strings act as if I have passed in a nil value. Is anyone else seeing this?

It's not exactly an answer but if you call the "description" method, witch is declared in the NSObject class, you can see the value of the property.

Related

AppleScript grap JSON data from safari

I have no knowledge at all about what I'm talking about which is a big issue.
I often run a search on an internal website, let say
https://theexemplewebsite.demo/
I found out that searching with this pattern (XXXXXXX is my search keyword) I can retrieve the information I want in something which look like JSON (I think...)
https://theexemplewebsite.demo/admin/api/v1/profil?id=XXXXXXX
e.g :
{"aDate":11111,"bDate":111112,,"OtherData":false,"example":"D01","moreData":"DEMO","description":"OSX computer", and so on...
Is there a way to get this information, for example OSX computer from "description":"OSX computer" and store them in a AppleScript variable ?
I hope that make some sense.
Thanks.
If you get a valid JSON string you could use AppleScriptObjC – which provides access to Cocoa classes like NSJSONSerialization –  to parse it:
use framework "Foundation"
set jsonString to "{\"aDate\":11111,\"bDate\":111112,\"OtherData\":false,\"example\":\"D01\",\"moreData\":\"DEMO\",\"description\":\"OSX computer\"}"
set jsonNSString to current application's NSString's stringWithString:jsonString
set jsonData to jsonNSString's dataUsingEncoding:(current application's NSUTF8StringEncoding)
set {jsonDict, theError} to current application's NSJSONSerialization's JSONObjectWithData:jsonData options:0 |error|:(reference)
if theError is missing value then
set theDescription to jsonDict's |description| as text
display dialog theDescription
else
display dialog theError
end if

Encoding NaN to JSON

My server uses ServiceStack to produce JSON, and I need to send double[] arrays containing NaNs to the browsers.
Since there's no standard way of encoding NaNs in JSON, it's not surprising that
ServiceStack produces invalid JSON in presence of NaNs
(e.g. [0,NaN,42]). I chose string values as my custom representation of NaNs (and ±Inf by the way):
[0,"NaN",42,"Inf","-Inf"] as an example. (Of course I implemented the necessary post-processing on the browser side, too).
I managed to do it by setting JsConfig<double>.RawSerializeFn to an encoder function.
That was fine, until I realized that as a side effect all DTO properties of type double
disappear from their JSON representation when the value is 0.
EDIT: this can be demonstrated by new KeyValuePair<double, double>(0, 1).ToJson()
which returns {"Key":0,"Value":1} when JsConfig<double>.RawSerializeFn is unset,
but returns {"Value":1} when JsConfig<double>.RawSerializeFn is set.
This change is a side effect that I want to avoid. (But my core problem is the transmitting of NaNs without sacrificing zero-valued DTO properties.)
I browsed the source code
of ServiceStack and it confirmed that the presence
of a custom RawSerializeFn activates the Equals(DefaultValue,propertyValue) check
(by causing propertySuppressDefaultConfig==true), which was omitted by default.
AFAICS the only way to avoid this check is setting JsConfig.IncludeNullValues=true,
which is bad because it cannot be done for double values only. I need the
default behavior: omitting properties with null values (for reference types) and include 0.0 double values in the generated JSON.
How to achieve these?
This custom RawSerializeFn emits 0 values in the latest version of ServiceStack.Text
JsConfig<double>.IncludeDefaultValue = true;
JsConfig<double>.RawSerializeFn = d =>
double.IsPositiveInfinity(d) ?
"\"+Inf\""
: double.IsNegativeInfinity(d) ?
"\"-Inf\""
: double.IsNaN(d) ?
"\"NaN\""
: d.ToString();
var doubles = new[] {
0.0, 1.0, double.NegativeInfinity, double.NaN, double.PositiveInfinity };
doubles.ToJson().Print(); // [0,1,"-Inf","NaN","+Inf"]
new KeyValuePair<double, double>(0, 1).ToJson().Print(); // {"Key":0,"Value":1}

Dart objects with strong typing from JSON

I'm learning Dart and was reading the article Using Dart with JSON Web Services, which told me that I could get help with type checking when converting my objects to and from JSON. I used their code snippet but ended up with compiler warnings. I found another Stack Overflow question which discussed the same problem, and the answer was to use the #proxy annotation and implement noSuchMethod. Here's my attempt:
abstract class Language {
String language;
List targets;
Map website;
}
#proxy
class LanguageImpl extends JsonObject implements Language {
LanguageImpl();
factory LanguageImpl.fromJsonString(string) {
return new JsonObject.fromJsonString(string, new LanguageImpl());
}
noSuchMethod(i) => super.noSuchMethod(i);
}
I don't know if the noSuchMethod implementation is correct, and #proxy seems redundant now. Regardless, the code doesn't do what I want. If I run
var lang1 = new LanguageImpl.fromJsonString('{"language":"Dart"}');
print(JSON.encode(lang1));
print(lang1.language);
print(lang1.language + "!");
var lang2 = new LanguageImpl.fromJsonString('{"language":13.37000}');
print(JSON.encode(lang2));
print(lang2.language);
print(lang2.language + "!");
I get the output
{"language":"Dart"}
Dart
Dart!
{"language":13.37}
13.37
type 'String' is not a subtype of type 'num' of 'other'.
and then a stacktrace. Hence, although the readability is a little bit better (one of the goals of the article), the strong typing promised by the article doesn't work and the code might or might not crash, depending on the input.
What am I doing wrong?
The article mentions static types in one paragraph but JsonObject has nothing to do with static types.
What you get from JsonObject is that you don't need Map access syntax.
Instead of someMap['language'] = value; you can write someObj.language = value; and you get the fields in the autocomplete list, but Dart is not able to do any type checking neither when you assign a value to a field of the object (someObj.language = value;) nor when you use fromJsonString() (as mentioned because of noSuchMethod/#proxy).
I assume that you want an exception to be thrown on this line:
var lang2 = new LanguageImpl.fromJsonString('{"language":13.37000}');
because 13.37 is not a String. In order for JsonObject to do this it would need to use mirrors to determine the type of the field and manually do a type check. This is possible, but it would add to the dart2js output size.
So barring that, I think that throwing a type error when reading the field is reasonable, and you might have just found a bug-worthy issue here. Since noSuchMethod is being used to implement an abstract method, the runtime can actually do a type check on the arguments and return values. It appears from your example that it's not. Care to file a bug?
If this was addressed, then JsonObject could immediate read a field after setting it to cause a type check when decoding without mirrors, and it could do that check in an assert() so that it's only done in checked mode. I think that would be a nice solution.

When do functions expecting maps silently return nil when passed a non-map argument?

I'm a bit surprised to see some functions silently returning nil (or the default value you pass) when you pass something that is not a map where a map is expected.
Take first the following doc and example, which works as I expected:
user> (doc dissoc)
-------------------------
clojure.core/dissoc
([map] [map key] [map key & ks])
dissoc[iate]. Returns a new map of the same (hashed/sorted) type,
that does not contain a mapping for key(s).
The first argument to dissoc must be a map as per the doc, so here's what happens:
user> (dissoc {:a 1 :b 2} :b)
{:a 1}
It works fine, I passed a map. Let's pass something that is not a map to that function whose doc says the first argument should be a map:
user> (dissoc 1 :b)
ClassCastException java.lang.Long cannot be cast to clojure.lang.IPersistentMap clojure.lang.RT.dissoc (RT.java:758)
Fair enough, an exception is thrown at runtime and the issue is clear enough, this is the behavior I expected.
Let's now take another function:
user> (doc get)
-------------------------
clojure.core/get
([map key] [map key not-found])
Returns the value mapped to key, not-found or nil if key not present.
The first argument to get must be a map as per the doc and here's what happens:
user> (get {:a 1} :a)
1
So far so good. Let's pass something that is not a map to that function whose doc says the first argument should be a map:
user> (get 42 :a)
nil
No exception. No nothing. Just a silent "failure".
How comes one function throws an exception when you pass something that is not a map and not the other, although both functions' docs clearly state that the first argument must be a map?
Is there a "rule" to know when, in Clojure, you'll get either exceptions or nil or should I just expect that kind of stuff to be inconsistent?
As a side-question: would Clojure and Clojure programs "break" if, say, get was modified to throw an exception instead of silently returning nil when you don't pass a map where you're supposed to?
An exception should probably be thrown for a get on non-associative arguments as in your example:
(contains? 42 :a)
;=> IllegalArgumentException
(get 42 :a)
;=> nil ??
This is an open issue in Clojure's Issue Tracker. As stated in the issue description, the current behavior of returning a nil is most likely a bug and can obscure programming errors.
get is intended to work on all associative data structures. The language implementors could have chosen to check if the argument was associative, or made a white-list of all associative things that it could check, but instead it has a few special cases defined in clojure.lang.RT, and will also work on anything that implements Map or IPersistentSet or ILookup.
the code is not too hard to grok
Now, as to why it would silently return nil on something that implements none of these interfaces, this is an instance of a persistent Clojure design strategy of silently returning nil rather than failing. This decision definitely has tradeoffs, but it is a pervasive way Clojure does things.

flex3 type casting

Does anyone know the real difference between the two ways of type casting in Flex 3?
var myObject1:MyObject = variable as MyObject;
var myObject2:MyObject = MyObject(variable);
I prefer to use the second method because it will throw an Error when type cast fails, whereas the first method will just return null. But are there any other differences? Perhaps any advantages to using the first method?
The second type of casting has different behaviour for top level(http://livedocs.adobe.com/flex/2/langref/) types, e.g. Array(obj) does not cast in the straightforward way you describe; it creates a new Array if possible from obj, even if obj is an Array.
I'm sure the times this would cause unexpected behaviour would be rare but I always use "as" for this reason. It means if I do
int(str)
I know it's a cast in the "attempt to convert" sense of the word not in the "I promise it is" sense.
ref: got some confirmation on this from http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/
The as method returns null if cast fails.
The () method throws and error if the cast fails.
If the value of variable is not compatible with MyObject, myObject1 will contain null and you will be surprised by a null pointer error (1009 : cannot access a property or method of a null object reference.) somewhere later in the program when you try to access it. Where as if you are casting using the MyObject(variable) syntax, you will get a type coercion error (1034 : Type Coercion failed: cannot convert _ to _) at the same line itself - which is more helpful than getting a 1009 somewhere later and wondering what went wrong.
I think I read somewhere on this site that as is slighty faster than (), but I can't find the question again.
Beside that this question have been asked many times, you will find an more in-depth answer here.
I recently discovered the very useful [] tag when searching on StackOverflow, it allows to only search in questions tagged with the specified tag(s). So you could do a search like [actionscript-3] as vs cast. There are more search tips here: https://stackoverflow.com/search.
And no; the irony in that I can not find the question about performance and write about how to search is not lost on me ;)
I think as returns back the base class and not null when the casting fails and () throws an error.