In CoffeeScript, is it possible to increment a for loop manually? - coffeescript

My CoffeeScript is as follows:
for i in [1..3]
i++ if i is 1
console.log i
Expected output is
2
3
Generated output is
2
2
3
The issue is that CoffeeScript keeps a private variable to keep track of the iteration, _i, but if I try to increment that _i++, then the private variable changes to _j and constantly evades me.
So how can I increment the loop manually using CoffeeScript?

You can't manually increment the loop's counting variable. Instead, you need to use continue to skip one or more iterations.
for i in [1..3]
continue if i is 1
console.log i
You should never attempt to access or modify CoffeeScript's generate variables, those are an implementation detail and you cannot rely on them being present.

Related

Is BPF_LOOP for Linkedlist iteration, viable?, if not what other way I can do it

I am trying to iterate a linked list in BPF, can I use bpf_loop for this?, if so how?
Tried using bpf_loops, but it required a fixed number to bound the loops, what way I can do that?
These are the comments for bpf_loop.
bpf_loop
For nr_loops, call callback_fn function
with callback_ctx as the context parameter.
The callback_fn should be a static function and
the callback_ctx should be a pointer to the stack.
The flags is used to control certain aspects of the helper.
Currently, the flags must be 0. Currently, nr_loops is
limited to 1 << 23 (~8 million) loops.
long (*callback_fn)(u32 index, void *ctx);
where index is the current index in the loop. The index
is zero-indexed.
If callback_fn returns 0, the helper will continue to the next
loop. If return value is 1, the helper will skip the rest of
the loops and return. Other return values are not used now,
and will be rejected by the verifier.
Returns
The number of loops performed, -EINVAL for invalid flags,
-E2BIG if nr_loops exceeds the maximum number of loops.
You can pass the linked list via the callback_ctx which is shared between iterations.
You can hardcode the number of loops to the max of 1 << 23 (~8 million) (perhaps less, it depends on how the verifier imposes penalties).
If you can advance the linked list you do so and perform whatever logic you want.
If you are done or at the end of the linked list you return 1 to
break out of the loop.
If you expect to need more than 8M iterations, you can at least detect when you are not done by looking at the return value (perhaps running a second loop, I don't know if that is allowed or not)

Counter doesn't count up

while True:
def update():
global counter
global points
counter = points
counter = 0
points = counter + 1
print(points)
First off I am very new to this I am wonder my simple counter only print 1 instead of counting up.
Your indentation is off. Also some of your code seems to not be of use for what you're outputting.
Try this:
counter = 0
while True:
counter = counter + 1
print(counter)
I'm not sure why you are using two variables. The points variable isn't doing anything. Also you never call the update() function if you were trying to do that.
Maybe go read the Python Tutorial? Because you seem a little lost.
Happy Coding!
When posting Python please take care to maintain the indents (the spaces before each line of your code), because they are critical to how Python programs work.
You have placed the definition of the update() function inside the while loop. Defining a function is not the same as running it, so the update would not actually be carried out as part of the loop. There is pretty much no reason to put a function definition inside a while loop.
It would also be better for update() not to be a function, since it depends on both variables being global and does not really have any useful function once parameterized.
The reset of counter to 0 is also inside the loop. This means that the counter resets every time around the loop, which is why it keeps printing 1.
This will work, although unless you have a reason for using the variable points it would be better not to since you only actually need counter:
counter = 0
while True:
points = counter + 1
counter = points
print(points)
A python program,print a number starting from 0.
def update():
counter = 0
while(True):
print(counter)
counter = counter + 1
update()

How do for-in loops in swift work?

I've used them, I'm familiar with the code and read a number tutorials but I still don't understand exactly how they work in that I can't run through my head what I'm doing and ultimately what I want to achieve, as opposed to say an if statement which can be read in English quite well.
For-loops have always been something I've struggled with through lack of understanding, can someone offer some insight please?
The for-in loop performs a set of statements for each item in a range or collection. Swift also provides two range operators a..<b and a...b, as a shortcut for expressing a range of values.
// prints 1-10
for i in 1...10 {
print(i)
}
// This way has been removed in Swift 3 so use the above
for var i = 1; i <= 10; i+=1 {
print(i)
}
The for-in loop is used for iterations on numbers, items in an array or characters in a string.
//I want my var res to be equal to 10:
for var nb = 0 in 0..10 {
nb += 1
print("my nb is \(nb)"
}
To understand for loops, one needs to understand the need for repeating lines of code (an unrolled loop) for a bunch of sequential numbers or array elements, etc. A "for-loop" tells the processor to do most of the repetition for you, without the need for you to copy-paste all those nearly identical lines of code a whole bunch (maybe millions or billions) of times.
A "for in" loop lets you specify the range (of numbers or array elements, etc.) over which you want the repetition, so the code doesn't go on repeating forever.

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.

Matlab: recursive algorithm to return the run count easily without profiler?

I would like to get the number of iterations that the recursive mlfnonneg requires. Currently, I use profiler for this but it would be more useful to get the number as a return value from the function. Is there any easy way to get it?
I measure the running time of a function like this
h=#() mlfnonneg(lb,ub,mlfBinCor,method);
tElapsed=timeit(h);
and now the function mlfnonneg should return the number of iterations. I have considered adding a ticker that the function always returns but I don't know how to get the return value after using timeit. How to get the running time and the running count of the recursive algorithm elegantly?
You can always add an optional return value to a function which you can use as a counter. Something like this:
[... count] = f(...)
% Do stuff here
if <some condition>
% Recurse
[... count] = f(...);
count = count + 1;
else
% Terminal condition
count = 1;
end
You should just call your function one more time to get the count. This should not be a significant problem, since timeit actually performs multiple calls to your function to get an average metric.
I don't know if this is an option for you - but you could create a global variable IT_COUNT that you declare both at the top level, and inside your function.
Before calling timeit() you set the variable to zero; inside the routine you increment it for every loop. When the function returns you print out the result - and there is your answer.
It does depend on you being able to modify the code to mlfnonneg to include the counter. I don't see an easy way around that, but maybe others have a better idea.
update inspired by Luis Mendo's (now deleted) answer that basically says the same thing, a bit more information.
In your mlfnonneg routine, add the following two lines (in a place where they are executed "once per iteration"):
global IT_COUNT;
if numel(IT_COUNT)==0, IT_COUNT = 1; else IT_COUNT = IT_COUNT + 1; end
This ensures that if you forget to create the variable at the top level, the code will not crash (you will thank me in the future, when you re-use this code and don't remember that you need a global variable...)
At the top level, add
global IT_COUNT
IT_COUNT = 0;
Then run your timeit() routine; finally use
fprintf(1, "The number of iterations was %d\n", IT_COUNT);
to get the answer you were looking for.