How to use the global variable in another function? [duplicate] - function

Im writing a small code using Memcache Go API to Get data stored in one of its keys . Here are few of lines of code i used ( got the code from Go app-engine docs )
import "appengine/memcache"
item := &memcache.Item {
Key: "lyric",
Value: []byte("Oh, give me a home"),
}
But the line 2 gives me a compilation error "expected declaration, found 'IDENT' item"
I'm new to Go , not able to figure out the problem

The := Short variable declaration can only be used inside functions.
So either put the item variable declaration inside a function like this:
import "appengine/memcache"
func MyFunc() {
item := &memcache.Item {
Key: "lyric",
Value: []byte("Oh, give me a home"),
}
// do something with item
}
Or make it a global variable and use the var keyword:
import "appengine/memcache"
var item = &memcache.Item {
Key: "lyric",
Value: []byte("Oh, give me a home"),
}

I was getting the same error, but the reason was completely different.
I was using following package name.
package go-example
Seems like, it's not a valid package name. After removing the hyphen, it worked.

This error also shows up when assigning value to a variable whose name is a keyword
Like using var:= 2
This also causes the error "expected declaration, found 'IDENT' item"
So correct the name and it will be fine

Related

Pushing Multiple values into array gives error using angular6

I am working in angular 6 here i want to push multiple values into array which gives me the following error
here is my code
this._model.NomineeList.push(
{
'FirstName': this._nomineemodel.FirstName,
'CNIC': this._nomineemodel.CNIC,
'MiddleName': this._nomineemodel.MiddleName,
'LandlineNumber': this._nomineemodel.LandlineNumber,
'LastName': this._nomineemodel.LastName,
'MobileNumber': this._nomineemodel.MobileNumber,
'PermanentAddress': this._nomineemodel.PermanentAddress,
'PresentAddress': this._nomineemodel.PresentAddress,
'RelationId': this._nomineemodel.RelationId,
'RelationName': this._nomineemodel.RelationName,
'UPermanentAddress': '',
'UPresentAddress': ''
});
How to push into array using angular 6.
The error is self explanatory, the kind on model you are inserting in your array they are not identical. there are two possible reasons.
1) Either you haven't initiated the array with empty values. or
2) The model you are inserting is missing mandatory properties or the new model having few extra properties or spell mistake in properly name.
Check this stackblitz example.

Python: create json query

I'm trying to get python to create a json formatted like :
[
{
"machine_working": true
},
{
"MachineName": "TBL165-169",
"MachineType": "Rig Test"
}
]
However, i can seam to do it, this is the code i have currently but its giving me error
this_is_a_dict_too=[]
this_is_a_dict_too = dict(State="on",dict(MachineType="machinetype1",MachineName="MachineType2"))
File "c:\printjson.py", line 40
this_is_a_dict_too = dict(Statedsf="test",dict(MachineType="Rig Test",MachineName="TBL165-169")) SyntaxError: non-keyword arg after
keyword arg
this_is_a_dict_too = [dict(machine_working=True),dict(MachineType="machinetype1",MachineName="MachineType2")]
print(this_is_a_dict_too)
You are trying to make dictionary in dictionary, the error message say that you try to add element without name (corresponding key)
dict(a='b', b=dict(state='on'))
will work, but
dict(a='b', dict(state='on'))
won't.
The thing that you presented is list, so you can use
list((dict(a='b'), dict(b='a')))
Note that example above use two dictionaries packed into tuple.
or
[ dict(a='b'), dict(b='a') ]

Vuejs changes order of json_encoded array, when decodes it back from props in vuejs component

Php:
$json_string = "{
"26":{"blabla":123,"group_id":1,"from":"27.08.2018","to":"02.09.2018"},
"25":{"blabla":124,"group_id":1,"from":"20.08.2018","to":"26.08.2018"},
"24":{"blabla":125,"group_id":1,"from":"20.08.2018","to":"26.08.2018"}
}"
my.blade.php template:
<my-component :records={{ $json_string }}></my-component>
MyComponent.vue:
export default {
props: ['records'],
...
mounted: function () {
console.log(this.records);
}
Output is:
{__ob__: Observer}
24:(...)
25:(...)
26:(...)
And when I use v-for, records in my table in wrong order (like in console.log output).
What I am doing wrong?
EDIT:
I figured out 1 thing:
When I do json_encode on collection where indexes are from 0 till x, than json string is: [{some data}, {some data}]
But if I do ->get()->keyBy('id') (laravel) and than json_encode, json string is:
{ "26":{some data}, "25":{some data}, "24":{some data} }
Then how I understood, issue is in different outer brackets.
In Javascript keys of objects have no order. If you need a specific order then use arrays.
Here is documentation for keyBy Laravel method: https://laravel.com/docs/5.6/collections#method-keyby
I wanted to have ids for rows data to fast and easy access without iterating over all rows and check if there is somewhere key Id which is equals with my particular Id.
Solution: not to use keyBy method in Laravel and pass json string to Vue component like following [{some data}, {some data}] (as I described in my Question Edit section) - this will remain array order as it used to be.
I found this short and elegant way how to do this, instead of writing js function by myself:
Its find() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Example:
let row = records.find( record => record.id === idToFind );

Check and print occurrences of an array of string in a dataset in Python

I want to check if an array of strings occur in a dataset and print those rows where the string array elements occur.
rareTitles = {"Capt", "Col", "Countess", "Don", "Dr", "Jonkheer", "Lady",
"Major", "Mlle", "Mme", "Ms", "Rev", "Sir"}
dataset[rareTitles in (dataset['Title'])]
I am getting following error:
TypeError: unhashable type: 'set'
First of all, I think the comparison should go the other way around - you look for a dataset['Title'], that contains string from rareTitles.
You can use str attribute of a pandas DataSeries, which allows as to use string methods, like contains. As this method accepts also a pattern as a regular expression, you can put as an argument something like 'Capt|Col...'. To join all elements of a set you can use str.join() method.
So the solution would be
dataset[dataset['Title'].str.contains('|'.join(rareTitles))]
Link to documentation: pandas.Series.str.contains

MongoDB - Dynamically update an object in nested array

I have a document like this:
{
Name : val
AnArray : [
{
Time : SomeTime
},
{
Time : AnotherTime
}
...arbitrary more elements
}
I need to update "Time" to a Date type (right now it is string)
I would like to do something psudo like:
foreach record in document.AnArray { record.Time = new Date(record.Time) }
I've read the documentation on $ and "dot" notation as well as a several similar questions here, I tried this code:
db.collection.update({_id:doc._id},{$set : {AnArray.$.Time : new Date(AnArray.$.Time)}});
And hoping that $ would iterate the indexes of the "AnArray" property as I don't know for each record the length of it. But am getting the error:
SyntaxError: missing : after property id (shell):1
How can I perform an update on each member of the arrays nested values with a dynamic value?
There's no direct way to do that, because MongoDB doesn't support an update-expression that references the document. Moreover, the $ operator only applies to the first match, so you'd have to perform this as long as there are still fields where AnArray.Time is of $type string.
You can, however, perform that update client side, in your favorite language or in the mongo console using JavaScript:
db.collection.find({}).forEach(function (doc) {
for(var i in doc.AnArray)
{
doc.AnArray[i].Time = new Date(doc.AnArray[i].Time);
}
db.outcollection.save(doc);
})
Note that this will store the migrated data in a different collection. You can also update the collection in-place by replacing outcollection with collection.