Are all Instants comparable or are they machine-dependent in Perl 6? - raku

This is a case where I can find the definition, but I don't quite grasp it. From the official documentation:
An Instant is a particular moment in time measured in atomic seconds, with fractions. It is not tied to or aware of any epoch.
I don't understand how you can specify a particular moment in time without having an epoch? Doesn't it have a reference point? On two different Linux machines it seemed that both Instants referred to seconds since the POSIX Epoch. My guess is that Instants do have an effective start time, but that that start time is implementation/device dependent.
# machine1
say(now * (1/3600) * (1/24) * (1/365.25)); # years from zero point
46.0748226200715
# machine2
say(now * (1/3600) * (1/24) * (1/365.25)); # years from zero point
46.0748712024946
Anyway, so my question is, can Instants be relied upon to be consistent between different processes or are they for "Internal" use only?

say (now).WHAT; # «(Instant)␤»
say (now * 1).WHAT # «(Num)␤»
Any numerical operator will coerce it's operands into Nums. If you want a proper string representation use .perl .
say (now).perl # «Instant.from-posix((<1211194481492/833>, 0))␤»
No matter what platform you are on, Instant.from-posix will always be relative to the Unix epoch.
see: https://github.com/rakudo/rakudo/blob/nom/src/core/Instant.pm#L15

All Instant objects currently on a particular machine are comparable, Instants from different machines may not be.
For practical purposes, on POSIX machines it is currently based on the number of seconds since January 1st, 1970 according to International Atomic Time (TAI), which is currently 36 seconds ahead of Coordinated Universal Time (UTC).
(This should not be relied upon even if you know your code will only ever be run on a POSIX machine)
On another system it may make more sense for it to be based on the amount of time since the machine was turned on.
So after a reboot, any Instants from before the reboot will not be comparable to any after it.
If you want to compare the Instants from different machines, or store them for later use, convert it to a standardized value.
There are several built-in converters you can use
# runtime constant-like term
my \init = INIT now;
say init.to-posix.perl;
# (1454172565.36938, Bool::False)
say init.DateTime.Str; # now.DateTime =~= DateTime.now
# 2016-01-30T16:49:25.369380Z
say init.Date.Str; # now.Date =~= Date.today
# 2016-01-30
say init.DateTime.yyyy-mm-dd eq init.Date.Str;
# True
I would recommend just using DateTime objects if you need more than what is shown above, as it has various useful methods.
my $now = DateTime.now;
say $now.Str;
# 2016-01-30T11:29:14.928520-06:00
say $now.truncated-to('day').utc.Str;
# 2016-01-30T06:00:00Z
# ^
say $now.utc.truncated-to('day').Str;
# 2016-01-30T00:00:00Z
# ^
Date.today and DateTime.now take into consideration your local timezone information, where as now.Date and now.DateTime can't.
If you really only want to deal with POSIX times you can use time which is roughly the same as now.to-posix[0].Int.

Related

Redis time jumps forward and goes backwards

This script shows that the timestamp that redis returns seems to jump forward a lot and then go backwards from time to time. This happens regularly throughout the run, on every run. What's going on? Is this documented anywhere? I stumbled on this as it messes up my sliding window rate limiter.
res_0, res_1 = 0, 0
for _ in range(200):
script = f"""
local time = redis.call("TIME")
local current_time = time[1] .. "." .. time[2]
return current_time
"""
res_0 = res_1
res_1 = float(await redis.eval(script, numkeys=0))
print(res_1 - res_0)
time.sleep(0.01)
1667745169.747809
0.011765003204345703
0.01197195053100586
0.011564016342163086
0.011634111404418945
0.012428998947143555
0.011847972869873047
0.011600971221923828
0.011788129806518555
0.012033939361572266
0.012130022048950195
0.01160883903503418
0.011954069137573242
0.012022972106933594
0.011958122253417969
0.011713981628417969
0.011844873428344727
0.012138128280639648
0.011618852615356445
0.011570215225219727
0.011890888214111328
0.011478900909423828
0.7928261756896973
-0.5926899909973145
0.11812996864318848
0.11584997177124023
0.12353992462158203
0.1199800968170166
0.11719989776611328
0.12331008911132812
-0.8117339611053467
0.011723995208740234
0.01131582260131836
The most likely reason for this behavior is floating point arithmetic on the calling code side: parsing floats would inevitably round (not sure about the extent, since you didn't tell what platform you are coding against) the input value and the original result precision is lost. So, I would suggest to review your logic so that you process the two components of the result returned by TIME independently using a couple of integers / longs instead.
In addition to that, apart from the obvious possibility of an issue with the clock of the Redis server, there may also be the chance you are contacting different Redis hosts along with each iteration - this may hold true in the event you are using a multi-node Redis topology (replication or cluster).

SUMO - simulating traffic scenario

How can I simulate continuous traffic flow from historical data which consists of:
1. Vehicle ID;
2. Speed;
3. Coordinates
without knowing the routes of each vehicle ID.
This is a commonly asked questions but probably hasn't been answered here before. Unfortunately the answer largely depends on the quality of your input data mainly on the frequency / distance of your location updates (it would be also helpful if there is a time stamp to each datum) and how precise the locations fit your street network. In the best case there is a location update on each edge of the route in the street network and you can simply read off the route by mapping the location to the street. This mapping can be done using the python sumolib coming with sumo:
import sumolib
net = sumolib.net.readNet("myNet.net.xml")
route = []
radius = 1
for x, y in coordinates:
minDist, minEdge = min([(dist, edge) for edge, dist in net.getNeighboringEdges(x_coordinate, y_coordinate, radius)])
if len(route) == 0 or route[-1] != minEdge.getID():
route.append(minEdge.getID())
See also http://sumo.dlr.de/wiki/Tools/Sumolib#locate_nearby_edges_based_on_the_geo-coordinate for additional geo conversion.
This will fail when there is an edge in the route which did not get hit by a data point or if you have a mismatch (for instance matching an edge which goes in the "wrong" direction). In the former case you can easily repair the route using sumo's duarouter.
> duarouter -n myNet.net.xml -r myRoutesWithGaps.rou.xml -o myRepairedRoutes.rou.xml --repair
The latter case is considerably harder both to detect and to repair because it largely depends on your definition of a wrong edge. There are almost clear cases like hitting suddenly the opposite direction (which still can happen in real traffic) and a lot of small detours which are hard to decide and deserve a separate answer.
Since you are asking for continuous input you may also be interested in doing this live with TraCI and in this FAQ on constant input flow.

How to write a random choice function in JES

How do I write a (short) function in JES to choose, and return, a random quotation from all of the quotations stored in a specific file.
def readSaying():
import random
file=open('C:/computer course/assignment 5/assignment5sayings.txt',"rt")
contents=file.read()
file.close()
random.seed()
print random.choice(contents)
Update
so it looks like by adding random.seed() it is reading my file but it is just choosing 1 letter-how do I get it to choose a whole quote
eg to choose 1 of these quotes:
"Any sufficiently advanced bug is indistinguishable from a feature" - Kulawiec
"By the year 2020, there will be a whole new industry built on remembering the year 2000" - Alvin Toffler
"You can lead a boy to college, but you cannot make him think" - Elbert Hubbard
"Many people would rather die than think; in fact, most do" - Bertrand Russell
You probably need to seed your random number generator. Place random.seed() before your random.choice(contents)
9.4. random — Generate pseudo-random numbers
random.seed([x])
Initialize the basic random number generator. Optional argument x can be any hashable object. If x is omitted or None, current system time is used; current system time is also used to initialize the generator when the module is first imported. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).
Changed in version 2.4: formerly, operating system resources were not used.
If x is not None or an int or long, hash(x) is used instead. If x is an int or long, x is used directly.

