Call a function every X seconds when activated - Scala - scala

I have a variable which is going to help me check if 10 seconds has passed.
private val currTime: Long = System.currentTimeMillis()
private val time: Long = 10000
I want something where, if a function foo is called, it will reset currTime to be the current time. That's the easy part which I can do. The tough part, and part 2 of this, is that if currTime at any point exceeds time, I want to change a boolean (say isHappy) from true to false - this can be in a function called bar.
I come from C#, so i'm not sure how to do this - typically we'd use a dispatcher timer but i have no idea how to achieve this is Scala.
I've seen scheduler examples and fixed interval examples, but this is more of a moving target... a condition that can be met at any time.
In simpler terms, it's like having 2 ints. Int A and Int B. When the sum of A and B is over 10, a function is triggered. A and B are forever changing in different functions in that class. How can we create a trigger?

Related

How to measure time for which resource is fully occupied?

I have a resource named "Docks", its capacity is 14, I want to calculate the total time for which all the 14 docks are busy? Is there any way, please help.
I will propose a solution that may not be the most efficient one. However, it will at least guide you in the right direction. One way to do it is to create an event with the following code, noting that timeBusy would be a variable of type double:
if( resourcePool.busy() == resourcePool.size() ) {
timeBusy++;
}
Make the event of type cyclic. If you make it cyclic every second, the timeBusy variable would give you the time all resources are busy in seconds. The issue with this method is:
The smaller the cycle time, the slower the model becomes (although this line of code may not be that of an issue)
The bigger the cycle time, the lower the accuracy of the measured time.
Alternatively, a more advanced solution would be to use the On Seize and On Release fields of the resource pool, where you can add your code to check the number of busy units each time a resource is seized or released only and not every cycle time. The main idea of this method would be to use three variables: startTime and totalTime of type double and start of type boolean with an initial value of false. So On Seize you would write:
if( resourcePool.busy() == resourcePool.size() && !start ) {
startTime = time();
start = true;
}
And On Release:
if( resourcePool.busy() == resourcePool.size() - 1 && start ) {
totalTime += time() - startTime;
start = false;
}
You may need to validate the results, but this should at least put you in the right direction.
The only downside of this method is that results are only updated when a resource is seized or released. So if for example, all your resources are seized for a long time, you may not see any changes to the variables.
Depending on your model, you can judge which method works better for you.
One final note is that you can opt to have a hybrid method to ensure live updates and 100% accuracy.
I would personally go for the first method if your model is relatively simple.

views in collections in scala

I understand that a view is a light-weight collection and that it is lazy. I would like to understand what makes a view light weight.
Say I have a list of 1000 random numbers. I'll like to find even numbers in this list and pick only 1st 10 even numbers. I believe using a view here is better because we can avoid creating an intermediate list esp because I'll pick only 1st 10 even numbers. Initially, I thought that the the optimization is achieved because the function I'll use in the filter method will not get executed till the method force is called but this isn't correct I believe. I am struggling to understand what makes using the view better in this scenario. Or have I picked a wrong example?
val r = scala.util.Random
val l:List[Int] = List.tabulate(1000)(x=>r.nextInt())
//without view, I'll get an intermediate list. The function x%2==0 will be on each elemenet of l
val l1 = l.filter(x=>(x%2 == 0))
//this will give size of l2. I got size as 508 but yours could be different depending on the random numbers generated in your case
l1.size
//pick 1st 10 even numbers
val l2 = l1.take(10)
//using view. I thought that x%2==0 will not be executed right now
val lv1 = l.view.filter(x=>(x%2 == 0))
lv1: scala.collection.SeqView[Int,List[Int]] = SeqViewF(...)
lv1.size //this is same as l1 size so my assumption that x%2==0 will not be executed is wrong else lv1.size will not be same as l1.size
val lv2 = lv1.take(10).force
**Question 1 - if I use view, how is the processing optimised?
Question 2 - lv1 is of type SeqViewF, F is related to filter but what does it mean?
Question 3 - what do the elements of lv1 look like (l1 for example are integers)**
You wrote:
lv1.size //this is same as l1 size so my assumption that x%2==0 will
not be executed is wrong else lv1.size will not be same as l1.size
Your assumption is actually correct it's just that your means of measuring the difference is faulty.
val l:List[Int] = List.fill(10)(util.Random.nextInt) // ten random Ints
// print every Int that gets tested in the filter
val lv1 = l.view.filter{x => println(x); x%2 == 0} // no lines printed
lv1.size // ten Ints sent to STDOUT
So, as you see, taking the size of your view also forces its completion.
Yeah, that's not a very fitting example. What you are doing is better done with an iterator: list.filter(_ % 2 == 0).take(10). This doesn't create intermediate collections, and does not scan the list past the first 10 even elements (view wouldn't either, it's just a bit of an overcomplication for this case).
A view is a sequence of delayed operations. It has a reference to the collection, and a bunch of operations to be applied when it is forced. The way operations to be applied are recorded is rather complicated, and not really important. You guessed right - SeqViewF means a view of a sequence with a filter applied. If you map over it, you'll get a SeqViewFM etc.
When would this be needed?
One example is when you need to "massage" a sequence that you are passing somewhere else. Suppose, you have a function, that combines elements of a sequence you pass in somehow:
def combine(s: Seq[Int]) = s.iterator.zipWithIndex.map {
case(x, i) if i % 2 == 0 => x
case(x, _) => -x
}.sum
Now, suppose, you have a huge stream of numbers, and you want to combine only even ones, while dropping the others. You can use your existing function for that:
val result = combine(stream.view.filter(_ % 2 == 0))
Of course, if combine parameter was declared as iterator to begin with, you would not need the view again, but that is not always possible, sometimes you just have to use some standard interface, that just wants a sequence.
Here is a fancier example, that also takes advantage of the fact that the elements are computed on access:
def notifyUsers(users: Seq[User]) = users
.iterator
.filter(_.needsNotification)
.foreach(_.notify)
timer.schedule(60 seconds) { notifyUsers(userIDs.view.map(getUser)) }
So, I have some ids of the users that may need to be notified of some external events. I have them stored in userIDs.
Every minute a task runs, that finds all users that need to be notified, and sends a notification to each of them.
Here is the trick: notifyUsers takes a collection of User as a parameter. But what we are really passing in is a view, composed of the initial set of user ids, and a .map operation, getting the User object for each of them. As a result, every time the task runs, a new User object will be obtained for each id (perhaps, from the database), so, if the _needsNotification flag gets changed, the new value is picked up.
Surely, I could change notifyUsers to receive the list of ids, and do getUser on its own instead, but that wouldn't be as neat. First, this way, it is easier to unit-test - I can just pass an a list of test objects directly in, without bothering to mock out getUser. And second, a generic utility like this is more useful - a User could be a trait, for example, that could be representing many different domain objects.

