Coffeescript inline conditionals - coffeescript

I have this piece of coffeescript which is compiling fine, yet it does actually work as it should.
jQuery ($) ->
eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"
eventer = window[eventMethod]
messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"
# Listen to message from child window
eventer messageEvent, (e) ->
console.log "parent received message!: #{e.data}"
newHeight = e.data
$("#cf-iframe").css("height", newHeight)
, false
messageEvent is undefined or false causing an error. Could someone please advise of how to get around this. I'm fairly new to coffeescript, but loving it so far.
Update: upon further inspection it looks to me like coffeescript does not implement the ?/: operators, instead favouring the if/then/else approach.

You are confusing the existential operator ? with the ternary operator, which in coffeescript is just an if expression.
eventMethod = if window.addEventListener then "addEventListener" else "attachEvent"

Related

Drools MVEL Dialect - Semi-Colon Requirement

I am just curious as to why my Eclipse Drools compiler (6.5.0) requires semi-colons at the end of statements in the For loop, as below:
Map businessRulesRequest = $root.containsKey("BusinessRulesRequest") ? $root.get("BusinessRulesRequest") : null
Map quoteRequest = businessRulesRequest!=null && businessRulesRequest.containsKey("QuoteRequest") ? businessRulesRequest.get("QuoteRequest") : null
List resultsByKey = quoteRequest!=null && quoteRequest.containsKey("resultsByKey") ? quoteRequest.get("resultsByKey") : new ArrayList()
for (Map search : resultsByKey) {
Map searchInfo = (search.containsKey("searchInfo") ? search.get("searchInfo") : null);
String searchName = searchInfo!=null && searchInfo.containsKey("searchName") ? searchInfo.get("searchName").toString() : "";
List results = (searchName=="quotesMotor" && search.containsKey("results") ? search.get("results") : new ArrayList());
}
If I remove the semi-colons from the first or second lines in the For loop, I get an "unexpected token" error, but not if I remove it from the last line in the loop.
Is it due to Drools evaluating RHS lines as a single statement and so they must be separated inside any loops?
Note: I understand it is not best practice to code assuming semi-colons are not required, however I came across this issue while experimenting and am just interested to know the reason for the compiler error. Thanks.
I guess the answer is because of MVEL itself. Drools may be delegating the entire chunk of code to MVEL to evaluate and execute.
According to this guide, in MVEL the use of a semi-colon is not mandatory in cases where you have 1 statement, or in the last statement of a script.
Hope it helps,

Why does my ternary operator give a different result to an if else?

The problem I am having is I am trying to use ternary operators over if else for smaller code but when using it in my case it is returning a different result than if I use an if else.
The problem code is below;
If Else
if(string.IsNullOrEmpty(jn["LARM"].Value))
pm.ItemLeftArm = null;
else
pm.ItemLeftArm = jn["LARM"];
Ternary
pm.ItemLeftArm = string.IsNullOrEmpty(jn["LARM"].Value) ? null : jn["LARM"];
The jn["LARM"] is a json node from simpleJSON and it is either a number e.g. "0" or nothing e.g. "".
It returns null form the if else but it returns the jn object which transforms from "" into 0.
Im not sure why Im getting this issue.
The code is ok, the problem must be in the JSON. Have you tried logging the jn["LARM"].Value just before the terniary operator in order to be sure that the value is null/empty or not?
BTW, why are you using simpleJSON instead of the new Unity integrated JsonUtility?

how to compare expected value to be in the list [duplicate]