Advice for bit level manipulation

I'm currently working on a project that involves a lot of bit level manipulation of data such as comparison, masking and shifting. Essentially I need to search through chunks of bitstreams between 8kbytes - 32kbytes long for bit patterns between 20 - 40bytes long.
Does anyone know of general resources for optimizing for such operations in CUDA?
There has been a least a couple of questions on SO on how to do text searches with CUDA. That is, finding instances of short byte-strings in long byte-strings. That is similar to what you want to do. That is, a byte-string search is much like a bit-string search where the number of bits in the byte-string can only be a multiple of 8, and the algorithm only checks for matches every 8 bits. Search on SO for CUDA string searching or matching, and see if you can find them.
I don't know of any general resources for this, but I would try something like this:
Start by preparing 8 versions of each of the search bit-strings. Each bit-string shifted a different number of bits. Also prepare start and end masks:
start
01111111
00111111
...
00000001
end
10000000
11000000
...
11111110
Then, essentially, perform byte-string searches with the different bit-strings and masks.
If you're using a device with compute capability >= 2.0, store the shifted bit-strings in global memory. The start and end masks can probably just be constants in your program.
Then, for each byte position, launch 8 threads that each checks a different version of the 8 shifted bit-strings against the long bit-string (which you now treat like a byte-string). In each block, launch enough threads to check, for instance, 32 bytes, so that the total number of threads per block becomes 32 * 8 = 256. The L1 cache should be able to hold the shifted bit-strings for each block, so that you get good performance.

If passing a negative number to taskDelay function in vxworks, what happens?

Noted that the parameter of taskDelay is of type int, which means the number could be negative. Just wondering how the function is going to react when passing a negative number.
Most functions would validate the input, and just return early/return 0/set the parameter in question to a default value.
I presume there's no critical need to do this in production, and you probably have some code lying around that you could test with.... why not give it a go?
The documentation doesn't address it, and the only error codes they do define doesn't cover this case. The most correct answer therefore is that the results are undefined.
See the VxWorks / Tornado II FAQ for this gem, however:
taskDelay(-1) shows another bug in
the vxWorks timer/tick code. It has
the (side) effect of setting vxTicks
to zero. This corrupts the localtime
(and probably other things). In fact
taskDelay(x) will have the same effect
if vxTicks + x >= 0x100000000. If the
system clock rate is 100Hz this
happens after about 500 days (because
vxTicks wraps). At faster clock rates
it will happen sooner. Anyone trying
for several years uptime?
Oh there is an undocumented upper
limit on the clock rate. At rates
above 4294 select() will fail to
convert its 'usec' time into the
correct number of ticks. (From: David
Laight, dsl#tadpole.co.uk)
Assuming this bug is old, I would hope that it would either return an error or do the same thing as taskDelay(0), which puts your task at the end of the ready queue.
The task delay tick will be VIRTUALLY 10,9,..,1,0 for taskDelay(10).
The task delay tick will be VIRTUALLY -10,-11,...,-2147483648,2147483647,...,1,0 for taskDelay(-10).