Is there a way to seed a random number generator in Opal? srand doesn't seem to do anything, and using the Random class directly errors out with NameError: uninitialized constant Object::Random.
Not at the moment.
There's an open PR that should fix this, but it's kinda stalled
https://github.com/opal/opal/pull/657
Would need someone to pick up and complete the work that was started.
Related
From Hashrockets blog post on "The Adventures of Generating Random Numbers in Erlang and Elixir" Dorian Karter mentions that opening and closing erl sessions allows him to reproduce the same output from the PRNG random:uniform()..
Turns out random uses the same seed by default for every VM instance.
E.G:
Session one
1> random:uniform().
0.4435846174457203
Session two
1> random:uniform().
0.4435846174457203
I can't seem to find in documentation, or my searches across the net if calling the seed methods will apply to the whole VM, or to the process that calls the seed method only.
The question:
In Elixir, would you need to call the seed (for both random or rand) function per erlang process? Or does one call ~somewhere~ apply across the entire Erlang runtime?
The rand module supersedes the random module:
The improved rand module is to be used instead of this module.
However with the rand module:
If a process calls uniform/0, uniform/1 or uniform_real/0 without setting a seed first, seed/1 is called automatically with the default algorithm and creates a non-constant seed.
So you'll have different results after VM restart with rand:uniform/0.
However if you use randomness for cryptography purpose, then you should use crypto:strong_rand_bytes/1.
From the documentation at https://erlang.org/doc/man/random.html:
Seeds random number generation ... in the process dictionary and returns the old state.
(emphasis mine)
So, yes, the random module requires each process be seeded individually.
I have been seeing allot of gambling (BTC) websites use the "Provably Fair" system. I am wondering if some of these could possibly be faked.
As an example:
Place a bet on a website for 1 BTC
The website gives you a hash to "verify" the outcome of the result
Displays the result, awards or takes
Now I understand that these are completely random, but with pretty much any programming langauge thousands of these hashes can be generated at once in miliseconds. Is it possible for gambling websites to pretty much try and "scam" a user by generating numbers before a specific rule to decide which one they want to give them based on them winning/losing.
I just started researching if they are trustworthy and this came across my mind.
I apologize if this is one the wrong stack website, if you don't mind directing me to the correct one.
Here are some examples:
http://provablyfair.org/
https://fortunejack.com/help/provably_fair
I understand what you mean and I also think this could be able to do, in fact its pretty simple:
Server send numbers to client, modify the results
Hash are displayed next day
Create 10000 hash, choose the outcomes you need and publicate in that order
Done
And now will come the genius one saying: "You can't modify the seeds". No, but as far as I know u can create as many diferent secrets as you want to archive diferente numbers results.
(Im new at codign but I think it could work by this way)
A result is often calculated using 3 things:
A server seed: Generated by the server. This is hashed so that the player can verify the result are legit and the server didn't change it mid-way but doesn't allow the player to calculate the result themself (cheating)
A client-seed: Generated by the browser. This is used so that the server don't know the result and can't change it.
A nonce, known by both parties. This is often used as a counter for how many bets you have made.
To get the result:
Your browser send the client-seed and the bet info (amount, odds) to the server. Now the server know the result, but can't change it because the client will check the hash later on.
The server send the result and the server seed to your brower.
To verify:
Step 1: Take the server seed and hash it, then compare it with the hash you recive before. If it match, the server play it nice and didn't cheat on you. Continute to Step 2. If it doesn't, you are getting scammed :(
Step 2: Calulate the result yourself.
I'm developing a roguelike in Lua for iOS and OSX. Pretty new to Lua and discovered to my dismay how nonrandom math.random is on my platform. I already had already setup my calls for random numbers set up through a function:
function rollD(max)
return math.random(max)
end
So I found a fantastic answer in response to this post which turns out I think will solve my problem (it's pretty critical for a roguelike that the game be different each time) But in order to make the following tweaked function:
function rollD(max)
return srandom(seedobj,1,max)
end
work, I had to make:
local seedobj = { seed = -232343 }
from Donati's Knuth adaptation not be local anymore, and then actually modified it to use (os.time()*-1). This actually works perfectly so far and my (very rudimentary) roguelike is rolling up random bad guys and dungeons just like I want it to. But I worry when things work right...
With a high number of calls to srandom (probably upwards of a thousand calls per level) am I going to take some kind of performance hit by having seedobj be global? I would like to think that, because it's nested in the table, that seed is a reference and that I'm worrying for nothing. But otherwise: is there a way I should modify this function so I can call it more efficiently?
Accessing a global variable in Lua is like accessing a table field. If seedobj is global the following code:
function rollD(max)
return srandom(seedobj,1,max)
end
in Lua 5.2 is equivalent to:
function rollD(max)
return srandom(_ENV.seedobj,1,max)
end
or in Lua 5.1 is (roughly) equivalent to
function rollD(max)
return srandom(_G.seedobj,1,max)
end
Where _ENV is the variable holding the current environment table and _G is the variable holding the global table.
Therefore whenever you call rollD you incur a small performance penalty for that indirect access, compared to a local variable. In general this penalty is significant or not depending on the complexity of the other operations performed when you call rollD.
In your specific case that penalty is unlikely to be noticeable, since the srandom implementation already performs much more intensive computations (among which some table accesses as well).
My objective is to use feedzirra, or a viable alternative, to access many varying RSS feeds and store them in ActiveRecords for later processing. Obviously, these feeds will vary in composition.
Just running the sample feedzirra code, I've found that its implementation of instance variables is sparse. If the feed doesn't provide the information, the variable is left at nil. This is okay, but as soon as I run a method like sanitize, I receive a NoMethod error on Nil.
Doing some research, I see there is an instance_variables method that would allow me to grab active variables. I could use that but it leaves the problem as to later downstream code that may be checking for instance variables that simply don't exist.
I'm torn on how to handle the situation of sparse instance variables. As I write my code, I need to be able to rely on the input so that I can run processes and methods without (too much) concern as to its reliability or existence.
At this point, I've simply set a rescue NoMethodError trap which is wholly insufficient. I figure that I have to start with some of my own "sanitize" methods to ensure that the input is both safe and reliable. But, when I get nil input, what do I do? I cannot leave it nil as later methods will fail. I could inject some standard string such as " " or "unavailable", either of which could occur in the wild.
This is the first time that I have gathered input that I'd considered wholly unsafe and unreliable. I need recommendations on what I need to do to clean it up before I process it.
At this point, lacking a viable alternative, I have fallen back to checking for nil on the variables as soon as I receive them and setting them to pre-defined values that I can check later needed.
I'm not sure this is the best solution, but getting nil NoMethodError's isn't either...
starting from Rails 4, everything would have to run in threaded environment by default. What this means is all of the code we write AND ALL the gems we use are required to be threadsafe
so, I have few questions on this:
what is NOT thread-safe in ruby/rails? Vs What is thread-safe in ruby/rails?
Is there a list of gems that is known to be threadsafe or vice-versa?
is there List of common patterns of code which are NOT threadsafe example #result ||= some_method?
Are the data structures in ruby lang core such as Hash etc threadsafe?
On MRI, where there a GVL/GIL which means only 1 ruby thread can run at a time except for IO, does the threadsafe change effect us?
None of the core data structures are thread safe. The only one I know of that ships with Ruby is the queue implementation in the standard library (require 'thread'; q = Queue.new).
MRI's GIL does not save us from thread safety issues. It only makes sure that two threads cannot run Ruby code at the same time, i.e. on two different CPUs at the exact same time. Threads can still be paused and resumed at any point in your code. If you write code like #n = 0; 3.times { Thread.start { 100.times { #n += 1 } } } e.g. mutating a shared variable from multiple threads, the value of the shared variable afterwards is not deterministic. The GIL is more or less a simulation of a single core system, it does not change the fundamental issues of writing correct concurrent programs.
Even if MRI had been single-threaded like Node.js you would still have to think about concurrency. The example with the incremented variable would work fine, but you can still get race conditions where things happen in non-deterministic order and one callback clobbers the result of another. Single threaded asynchronous systems are easier to reason about, but they are not free from concurrency issues. Just think of an application with multiple users: if two users hit edit on a Stack Overflow post at more or less the same time, spend some time editing the post and then hit save, whose changes will be seen by a third user later when they read that same post?
In Ruby, as in most other concurrent runtimes, anything that is more than one operation is not thread safe. #n += 1 is not thread safe, because it is multiple operations. #n = 1 is thread safe because it is one operation (it's lots of operations under the hood, and I would probably get into trouble if I tried to describe why it's "thread safe" in detail, but in the end you will not get inconsistent results from assignments). #n ||= 1, is not and no other shorthand operation + assignment is either. One mistake I've made many times is writing return unless #started; #started = true, which is not thread safe at all.
I don't know of any authoritative list of thread safe and non-thread safe statements for Ruby, but there is a simple rule of thumb: if an expression only does one (side-effect free) operation it is probably thread safe. For example: a + b is ok, a = b is also ok, and a.foo(b) is ok, if the method foo is side-effect free (since just about anything in Ruby is a method call, even assignment in many cases, this goes for the other examples too). Side-effects in this context means things that change state. def foo(x); #x = x; end is not side-effect free.
One of the hardest things about writing thread safe code in Ruby is that all core data structures, including array, hash and string, are mutable. It's very easy to accidentally leak a piece of your state, and when that piece is mutable things can get really screwed up. Consider the following code:
class Thing
attr_reader :stuff
def initialize(initial_stuff)
#stuff = initial_stuff
#state_lock = Mutex.new
end
def add(item)
#state_lock.synchronize do
#stuff << item
end
end
end
A instance of this class can be shared between threads and they can safely add things to it, but there's a concurrency bug (it's not the only one): the internal state of the object leaks through the stuff accessor. Besides being problematic from the encapsulation perspective, it also opens up a can of concurrency worms. Maybe someone takes that array and passes it on to somewhere else, and that code in turn thinks it now owns that array and can do whatever it wants with it.
Another classic Ruby example is this:
STANDARD_OPTIONS = {:color => 'red', :count => 10}
def find_stuff
#some_service.load_things('stuff', STANDARD_OPTIONS)
end
find_stuff works fine the first time it's used, but returns something else the second time. Why? The load_things method happens to think it owns the options hash passed to it, and does color = options.delete(:color). Now the STANDARD_OPTIONS constant doesn't have the same value anymore. Constants are only constant in what they reference, they do not guarantee the constancy of the data structures they refer to. Just think what would happen if this code was run concurrently.
If you avoid shared mutable state (e.g. instance variables in objects accessed by multiple threads, data structures like hashes and arrays accessed by multiple threads) thread safety isn't so hard. Try to minimize the parts of your application that are accessed concurrently, and focus your efforts there. IIRC, in a Rails application, a new controller object is created for every request, so it is only going to get used by a single thread, and the same goes for any model objects you create from that controller. However, Rails also encourages the use of global variables (User.find(...) uses the global variable User, you may think of it as only a class, and it is a class, but it is also a namespace for global variables), some of these are safe because they are read only, but sometimes you save things in these global variables because it is convenient. Be very careful when you use anything that is globally accessible.
It's been possible to run Rails in threaded environments for quite a while now, so without being a Rails expert I would still go so far as to say that you don't have to worry about thread safety when it comes to Rails itself. You can still create Rails applications that aren't thread safe by doing some of the things I mention above. When it comes other gems assume that they are not thread safe unless they say that they are, and if they say that they are assume that they are not, and look through their code (but just because you see that they go things like #n ||= 1 does not mean that they are not thread safe, that's a perfectly legitimate thing to do in the right context -- you should instead look for things like mutable state in global variables, how it handles mutable objects passed to its methods, and especially how it handles options hashes).
Finally, being thread unsafe is a transitive property. Anything that uses something that is not thread safe is itself not thread safe.
In addition to Theo's answer, I'd add a couple problem areas to lookout for in Rails specifically, if you're switching to config.threadsafe!
Class variables:
##i_exist_across_threads
ENV:
ENV['DONT_CHANGE_ME']
Threads:
Thread.start
starting from Rails 4, everything would have to run in threaded environment by default
This is not 100% correct. Thread-safe Rails is just on by default. If you deploy on a multi-process app server like Passenger (community) or Unicorn there will be no difference at all. This change only concerns you, if you deploy on a multi-threaded environment like Puma or Passenger Enterprise > 4.0
In the past if you wanted to deploy on a multi-threaded app server you had to turn on config.threadsafe, which is default now, because all it did had either no effects or also applied to a Rails app running in a single process (Prooflink).
But if you do want all the Rails 4 streaming benefits and other real time stuff of the multi-threaded deployment
then maybe you will find this article interesting. As #Theo sad, for a Rails app, you actually just have to omit mutating static state during a request. While this a simple practice to follow, unfortunately you cannot be sure about this for every gem you find. As far as i remember Charles Oliver Nutter from the JRuby project had some tips about it in this podcast.
And if you want to write a pure concurrent Ruby programming, where you would need some data structures which are accessed by more than one thread you maybe will find the thread_safe gem useful.