One of my test expects an error message text to be one of multiple values. Since getText() returns a promise I cannot use toContain() jasmine matcher. The following would not work since protractor (jasminewd under-the-hood) would not resolve a promise in the second part of the matcher, toContain() in this case:
expect(["Unknown Error", "Connection Error"]).toContain(page.errorMessage.getText());
Question: Is there a way to check if an element is in an array with jasmine+protractor where an element is a promise?
In other words, I'm looking for inverse of toContain() so that the expect() would implicitly resolve the promise passed in.
As a workaround, I can explicitly resolve the promise with then():
page.errorMessage.getText().then(function (text) {
expect(["Unknown Error", "Connection Error"]).toContain(text);
});
I'm not sure if this is the best option. I would also be okay with a solution based on third-parties like jasmine-matchers.
As an example, this kind of assertion exists in Python:
self.assertIn(1, [1, 2, 3, 4])
Looks like you need a custom matcher. Depending on the version of Jasmine you are using:
With Jasmine 1:
this.addMatchers({
toBeIn: function(expected) {
var possibilities = Array.isArray(expected) ? expected : [expected];
return possibilities.indexOf(this.actual) > -1;
}
});
With Jasmine 2:
this.addMatchers({
toBeIn: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
var possibilities = Array.isArray(expected) ? expected : [expected];
var passed = possibilities.indexOf(actual) > -1;
return {
pass: passed,
message: 'Expected [' + possibilities.join(', ') + ']' + (passed ? ' not' : '') + ' to contain ' + actual
};
}
};
}
});
You'll have to execute this in the beforeEach section on each of your describe blocks it's going to be used in.
Your expect would look like:
expect(page.errorMessage.getText()).toBeIn(["Unknown Error", "Connection Error"]);
The alternative solution is to use .toMatch() matcher with Regular Expressions and specifically a special character | (called "or"), which allows to match only one entry to succeed:
expect(page.errorMessage.getText()).toMatch(/Unknown Error|Connection Error/);
To me, the work-around that you identified is the best solution. However, we should not forget that this is an asynchronous execution and you might want to consider Jasmine's asynchronous support.
Then, your test will look like the following one:
it('should check item is in array', function(done){ //Note the argument for callback
// do your stuff/prerequisites for the spec here
page.errorMessage.getText().then(function (text) {
expect(["Unknown Error", "Connection Error"]).toContain(text);
done(); // Spec is done!
});
});
Note: If you don't pass this done argument to the spec callback, it is going to run to completion without failures, but no assertions are going to be reported in the execution results for that spec (in other words, that spec will have 0 assertions) and it might lead to confusions.

Inline if condition with nil in swift

I am trying to use inline if condition as follows:
topDisplay.text = topDisplay.text!.rangeOfString(".") ? "Sth for true" : "Sth for false"
The idea here is if there is "." in the topDisplay.text! then do something, if not, do something else. The method, rangeOfString, returns nil if no "." is found. So I am wondering is it possible to check nil within inline condition expression.
((btw, you might find out that I am trying to add "." button for calculator assignment in Stanford's online course, and to use only one line to implement this function as the hint describes))
So I am wondering is it possible to check nil within inline condition expression.
Sure. rangeOfString(".") != nil is a boolean expression which can
be used as the condition in the conditional expression:
topDisplay.text = topDisplay.text!.rangeOfString(".") != nil ? "Sth for true" : "Sth for false"

Is is possible to populate a datatable using a Lambda expression(C#3.0)

I have a datatable. I am populating some values into that.
e.g.
DataTable dt =new DataTable();
dt.Columns.Add("Col1",typeof(int));
dt.Columns.Add("Col2",typeof(string));
dt.Columns.Add("Col3",typeof(DateTime));
dt.Columns.Add("Col4",typeof(bool));
for(int i=0;i< 10;i++)
dt.Rows.Add(i,"String" + i.toString(),DateTime.Now,(i%2 == 0)?true:false);
There is nothing wrong in this program and gives me the expected output.
However, recently , I am learning Lambda and has done some basic knowledge.
With that I was trying to do the same thing as under
Enumerable.Range(0,9).Select(i = >
{
dt.Rows.Add(i,"String" + i.toString(),DateTime.Now,(i%2 == 0)?true:false);
});
But I am unsuccessful.
Is my approach correct(Yes I know that I am getting compile time error; since not enough knowledge on the subject so far)?
Can we achieve this by the way I am doing is a big doubt(as I donot know.. just giving a shot).
If so , can some one please help me in this regard.
I am using C#3.0 and dotnet framework 3.5
Thanks
You're very close. Just remove the {curly braces} and the space in "= >".
Enumerable.Range(0, 9).Select(i => dt.Rows.Add(i,
"String" + i.ToString(), DateTime.Now, (i%2 == 0) ? true : false));
The Select method returns an enumerable with deferred execution. To make the enumerable execute, you must enumerate it. Also - dt.Rows.Add returns void, so it is an Action, not a Func and cannot be used in the Select call.
Instead of using Select, how about using
ToList<T>().ForEach<T>(Action<T>)
As in:
Enumerable.Range(0,9)
.ToList()
.ForEach(i =>
{
dt.Rows.Add(i,"String" + i.ToString(), DateTime.Now, (i%2 == 0) );
});