Empty Object in Coffeescript - coffeescript

I want to make an if statement to check if an object is an empty object or not.
By empty object I mean if I do console.log(object) it prints out {}.
How do I do this?

myObject = {}
if Object.keys(myObject).length == 0
# myObject is "empty"
else
# myObject is not "empty"

This function might work for you :
is_empty = (obj) ->
return true if not obj? or obj.length is 0
return false if obj.length? and obj.length > 0
for key of obj
return false if Object.prototype.hasOwnProperty.call(obj,key)
return true
#Examples
console.log is_empty("") #true
console.log is_empty([]) #true
console.log is_empty({}) #true
console.log is_empty(length: 0, custom_property: []) #true
console.log is_empty("Hello") #false
console.log is_empty([1,2,3]) #false
console.log is_empty({foo: 1}) #false
console.log is_empty(length: 3, custom_property: [1,2,3]) #false

Related

Its giving unexpected Indentation error.Any Idea ?Any one?

Below is my coffee Script .Its giving "Unexpected Indentation" error.
Any one can guess whats the errror is?
evaluateContainerRules: ( rules, containerType ) ->
deferred = Ext.create( 'Deft.promise.Deferred' )
searchCriteria = []
for rule in rules
if rule.searchTerms? and rule.searchTerms.length > 0
searchCriteria.push( rule )
console.log 'rule'
console.log 'searchCriteria'
if searchCriteria.length <= 0
emptyRules =
[
{
searchOption: 'EMPTY_RULE'
searchTerms: true
}
]
console.log 'emptyRules'
searchCriteria.push( emptyRules )
searchCriteria.push["Hello"]
console.log 'searchCriteria'
store = Ext.create( 'Traverse.core.store.admin.container.ContainerMemberSummarySearchStore',
params:
searchCriterias: searchCriteria
traverseTypeEnums: if containerType is 'device' then [ Traverse.core.enumeration.TraverseType.DEVICE ] else [ Traverse.core.enumeration.TraverseType.TEST ]
)
complete = false
store.on(
'load'
( records, operation, success ) ->
# NOTE: callback is fired multiple times for a paging store, only execute logic during the first call
if complete
return
complete = true
if success
deferred.resolve( store )
else
store.destroyStore()
#showError( operation.getError() )
deferred.reject( operation.getError() )
return
scope: #
)
store.load()
return deferred.promise
Its
This seems a reasonable re-indentation of your code that compiles
evaluateContainerRules: ( rules, containerType ) ->
deferred = Ext.create( 'Deft.promise.Deferred' )
searchCriteria = []
for rule in rules
if rule.searchTerms? and rule.searchTerms.length > 0
searchCriteria.push( rule )
console.log 'rule'
console.log 'searchCriteria'
if searchCriteria.length <= 0
emptyRules =
[{
searchOption: 'EMPTY_RULE'
searchTerms: true
}]
console.log 'emptyRules'
searchCriteria.push( emptyRules )
searchCriteria.push["Hello"]
console.log 'searchCriteria'
store = Ext.create( 'Traverse.core.store.admin.container.ContainerMemberSummarySearchStore',
params:
searchCriterias: searchCriteria
traverseTypeEnums: if containerType is 'device' then [ Traverse.core.enumeration.TraverseType.DEVICE ] else [ Traverse.core.enumeration.TraverseType.TEST ]
)
complete = false
store.on(
'load'
( records, operation, success ) ->
# NOTE: callback is fired multiple times for a paging store, only execute logic during the first call
if complete
return
complete = true
if success
deferred.resolve( store )
else
store.destroyStore()
#showError( operation.getError() )
deferred.reject( operation.getError() )
return
scope: #
)
store.load()
Hope this helps

Drupal 8: How to print node__field values in hook_views_query_alter function?

i try to print node field values in the hook_views_query_alter function.
I would add a new condition with this function
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'my_view' && $view->current_display == "block_1") {
$query->addWhere(
$options['group'],
db_and()
->condition('node__field_myfield.field_myfield', 'myvalue', '=')
);
}
}
in this case "myvalue" should be a value from node field

Show syntax errors in knitr output?