clearer explanation of function level scope for recursion

This is an example from the book 'Matlab for Neuroscientists'. I don't understand the order in which, or why, g gets assigned a new value after each recursion. Nor do I understand why "factorial2" is included in the final line of code.
here is a link to the text
Basically, I am asking for someone to re-word the authors explanation (circled in red) of how the function works, as if they were explaining the concept and processes to a 5-year old. I'm brand new to programming. I thought I understood how this worked from reading another book, but now this authors explanation is causing nothing but confusion. Many thanks to anyone who can help!!
A recursive method works by breaking a larger problem into smaller problems each time the method is called. This allows you to break what would be a difficult problem; a factorial summation, into a series of smaller problems.
Each recursive function has 2 parts:
1) The base case: The lowest value that we care about evaluating. Usually this goes to zero or one.
if (num == 1)
out = 1;
end
2) The general case: The general case is what we are going to call until we reach the base case. We call the function again, but this time with 1 less than the previous function started with. This allows us to work our way towards the base case.
out = num + factorial(num-1);
This statement means that we are going to firstly call the function with 1 less than what this function with; we started with three, the next call starts with two, the call after that starts with 1 (Which triggers our base case!)
Once our base case is reached, the methods "recurse-out". This means they bounce backwards, back into the function that called it, bringing all the data from the functions below it!It is at this point that our summation actually occurs.
Once the original function is reached, we have our final summation.
For example, let's say you want the summation of the first 3 integers.
The first recursive call is passed the number 3.
function [out] = factorial(num)
%//Base case
if (num == 1)
out = 1;
end
%//General case
out = num + factorial(num-1);
Walking through the function calls:
factorial(3); //Initial function call
//Becomes..
factorial(1) + factorial(2) + factorial(3) = returned value
This gives us a result of 6!

Assign a value to a variable for a limited time only

Let's say that there is a boolean variable, initially assigned the value false. Is there a way to say, let this variable be true for the next 5 minutes and then let it be false again?
My current idea is that I could store the variable along with a timestamp, then as soon as the variable is turned to true, the timestamp is set to the current time, then check the variable's value through a method that will return true if the current time and the initial timestamp form a duration of less than 5 minutes and then false if the duration is greater than 5 minutes. I'm thinking about an implicit conversion from Boolean to a RichBoolean that would handle this mechanism through an elegant method name or something.
Is there a more elegant or Scala native way of doing this?
The timestamp idea is pretty easy to implement (here the argument is in seconds):
class TransientlyTrue(duration: Double) {
private[this] val createdAt = System.nanoTime
def value = (System.nanoTime-createdAt)*1e-9 <= duration
}
implicit def TransientToBoolean(t: TransientlyTrue) = t.value
With the implicit conversion you can transparently drop this in wherever you need a Boolean. Or you could leave that off and just call .value.
You may be able to accomplish what you want more elegantly with futures. You won't have a proper variable that's changing its value, but it's not clear that that's an absolute requirement in your question, and you will have a method that starts returning a different value after a certain amount of time. For example, with Twitter's implementation:
import com.twitter.util._
import com.twitter.conversions.time._
implicit val timer = new JavaTimer
val t = Future.sleep(10.seconds)
Now t.isDone will be false for ten seconds and then true. The nice thing about this approach is that you get lots of other combinators on the future that may allow you to solve your problem more directly—see the Scala documentation for more information.
Would you be okay with a wrapper object for this? Like TimedBoolean? If so, then you could do something pretty straight forward with either a Timer, or just on your getter and setter do a timestamp check..
To directly answer your question, though, no, there's no Scala native way of doing this. But I'd think that a wrapper method is the "more elegant" way you're looking for.

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.