how to use find count using raw method in query builder on laravel - mongodb

I am trying to find count of gender using the raw statement but i get this error
Parse error: syntax error, unexpected '$total' (T_VARIABLE). Can someone please tell me whats my error
$collection='{gender:"Male"}'
$total = DB::collection('leads')->raw(function($collection)
{
return $collection->find();
});
return $total;

A semicolon is missing behind $collection='{gender:"Male"}'. (that should at least solve the error you get currently)

Related

How do I print a message if a ValueError occurs?

while answers_right < 3:
ran_number_1 = random.randint(10, 99)
ran_number_2 = random.randint(10, 99)
solution = ran_number_1 + ran_number_2
print(f"What is {ran_number_1} + {ran_number_2}?")
user_answer = int(input("Your answer: "))
if user_answer == solution:
answers_right += 1
print(f"Correct. You've gotten {answers_right} correct in a row.")
elif user_answer != solution:
answers_right = 0
print(f"Incorrect. The expected answer is {solution}.")
if answers_right == 3:
print("Congratulations! You've mastered addition.")
I want to add an additional if statement in case someone types string and return a message that says "Invalid Response" instead of the Traceback Error.
Use of Exception handling in python may be solve your Problem and you can also generate your own error class for particular condition.
if x < 3:
raise Exception("Sorry, no numbers below 3")
Use of throw and raise keyword you can generate your own error.
for more referencelink here
The correct way to solve this problem is to look at the error type in your traceback, and use a try/except block. It will say something like TypeError: error stuff here or ValueError: error stuff also here.
The way you do a try/except is to:
try:
some_code()
that_might()
produce_an_error()
except some_error_type:
do_stuff()
except_some_other_error_type:
do_other_stuff()
So, to catch a ValueError and a TypeError, you might do:
try:
buggy_code()
except ValueError:
print("Woah, you did something you shouldn't have")
except TypeError:
print("Woah, you did something ELSE you shouldn't have")
If you then want the traceback, you can add in a lone "raise" statement below the excepts. For example:
try:
buggy_code()
except ValueError:
print("Woah, you did something you shouldn't have")
raise
except TypeError:
print("Woah, you did something ELSE you shouldn't have")
raise
Errors have evolved to be a lot more useful in modern times. They don't break the entire system anymore, and there are ways of handling them. Try/Except blocks like the above give you the tools to have code that only executes when a specific error or set of errors is raised.

How to pass a null value received on msg.req.query to msg.payload

I am developing an application using Dashdb on Bluemix and nodered, my PHP application uses the call to webservice to invoke the node-red, whenever my function on PHP invokes the node to insert on table and the field GEO_ID is null, the application fails, I understand the issue, it seems the third parameter was not informed, I have just tried to check the param before and passing something like NULL but it continues not working.
See the code:
msg.account_id = msg.req.query.account_id;
msg.user_id = msg.req.query.user_id;
msg.geo_id=msg.req.query.geo_id;
msg.payload = "INSERT INTO ACCOUNT_USER (ACCOUNT_ID, USER_ID, GEO_ID) VALUES (?,?,?) ";
return msg;
And on Dashdb component I have set the parameter as below:
msg.account_id,msg.user_id,msg.geo_id
The third geo_id is the issue, I have tried something like the code below:
if(msg.req.query.geo_id===null){msg.geo_id=null}
or
if(msg.req.query.geo_id===null){msg.geo_id="null"}
The error I got is the one below:
dashDB query node: Error: [IBM][CLI Driver][DB2/LINUXX8664] SQL0420N Invalid character found in a character string argument of the function "DECIMAL". SQLSTATE=22018
I really appreciate if someone could help me on it .
Thanks,
Eduardo Diogo Garcia
Is it possible that msg.req.query.geo_id is set to an empty string?
In that case neither if statement above would get executed, and you would be trying to insert an empty string into a DECIMAL column. Maybe try something like this:
if (! msg.req.query.geo_id || msg.req.query.geo_id == '') {
msg.geo_id = null;
}

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.

CoffeeScript parse error - Unexpected "(" - But there's no "(" in the code