I'm writing a description of R syntax, and I'd like to include some statements that include syntax errors, e.g.
if (n >= 2)
{
# if TRUE
}
else
{
# if FALSE
}
(This is a syntax error at top level because the if is complete before the else is read.) I'm trying to put this into a knitr document, but
even with error=TRUE it fails, because that option only affects run-time errors, not syntax errors. Is there some reasonable way to get this to display what would be shown if I entered it at the console? I.e.
I'd like it to display something like
if (n >= 2)
{
# if TRUE
}
else
Error: unexpected 'else' in "else"
{
# if FALSE
}
Here's a function that does part of what I want: it reproduces the output from a syntax error, but it doesn't do all the markup that knitr would do, so the formatting is wrong.
parse_with_error <- function(text) {
reportError <- function(e) {
msg <- conditionMessage(e)
line <- as.numeric(sub("^text:([[:digit:]]*):.*", "\\1", msg))
col <- as.numeric(sub("^text:[[:digit:]]*:([[:digit:]]*):.*", "\\1", msg))
cat(text[1:line], sep="\n")
if (col > 1)
cat(paste(rep(" ", col-1), collapse=""))
cat("^\n")
err <- sub("^text:[[:digit:]]*:[[:digit:]]*: ([^[:cntrl:]]*)\n.*", "\\1", msg)
parseData <- getParseData(sf)
lastToken <- parseData[nrow(parseData), "text"]
cat(paste0("Error: ", err, ' in "', lastToken, '"'), "\n")
}
text <- unlist(strsplit(text, "\n"))
sf <- srcfile("text")
tryCatch(parse(text = text, keep.source = TRUE, srcfile=sf),
error = reportError)
}
This shows how it would be used:
parse_with_error(
"if (TRUE) {
# do TRUE
}
else {
# do FALSE
}")
You can use a separate R session to evaluate the code, e.g.
```{r, engine='Rscript', error=TRUE}
if (TRUE)
{
# if TRUE
}
else
{
# if FALSE
}
```

Inference not working

I'm relatively new to Drools. I have those rules :
import models.Demarche;
declare IsMarque
demarche : Demarche
end
rule "Add type Marque taxe"
salience 2
no-loop true
lock-on-active true
when
$d : Demarche( typeDemarche == "Marque" )
then
modify($d){
listTaxes.put(14, 1)
}
insert( new IsMarque( $d ) );
System.out.println("infer marque");
end
And :
rule "Add Marque Polynesie extention taxe"
no-loop true
lock-on-active true
when
$d : Demarche( extPolynesie == true)
IsMarque(demarche == $d)
then
$d.listTaxes.put(17, 1);
System.out.println("marque");
end
rule "Add Not Marque Polynesie extention taxe"
no-loop true
lock-on-active true
when
$d : Demarche( extPolynesie == true)
not(IsMarque(demarche == $d))
then
System.out.println("not marque");
end
For the rules 2 or 3, nothing happens. One of them should be true, but nothing is printed, as if the infered IsMarque cannot be evaluated. If I comment the IsMaqrue evaluation this is working, i can see the messages printed in the console.
Any idea?
This rule needs to be rewritten as
rule "Add type Marque taxe"
when
$d : Demarche( typeDemarche == "Marque", $t: listTaxes) // I AM GUESSING HERE
not IsMarque(demarche == $d)
then
modify($t){
put(14, 1)
}
insert( new IsMarque( $d ) );
System.out.println("infer marque");
end
And no no-loop true and lock-on-active true if you have shown everything there is.
Note that you could write the first rule also as
rule "Add type Marque taxe"
when
$d : Demarche( typeDemarche == "Marque")
then
$d.getListTaxes().put(14, 1);
insert( new IsMarque( $d ) );
System.out.println("infer marque");
end
if (and only if) no other rule as CEs referring to the listTaxes property. Since you have used this "dirty update" in rule "Add Marque Polynesie extention taxe", it seems to be OK.
Please post complete rules - #1 doesn't compile.

PowerShell - if statement condition that produces multiple results

Please consider this silly example:
if (1..3) { "true" }
The above produces the output true.
My question: How does the if statement handle a case like this where multiple values are output by the conditional? Is the "true" output the result of the "3" (the last case)? Or is some other logic at work? Thanks.
The observed behavior is explained (to some extent) in this blog post. Basically, if an expression evaluates to 0 it's interpreted as false, otherwise as true. Examples:
0 => False
1 => True
"0" => True (because it's a string of length 1)
"" => False (because it's a string of length 0)
#() => False
#(0) => False (this one's a little surprising)
#(0,1) => True
#("0") => True
The above produces the output true, as expected.
Why do you expect it to output "true"?
How does the if statement handle a case like this where multiple values are output by the conditional?
The conditional does not "output" any values. It always evaluates to "true" or "false". The question remaining is, why does it evaluate to true (or false).
The code
if (1..3) { "true" }
is equal to
if (#(1,2,3)) { "true" }
is equal to
$array = #(1,2,3)
if ($array) { "true" }
behaves as
if ($array.Length -gt 0) { "true" }
So not individual elements are tested, but rather if the array contains any elements.
For example, the following will not print "true":
if (#()) { "true" }
Update If the array contains only one value, it looks (I coudn't find any normative documentation on that), as if the array is treated as a scalar value using the one element inside.
So
if (#(0))
if (#(0.0))
if (#(1))
if (#(-1))
if (,$null))
if (,"false"))
is treated as
if (0) --> false
if (0.0) --> false
if (1) --> true
if (-1) --> true
if ($null) --> false
if ("false") --> true
1..3 results in an array with 3 items
PS> (1..3).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> (1..3).Length
3
If there is at least one item in the array the if considers it true
PS> if (#()) { "true" } else { "false" }
false
PS> if (#(1)) { "true" } else { "false" }
true
PS> if (#(1,2)) { "true" } else { "false" }
true