Can't get query results outside the function - mongodb

I have this class in which i try to initialize array attributes with query results:
class data
minute: []
hour: []
constructor: () ->
findMin = events.find({"aggr":"minute"}).sort({$natural:-1}).limit(120)
findHour = events.find({"aggr":"hour"}).sort({$natural:-1}).limit(14)
findMin.execFind (errMin, resMin) ->
for recMin in resMin
#minute.push recMin
findHour.execFind (errH, resH) ->
for recH in resH
#hour.push recH
So i call smth = new data() and console.log smth and get an empty attributes and an error about undefined not having 'push' method. While i can understand an error i cant get why my arrays are empty. Dont get me wrong - i know this error causes them to be empty, but i tried several kinds of variants. And ive read about acync and callbacks, but still don't have a clue how to use callbacks not to 'alert' smth, but to use it afterwards. If you could help me with that or with some links that could - i would appreciate it SO much.

You have two issues. The one that is causing the error you are observing is that '#' inside of your two callbacks is not bound to your data instance, so you need to use =>. Secondly, and as pointed out by #AaronDufour, your hour and minute arrays are declared at the class level so they will be shared between every instance of data, which I doubt is what you want, so you need to move them into your constructor.
class data
constructor: () ->
#minute = []
#hour = []
findMin = events.find({"aggr":"minute"}).sort({$natural:-1}).limit(120)
findHour = events.find({"aggr":"hour"}).sort({$natural:-1}).limit(14)
findMin.execFind (errMin, resMin) =>
for recMin in resMin
#minute.push recMin
findHour.execFind (errH, resH) =>
for recH in resH
#hour.push recH

I assume you want minute and hour to be instance variables? They must be initialized in the constructor. The way you're doing it now, they're on the prototype, so it won't work properly. Try this:
class data
constructor: () ->
#minute = []
#hour = []
findMin = events.find({"aggr":"minute"}).sort({$natural:-1}).limit(120)
findHour = events.find({"aggr":"hour"}).sort({$natural:-1}).limit(14)
findMin.execFind (errMin, resMin) =>
for recMin in resMin
#minute.push recMin
findHour.execFind (errH, resH) =>
for recH in resH
#hour.push recH

Related

want to store promise value in an array

I want to get all the values from a registration page and store all values in an array. How can I do that in protractor?
var arr = new Array(); //declare array
InputName.getAttribute("value")
.then(function(value){
arr[0]=value; // want to store promise value in an array
});
console.log(arr[0]);
If you run your code, it will first log arr[0] and then resolve Promise. Therefore, you may access that array's values in the next Promise. Something like this
var arr = new Array(); // <- this is by the way bad practice, use 'let arr = [];'
InputName.getAttribute("value")
.then(function(value) {
arr[0]=value; // I would use arr.push(value)
});
anotherInput.getAttribute("value")
.then(function(value) {
console.log(arr[0]); // your value should be accessible here
arr.push(value) // push another value
});
But, honestly, I've been working with Protractor fo a while now and I still have difficulties understanding promises... This why I'm using async/await in my tests so if I were to implement something like that I would end up having the following
let arr = [];
let value1 = await InputName.getAttribute("value");
arr.push(value1);
console.log(arr[0]);
Clear, neat code with no hustle. Plus protractor team is actually removing promise_manager, so one day when you update it your code will not work anymore. Then why not switch earlier

Combine Mono with every Flux element emitted