Here's the original code:
res.write JSON.stringify {"#{result.statusCode}": "OK"}
and here's the error that both the CoffeeScript linter in SublimeText 2 and the "Try CoffeeScript" interpreter on the CoffeeScript site give me:
PARSE ERROR ON LINE 1: UNEXPECTED '('
Obviously there's no open parens in the code, so I don't understand the error. Is it a bug in the CoffeeScript parser?
The smallest line of code that does this seems to be something like this:
{"#{a}": ""}
I'm assuming that string interpolation in an object's key is valid, but I don't know for sure.
EDIT:
After some investigation it seems that it's not valid to do the string interpolation in the key because the resulting JavaScript would be invalid.
This:
{"#{a}": "stuff}
would translate to something like:
{ "" + a: "stuff"}
which isn't valid.
But can someone explain why the error message it gives me is so wrong?
I'm assuming that string interpolation in an object's key is valid, but I don't know for sure.
Unfortunately it's not.
You'll have to do something like
(json = {})[result.statusCode] = 'OK'
res.write JSON.stringify json
or if you want a one-liner
res.write (-> ((json = {})[result.statusCode] = 'OK') and JSON.stringify json)()
As for the misleading error, CoffeeScript is trying to translate your {"#{a}": ''} into {("" + a): ""} which is not valid JavaScript. CoffeeScript is throwing the error at that left paren.

Why is this defined value not recognized as a package or object reference?

I have the code below:
my $content = $response->decoded_content((charset => 'UTF-8'));
my $feed = XML::Feed->parse(\$content) || $logger->error("When retrieving $URL: ", XML::Feed->errstr);
if (defined $feed) {
for my $entry ($feed->entries) {
#DO SOMETHING
}
}
For some site, XML::FEED saying that it can't detect the feed type. This is something I have to look at but this is not my question at the moment.
This sample code is inside a while loop has I'm retrieving different RSS and I would like to have the script running even when some URLs failed.
The defined function seems to not work as I get the error message:
Can't call method "entries" without a package or object reference
Can someone tell me what is the right way to handle the test?
You first have to check the value of $feed.
The error message you describe is obvious: $feed is not a package / object reference, but it can be a simple hash for instance. So it's defined.
Add my favourite debugging line right in front of if(defined):
warn Data::Dumper->new([ $feed ],[ '*feed' ])->Sortkeys(1)->Dump();use Data::Dumper;
and you'll see the value in a nice way.
Without testing I'd say that $feed contains the result of your logger, which might be 1 or 0 or something like that, because you set the value of $feed to XML::Feed->parse, and if this is not successful (undefined) it's the result of $logger->error.
You'd better write it like:
my $feed = XML::Feed->parse(\$content);
if (defined $feed) {
for my $entry ($feed->entries) {
#DO SOMETHING
}
}
else {
$logger->error("When retrieving $URL: ", XML::Feed->errstr);
}
because parse is said to return an object, and I guess it returns undef on error.
The error message means what it says: $feed is neither a package nor an object reference. It passes the defined test because there are many defined values which are neither packages nor object references.
In this particular case, you're seeing this error because you are misuing ||:
my $feed = XML::Feed->parse(\$content) || $logger->error("When retrieving $URL: ", XML::Feed->errstr);
If the parse call should fail and return undef, this evaluates to
my $feed = ( undef || $logger->error("When retrieving $URL: ", XML::Feed->errstr) );
which evaluates to
my $feed = $logger->error("When retrieving $URL: ", XML::Feed->errstr);
. The return value of $logger->error is unknown to me, but presumably it is neither a package nor an object reference. And if it were one, it probably would be the wrong one to put in a variable named $feed.
The documentation for XML::Feed mentions parsing with a construct like
my $feed = XML::Feed->parse(URI->new('http://example.com/atom.xml'))
or die XML::Feed->errstr;
This is not the same thing. Their respective precedence rules make || and or suitable for different applications; specifically, you should only use || when you want the value on the right-hand side for something. Do not use it only for the short-circuit side effect.
You can solve this by replacing the || with or to get the right evaluation order. While you are there, you probably should also eliminate the redundant defined test.