Callbacks only see last value from loop - coffeescript

I have this code:
for food in foods
Person.eat ->
console.log food
The problem here is that "food" will always be the last "food" in "foods". That is because I have the console.log in a callback function.
How can I preserve the value in the current iteration?

You need to close over the value of a loop if you want to geneate functions to run later. This what coffee provides the do keyword for.
for food in foods
do (food) ->
Person.eat ->
console.log food
See this example:
https://gist.github.com/c8329fdec424de9c57ca
This occurs because your loop body has a reference to the food variable which changes values each time though the loop, and when you function if finds the closure the function was created in and finds that food variable set to the last value of the array. Using another function to in order to create a new scope solves the problem.

Related

How to implement Recursive Paginated Network Call using RxSwift

I have an endpoint that returns the items of the current page. Also, if you want to get next page's items, you have to construct a URL with the next page's hash. This hash returns as property in the response of the previous request. As you understand, we need a recursive network call.
When a request finishes, a new request will begin until hash returns null through the response.
Then, I need to bind all collected data into an array.
How can I build something like that in RxSwift? I would appreciate if you describe that concept.
You need something like this: https://gist.github.com/danielt1263/ec1032375498eb95aa260239b289d263
/**
Calls `producer` with `seed` then emits result and also passes it to `pred`. Will continue to call `producer` with new values as long as `pred` returns values.
- parameter seed: The starting value needed for the first producer call.
- parameter pred: This closure determines what the next value pass into producer should be or returns nil if no more calls are necessary.
- parameter producer: The function that produces the Single result.
- returns: An observable that emits each producer's value.
*/
func emitWhile<T, U>(seed: U, pred: #escaping (T) -> U?, producer: #escaping (U) -> Single<T>) -> Observable<T>
The seed is the hash for the first page. The pred takes the result of a network request, extracts the hash for the next page and returns it (or returns nil if there is no next page.) The producer takes the hash and returns an observable that will make the request for the page when it is subscribed to.
You will likely want to collect all the elements using either scan or reduce to emit all of the pages as a single array.

MATLAB equivalent to Python argmax with array of user defined objects

I have an array as shown here. Here Bandit is a class that I created.
bandits = [Bandit(m1),Bandit(m2),Bandit(m3)];
Now, I want to do the following. Following is Python code which immediately gives me the maxarg of the value of the mean of each of these objects.
j = np.argmax([b.mean for b in bandits])
How can I do the same in MATLAB? To give more clarity, every bandit object has an attribute mean_value. I.e. if b1 is a bandit object, then I can get that value using dot operator (b1.mean_value). I want to find which among b1, b2, b3 has maximum mean_val and need to get the index for it. (See the python code above. If b2 has the highest mean_val, then finally, j will contain index 2.)
arrayfun applies a function to each element of an array. It results in a new array with the results of the operation. To this result you can then apply max as usual:
[~,arg] = max(arrayfun(#mean,bandits));
Note that this might not work if you have overloaded the subsref or size methods for the Bandit class.
Edit:
So now I understand that mean was not a function but an attribute. The operation x.mean can be expressed as the function call subsref(x,substruct('.','mean')). Thus, it is possible to change the solution above to call this function on each array element:
op = #(x)subsref(x,substruct('.','mean'))
[~,arg] = max(arrayfun(op,bandits));
That is, instead of calling the function mean, we call the function subsref to index the attribute mean.
If bandits is a simple struct array, then the following will work also:
[~,arg] = max([bandits.mean]);
Here, bandits.mean will extract the mean value for each element of the struct array, yielding a comma-separated list. This list is captured with the square brackets to form a vector. This vector is again input into the max function as usual.
I'm not sure if this latter solution works also for custom classes. I don't have your Bandit class to test. Please let me know if this latter solution works, so I can update the post with correct information.

Drools from clause not working

The most basic use of from clause is not working, even when I know there are elements in the list and there is no conditions for the elements being extracted from that list, and I have other rules working properly.
Here is what happens, there are many variables in my problem, but I have simplified to this:
Having this two rules, the firstone is made to demostrate that fixedShipmentValueData list, has at least one element. However, the second rule isn't fired, even when the only different thing it does from the firstone, is to use the from clause and put a variable name.
rule "Print list value"
ruleflow-group "fixed-values"
no-loop
when
cParams: CustomerParameters(list: fixedShipmentValueData)
then
System.out.format("There are %s elements at fixedShipmentValue and fixed value is %s%n",list.size(),
((ParameterValues)list.get(0)).getFixedShipmentValue());
end
rule "Do something with the list"
ruleflow-group "fixed-values"
no-loop
when
cParams: CustomerParameters(list: fixedShipmentValueData)
ParameterValues($fixedShipmentValue: fixedShipmentValue) from list
then
System.out.format("fixed Shipment Value is %s%n", $fixedShipmentValue);
end
This looks so simple... I have expent enough time as to be out of ideas.
Without seeing the Java code for CustomerParameters, ParameterValues and the application part that creates, composes and inserts the fact(s) there's just one scenario I know that can reproduce the effect as you have told it. Consider this:
A List<Base> is field list in class X. There are subclasses SubA and SubB both extending Base. Create X, add objects of class SubA to list. A rule (like "Print list value") will show that the list is not empty.
However, a rule using a pattern such as
X( $list: list )
SubB() from $list
will never fire, since there are no SubB's in Base.list.

Rx Observable Window with closing function with parameter

I'm trying to separate observable into windows (or for my purposes also Buffers are fine) while being able to close windows/buffers at custom location.
E.g. I have an observable which produces integers starting at 1 and moving up. I want to close a window at each number which is divisible by 7. My closing function would need to take in the item as parameter in that case.
There is an overload of Window method:
Window<TSource, TWindowClosing>(IObservable<TSource>, Func<IObservable<TWindowClosing>>)
Either it cant be done using this overload, or I can't wrap my head around it. Documentation describes that it does exactly what I want but does not show an example. Also, it shows an example of non-deterministic closing, which depends on timing when closing observable collection emits items.
The Window operator breaks up an observable sequence into consecutive
non-overlapping windows. The end of the current window and start of
the next window is controlled by an observable sequence which is the
result of the windowClosingSelect function which is passed as an input
parameter to the operator. The operator could be used to group a set
of events into a window. For example, states of a transaction could be
the main sequence being observed. Those states could include:
Preparing, Prepared, Active, and Committed/Aborted. The main sequence
could include all of those states are they occur in that order. The
windowClosingSelect function could return an observable sequence that
only produces a value on the Committed or Abort states. This would
close the window that represented transaction events for a particular
transaction.
I'm thinking something like following would do the job, but I'd have to implement it myself:
Window<TSource, TWindowClosing>(IObservable<TSource>, Func<TSource, bool>)
Is such windowing possible with built-in functions (I know I can build one myself)?
Is it possible to close a window based on emitted item or only non-deterministically, once an item is emitted from windowing observable?
Use the original sequence with a Where clause as your closing sequence. If your source sequence is cold, then make use of Publish and RefCount to make it work correctly.
var source = ...;
var sharedSource = source.Publish().RefCount();
var closingSignal = sharedSource.Where(i => (i % 7) == 0);
var windows = sharedSource.Window(() => closingSignal);

Interpret line of Q code

Trying to understand what this function does:
yr:{ yr:.z.T+1000*x; -1 string .z.Z; while[(.z.T < yr); ZZ,::.z.Z]}
I understand .z.Z gets the datetime, and that execution is from right to left. what is ZZ? What is .z.T?
Essentially, what does the line accomplish?
Here :: means assign the value on the right to the global variable on
the left
ZZ is a global variable
ZZ,::.z.Z is shorthand for ZZ::ZZ,.z.Z
So it appends the latest time to the global variable ZZ.
e.g.
q)f:{ZZ,::2}
q)f[]
q)ZZ
,2
q)f[]
q)ZZ
2 2
.z.T is the time.
.z.T is the current time in the time datatype; the underlying number in times is milliseconds since midnight, so adding 1000*x gives a time x seconds in the future.
-1 string .z.Z prints the current datetime to stdout.
while[(.z.T < yr); ..] loops as long as the current time is less than yr (x seconds in the future).
ZZ,::.z.Z appends the current datetime to a global variable named ZZ.
some additional notes:
the datetime datatype is in general deprecated in favor of timestamp.
the parentheses around the test condition are redundant.
the second : is also redundant, but for more interesting reasons: ,: (like all of the two-argument "writeback" functions (x+:1, y-:2, etc.)) always modifies either a global or a local variable, depending on whether a local of that name exists in the function.
proof:
q)delete from`.;
q){ZZ:(); yr:.z.T+1000*x; -1 string .z.Z; while[(.z.T < yr); ZZ,::.z.Z]}1
2014.04.30T18:26:24.592
q)ZZ
'ZZ
q)
the ZZ being modified inside the while loop in that version of the function was the local variable declared in the first statement, not a global one as one might assume given the presence of a :: in the modification statement.
anyway, if you want to do it like this, it should at the very least be rewritten to yr:{ yr:.z.T+1000*x; -1 string .z.Z; while[.z.T < yr; ZZ,:.z.Z]}.
There is a nicer rewrite of this to make it much more idiomatic. It takes advantage of the overload of \ to iterate. Check out http://code.kx.com/q/ref/adverbs/#converge-iterate
The current function you have, takes the current time (.z.T) and adds x number of seconds (it multiplies by 1000 to make it milliseconds). This becomes your bound, and then as long as the current time is less than that, you append .z.Z (the datetime marker) to a global list ZZ.
The version below will do the same with a couple advantages:you avoid using a global and you write more idiomatic code
f2:{{.z.Z}\[{y; .z.T<x}.z.T+1e3*x; .z.Z]}
While your condition {y; .z.T<x}.z.T+1e3*x is true, your loop will continue to iterate. Note that we make sure to pass in the time limit from outside, so that it is not revaluated it each time, additionally we need a dummy parameter y, as it will try to apply this condition to the result of our iteration, but we don't really want that, since that is .z.Z. Each time it iterates it will evaluate .z.Z returning the datetime. Since you are using \ and not / you will get the entire list generated.
q)f2:{{.z.Z}\[{y; .z.T<x}.z.T+1e3*x; .z.Z]}
q)f2 1
2014.04.30T17:40:23.357 2014.04.30T17:40:23.357 .......
That being said, if you're looking to generate a sequence of datetime values, from now to now+x, this is not the best way to do that, since your .z.Z stamp will reflect the time it takes your machine to actually evaluate that.
CORRECTION:
I did not correctly explain the reason our condition testing lambda is {y; .z.T<x}.z.T+1e3*x. You want to make sure your .z.T+1e3*x is only evaluated at the start, so you do not want your bound to be inside the function. Additionally, if you were to leave out the y param, then {z.T<x}.z.T+1e3*x would immediately evaluate to false, and your iteration would return a type error as it tries to apply your iteration result to 0b at each cycle of the loop. By keeping y and just not using it, we make sure to delay this evaluation and create a lambda that correctly tests our bound.
What This Function is doing:
This function accepts one parameter(should be int) and add those many seconds to current time(lets say it future time). Then it starts a loop from current time to future time and in every iteration, append current date and time to global list(referred by variable ZZ).
How to Call: yr[2]
Explanation:
yr:.z.T+1000*x
.z.T give you current local time.
1000 is equivalent to 1 seconds. So it is adding x seconds to current time and storing it in variable yr. ( : means assignment (=))
ZZ,::.z.Z
:: is used to assign something to global variable. So ZZ is a
global variable which is list (like array).
, is used to append. Above statement is equivalent to ZZ : ZZ , .z.Z
.z.Z gives current local date and time.
while[(.z.T < yr);...]
This is a condition for the loop. So it takes the current time(.z.T)
and check whether it is lesser than future time that was calculated
in first statement.
Loop will end once current time =yr(future time).
Finally you'll have global list which you can access using variable
ZZ.