I have a Flux and Mono as below:
Mono<MyRequest> req = request.bodyToMono(MyRequest.class);
Mono<List<String>> mono1 = req.map(r -> r.getList());;
Flux<Long> flux1 = req.map(r -> r.getVals()) // getVals() return list of Long
.flatMapMany(Flux::fromIterable);
Now for each number in flux1, I want to call a method where params are the id from flux1 and the List<String> from mono1. Something like,
flux1.flatMap(id -> process(id, mono1))
But passing and processing same mono1 results in error Only one connection receive subscriber allowed. How can I achieve above? Thanks!
Since both information are coming from the same source, you could just run the whole thing with one pipeline like this and wrap both elements in a Tuple or better, a domain object that has more meaning:
Mono<MyRequest> req = // ...
Flux<Tuple2<Long, List<String>>> tuples = req.flatMapMany(r ->
Flux.fromIterable(r.getVals())
.map(id -> Tuples.of(id, r.getList()))
);
// once there, you can map that with your process method like
tuples.map(tup -> process(tup.getT1(), tup.getT2());
Note that this looks unusual, and this basically comes from the structure of that object you're receiving.

What am I doing wrong with this Python class? AttributeError: 'NoneType' object has no attribute 'usernames'

Hey there I am trying to make my first class my code is as follows:
class Twitt:
def __init__(self):
self.usernames = []
self.names = []
self.tweet = []
self.imageurl = []
def twitter_lookup(self, coordinents, radius):
twitter = Twitter(auth=auth)
coordinents = coordinents + "," + radius
print coordinents
query = twitter.search.tweets(q="", geocode='33.520661,-86.80249,50mi', rpp=10)
print query
for result in query["statuses"]:
self.usernames.append(result["user"]["screen_name"])
self.names.append(result['user']["name"])
self.tweet.append(h.unescape(result["text"]))
self.imageurl.append(result['user']["profile_image_url_https"])
What I am trying to be able to do is then use my class like so:
test = Twitt()
hello = test.twitter_lookup("38.5815720,-121.4944000","1m")
print hello.usernames
This does not work and I keep getting: "AttributeError: 'NoneType' object has no attribute 'usernames'"
Maybe I just misunderstood the tutorial or am trying to use this wrong. Any help would be appreciated thanks.
I see the error is test.twitter_lookup("38.5815720,-121.4944000","1m") return nothing. If you want the usernames, you need to do
test = Twitt()
test.twitter_lookup("38.5815720,-121.4944000","1m")
test.usernames
Your function twitter_lookup is modifying the Twitt object in-place. You didn't make it return any kind of value, so when you call hello = test.twitter_lookup(), there's no return value to assign to hello, and it ends up as None. Try test.usernames instead.
Alternatively, have the twitter_lookup function put its results in some new object (perhaps a dictionary?) and return it. This is probably the more sensible solution.
Also, the function accepts a coordinents (it's 'coordinates') argument, but then throws it away and uses a hard-coded value instead.

missing context in coffeescript => operator

App.WebNotificationComponent = Em.Component.extend
subscriptionQueue: null
connection: (->
App.StompConnection.create(subscriptionQueue: #get('subscriptionQueue'))
).property('subscriptionQueue')
willDestroy: ->
#get('connection').destroy()
App.AlertsIndexAlertWebNotificationComponent = App.WebNotificationComponent.extend
subscriptionQueue: "notifications"
didInsertElement: ->
#get('connection').onMessage = ((message) ->
result = JSON.parse(message.body)
App.AlertNotification.store.find('alert_notification', result.id).then (notification) =>
debugger
).bind(#get('targetObject'))
#get('connection').connect()
At the debugger breakpoint, I am no longer able to access message or result.
Is there anything that I am doing wrong or another way to do this ?
You can't access those values in the debugger because you didn't close over them, so they're not available in the closure. If you use them in the closure, they'll be available. Javascript has to know that you're going to use a variable in order to save it in the closed scope.
In other words, this will work as expected:
result = JSON.parse(message.body)
App.AlertNotification.store.find('alert_notification', result.id).then (notification) =>
console.log(message)
console.log(result)

Passing query results in a viewbag

This seems like it should be so easy, but I've tried three or four ways to do it (but to no avail).
I'm just trying to put a query result in a viewbag and display it.
I've tried putting a model object list in a ViewBag:
var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG;
ViewBag.messages = MSG;
And then I try to spit it out in a .cshtml:
var message = (List<LemonTrader.Models.Message>)ViewBag.messages; // <--- fails here because it is a string
foreach ( var MSG in message )
{
#Html.Label(MSG.msg)<br />
}
But it says:
Cannot convert type
'System.Data.Entity.Infrastructure.DbQuery'
to
'System.Collections.Generic.List'
So it seems I'm using using the wrong template. How do I spit out a System.Entity.Infrastructure.DbQuery?
I've also tried passing the results through the Viewbag as a list of strings. (Is that a worse way to do it?)
var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG.msg;
ViewBag.messages = mesg;
And spitting it out as a string list:
foreach (var atext in ViewBag.messages as List<string>) { // gets hung up on foreach here (why???)
#Html.Label( atext )
}
And I get this:
Object reference not set to an
instance of an object.
And it points at the "foreach" keyword.
Does that mean there were no messages? Or what?
I wish there was a tutorial showing how to put queryresults in a ViewBag and how to get them out! I've seen tutorials that return an object.ToList() without respect to any kind of "where" mechanism, but no examples to pull out a few, relevant entries and display them.
Try
ViewBag.messages = MSG.ToList();
Also, System.Data.Entity.Infrastructure.DbQuery implements IEnumerable ( http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbquery(v=vs.103).aspx ) so this should also work:
var message = (IEnumerable<LemonTrader.Models.Message>)ViewBag.messages;