-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbrython_modules.js
2 lines (2 loc) · 44.4 KB
/
brython_modules.js
1
2
__BRYTHON__.use_VFS = true
__BRYTHON__.VFS = {"browser": [".py", "import javascript\n\nfrom _browser import *\n\nfrom . local_storage import LocalStorage\nfrom . session_storage import SessionStorage\nfrom . object_storage import ObjectStorage\n\nWebSocket=window. WebSocket. new", 1], "sys": [".py", "\nfrom _sys import *\n\n_getframe=Getframe\nfrom javascript import JSObject\nfrom browser import window\n\nbrython_debug_mode=__BRYTHON__. debug\n\nbase_exec_prefix=__BRYTHON__. brython_path\n\nbase_prefix=__BRYTHON__. brython_path\n\nbuiltin_module_names=__BRYTHON__. builtin_module_names\n\nbyteorder='little'\n\ndef exc_info():\n exc=__BRYTHON__. current_exception\n if exc is None :\n return (None ,None ,None )\n return (exc. __class__,exc,exc. traceback)\n \nexec_prefix=__BRYTHON__. brython_path\n\nexecutable=__BRYTHON__. brython_path+'/brython.js'\n\nargv=__BRYTHON__. __ARGV\n\ndef exit(i=None ):\n raise SystemExit('')\n \nclass flag_class:\n def __init__(self):\n self. debug=0\n self. inspect=0\n self. interactive=0\n self. optimize=0\n self. dont_write_bytecode=0\n self. no_user_site=0\n self. no_site=0\n self. ignore_environment=0\n self. verbose=0\n self. bytes_warning=0\n self. quiet=0\n self. hash_randomization=1\n \nflags=flag_class()\n\nclass float_info:\n mant_dig=53\n max=window. Number. MAX_VALUE\n min=window. Number. MIN_VALUE\n radix=2\n \ndef getfilesystemencoding(*args,**kw):\n ''\n\n \n return'utf-8'\n \ndef getrecursionlimit():\n return 200\n \nmaxsize=2 **63 -1\n\nmaxunicode=1114111\n\n\n\n\n\n\nplatform=\"brython\"\n\nprefix=__BRYTHON__. brython_path\n\nversion='.'. join(str(x)for x in __BRYTHON__. version_info[:3])\nversion +=\" (default, %s) \\n[Javascript 1.5] on Brython\"%__BRYTHON__. compiled_date\nhexversion=0x03000000\n\nclass _version_info(object):\n def __init__(self,version_info):\n self. version_info=version_info\n self. major=version_info[0]\n self. minor=version_info[1]\n self. micro=version_info[2]\n self. releaselevel=version_info[3]\n self. serial=version_info[4]\n \n def __getitem__(self,index):\n if isinstance(self. version_info[index],list):\n return tuple(self. version_info[index])\n return self. version_info[index]\n \n def hexversion(self):\n try :\n return'0%d0%d0%d'%(self. major,self. minor,self. micro)\n finally :\n return'0%d0000'%(self. major)\n \n def __str__(self):\n _s=\"sys.version(major=%d, minor=%d, micro=%d, releaselevel='%s', serial=%d)\"\n return _s %(self. major,self. minor,self. micro,\n self. releaselevel,self. serial)\n \n \n def __eq__(self,other):\n if isinstance(other,tuple):\n return (self. major,self. minor,self. micro)==other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __ge__(self,other):\n if isinstance(other,tuple):\n return (self. major,self. minor,self. micro)>=other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __gt__(self,other):\n if isinstance(other,tuple):\n return (self. major,self. minor,self. micro)>other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __le__(self,other):\n if isinstance(other,tuple):\n return (self. major,self. minor,self. micro)<=other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __lt__(self,other):\n if isinstance(other,tuple):\n return (self. major,self. minor,self. micro)<other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n def __ne__(self,other):\n if isinstance(other,tuple):\n return (self. major,self. minor,self. micro)!=other\n \n raise Error(\"Error! I don't know how to compare!\")\n \n \n \nversion_info=_version_info(__BRYTHON__. version_info)\n\nclass _implementation:\n def __init__(self):\n self. name='brython'\n self. version=_version_info(__BRYTHON__. implementation)\n self. hexversion=self. version. hexversion()\n self. cache_tag=None\n \n def __repr__(self):\n return\"namespace(name='%s' version=%s hexversion='%s')\"%(self. name,self. version,self. hexversion)\n \n def __str__(self):\n return\"namespace(name='%s' version=%s hexversion='%s')\"%(self. name,self. version,self. hexversion)\n \nimplementation=_implementation()\n\nclass _hash_info:\n def __init__(self):\n self. width=32,\n self. modulus=2147483647\n self. inf=314159\n self. nan=0\n self. imag=1000003\n self. algorithm='siphash24'\n self. hash_bits=64\n self. seed_bits=128\n cutoff=0\n \n def __repr__(self):\n \n return\"sys.hash_info(width=32, modulus=2147483647, inf=314159, nan=0, imag=1000003, algorithm='siphash24', hash_bits=64, seed_bits=128, cutoff=0)\"\n \nhash_info=_hash_info()\n\nclass _float_info:\n ''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n def __init__(self):\n _number=window. Number\n self. dig=15\n self. epsilon=2 **-52\n self. mant_dig=53\n self. max=_number. MAX_VALUE\n self. max_exp=2 **10\n self. max_10_exp=308\n self. min=2 **(-1022)\n self. min_exp=-1021\n self. min_10_exp=-307\n self. radix=2\n self. rounds=1\n self. _tuple=(self. max,self. max_exp,self. max_10_exp,self. min,self. min_exp,self. min_10_exp,self. dig,self. mant_dig,self. epsilon,self. radix,self. rounds)\n \n def __getitem__(self,k):\n return self. _tuple[k]\n \n def __iter__(self):\n return iter(self. _tuple)\n \nfloat_info=_float_info()\n\nwarnoptions=[]\n\ndef getfilesystemencoding():\n return'utf-8'\n \n \n__stdout__=__BRYTHON__. stdout\n__stderr__=__BRYTHON__. stderr\n__stdin__=__BRYTHON__. stdin\n\n\ndel JSObject\ndel _implementation\n"], "browser.timer": [".py", "from browser import window\n\ndef wrap(func):\n\n\n def f(*args,**kw):\n try :\n return func(*args,**kw)\n except Exception as exc:\n msg='{0.info}\\n{0.__name__}: {0.args[0]}'. format(exc)\n import sys\n sys. stderr. write(msg)\n return f\n \nclear_interval=window. clearInterval\n\nclear_timeout=window. clearTimeout\n\ndef set_interval(func,interval):\n return window. setInterval(wrap(func),interval)\n \ndef set_timeout(func,interval):\n return int(window. setTimeout(wrap(func),interval))\n \ndef request_animation_frame(func):\n return int(window. requestAnimationFrame(func))\n \ndef cancel_animation_frame(int_id):\n window. cancelAnimationFrame(int_id)\n \ndef set_loop_timeout(x):\n\n assert isinstance(x,int)\n __BRYTHON__. loop_timeout=x"], "browser.html": [".py", "from _html import *"], "_sys": [".js", "var $module=(function($B){\n var _b_=$B.builtins\n return {\n // Called \"Getframe\" because \"_getframe\" wouldn't be imported in \n // sys.py with \"from _sys import *\"\n Getframe : function(depth){\n return $B._frame($B.frames_stack, depth)\n },\n modules :\n {'__get__':function(){return $B.obj_dict($B.imported)},\n '__set__':function(self, obj, value){ throw _b_.TypeError(\"Read only property 'sys.modules'\") }\n },\n path: \n {'__get__':function(){return $B.path},\n '__set__':function(self, obj, value){ $B.path = value }\n },\n meta_path: \n {'__get__':function(){return $B.meta_path},\n '__set__':function(self, obj, value){ $B.meta_path = value }\n },\n path_hooks: \n {'__get__':function(){return $B.path_hooks},\n '__set__':function(self, obj, value){ $B.path_hooks = value }\n },\n path_importer_cache: \n {'__get__':function(){return _b_.dict($B.JSObject($B.path_importer_cache))},\n '__set__':function(self, obj, value){ throw _b_.TypeError(\"Read only property 'sys.path_importer_cache'\") }\n },\n stderr : {\n __get__:function(){return $B.stderr},\n __set__:function(self, obj, value){$B.stderr = value},\n write:function(data){_b_.getattr($B.stderr,\"write\")(data)}\n },\n stdout : {\n __get__:function(){return $B.stdout},\n __set__:function(self, obj, value){$B.stdout = value},\n write:function(data){_b_.getattr($B.stdout,\"write\")(data)}\n },\n stdin : $B.stdin\n }\n})(__BRYTHON__)\n"], "random": [".js", "// Javascript implementation of the random module\n// Based on Ian Bicking's implementation of the Mersenne twister\n\nvar $module = (function($B){\n\n_b_ = $B.builtins\n\nvar VERSION = 3\n\n// Code copied from https://github.com/ianb/whrandom/blob/master/mersenne.js\n// by Ian Bicking\n\n// this program is a JavaScript version of Mersenne Twister,\n// a straight conversion from the original program, mt19937ar.c,\n// translated by y. okada on july 17, 2006.\n// and modified a little at july 20, 2006, but there are not any substantial differences.\n// modularized by Ian Bicking, March 25, 2013 (found original version at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/JAVASCRIPT/java-script.html)\n// in this program, procedure descriptions and comments of original source code were not removed.\n// lines commented with //c// were originally descriptions of c procedure. and a few following lines are appropriate JavaScript descriptions.\n// lines commented with /* and */ are original comments.\n// lines commented with // are additional comments in this JavaScript version.\n/*\n A C-program for MT19937, with initialization improved 2002/1/26.\n Coded by Takuji Nishimura and Makoto Matsumoto.\n\n Before using, initialize the state by using init_genrand(seed)\n or init_by_array(init_key, key_length).\n\n Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n 3. The names of its contributors may not be used to endorse or promote\n products derived from this software without specific prior written\n permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n Any feedback is very welcome.\n http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html\n email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)\n*/\n\nfunction RandomStream(seed) {\n\n /*jshint bitwise:false */\n /* Period parameters */\n //c//#define N 624\n //c//#define M 397\n //c//#define MATRIX_A 0x9908b0dfUL /* constant vector a */\n //c//#define UPPER_MASK 0x80000000UL /* most significant w-r bits */\n //c//#define LOWER_MASK 0x7fffffffUL /* least significant r bits */\n var N = 624;\n var M = 397;\n var MATRIX_A = 0x9908b0df; /* constant vector a */\n var UPPER_MASK = 0x80000000; /* most significant w-r bits */\n var LOWER_MASK = 0x7fffffff; /* least significant r bits */\n //c//static unsigned long mt[N]; /* the array for the state vector */\n //c//static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */\n var mt = new Array(N); /* the array for the state vector */\n var mti = N+1; /* mti==N+1 means mt[N] is not initialized */\n\n function unsigned32 (n1) // returns a 32-bits unsiged integer from an operand to which applied a bit operator.\n {\n return n1 < 0 ? (n1 ^ UPPER_MASK) + UPPER_MASK : n1;\n }\n\n function subtraction32 (n1, n2) // emulates lowerflow of a c 32-bits unsiged integer variable, instead of the operator -. these both arguments must be non-negative integers expressible using unsigned 32 bits.\n {\n return n1 < n2 ? unsigned32((0x100000000 - (n2 - n1)) & 0xffffffff) : n1 - n2;\n }\n\n function addition32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator +. these both arguments must be non-negative integers expressible using unsigned 32 bits.\n {\n return unsigned32((n1 + n2) & 0xffffffff);\n }\n\n function multiplication32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator *. these both arguments must be non-negative integers expressible using unsigned 32 bits.\n {\n var sum = 0;\n for (var i = 0; i < 32; ++i){\n if ((n1 >>> i) & 0x1){\n sum = addition32(sum, unsigned32(n2 << i));\n }\n }\n return sum;\n }\n\n /* initializes mt[N] with a seed */\n //c//void init_genrand(unsigned long s)\n function init_genrand(s) {\n //c//mt[0]= s & 0xffffffff;\n mt[0]= unsigned32(s & 0xffffffff);\n for (mti=1; mti<N; mti++) {\n mt[mti] =\n //c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);\n addition32(multiplication32(1812433253, unsigned32(mt[mti-1] ^ (mt[mti-1] >>> 30))), mti);\n /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\n /* In the previous versions, MSBs of the seed affect */\n /* only MSBs of the array mt[]. */\n /* 2002/01/09 modified by Makoto Matsumoto */\n //c//mt[mti] &= 0xffffffff;\n mt[mti] = unsigned32(mt[mti] & 0xffffffff);\n /* for >32 bit machines */\n }\n }\n\n /* initialize by an array with array-length */\n /* init_key is the array for initializing keys */\n /* key_length is its length */\n /* slight change for C++, 2004/2/26 */\n //c//void init_by_array(unsigned long init_key[], int key_length)\n function init_by_array(init_key, key_length) {\n //c//int i, j, k;\n var i, j, k;\n init_genrand(19650218);\n i=1; j=0;\n k = (N>key_length ? N : key_length);\n for (; k; k--) {\n //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525))\n //c// + init_key[j] + j; /* non linear */\n mt[i] = addition32(addition32(unsigned32(mt[i] ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1664525)), init_key[j]), j);\n mt[i] =\n //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n unsigned32(mt[i] & 0xffffffff);\n i++; j++;\n if (i>=N) { mt[0] = mt[N-1]; i=1; }\n if (j>=key_length) {\n j=0;\n }\n }\n for (k=N-1; k; k--) {\n //c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941))\n //c//- i; /* non linear */\n mt[i] = subtraction32(unsigned32((mt[i]) ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1566083941)), i);\n //c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */\n mt[i] = unsigned32(mt[i] & 0xffffffff);\n i++;\n if (i>=N) { mt[0] = mt[N-1]; i=1; }\n }\n mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */\n }\n\n /* generates a random number on [0,0xffffffff]-interval */\n //c//unsigned long genrand_int32(void)\n function genrand_int32() {\n //c//unsigned long y;\n //c//static unsigned long mag01[2]={0x0UL, MATRIX_A};\n var y;\n var mag01 = [0x0, MATRIX_A];\n /* mag01[x] = x * MATRIX_A for x=0,1 */\n\n if (mti >= N) { /* generate N words at one time */\n //c//int kk;\n var kk;\n\n if (mti == N+1) { /* if init_genrand() has not been called, */\n init_genrand(Date.now()); /* a default initial seed is used */\n }\n\n for (kk=0;kk<N-M;kk++) {\n //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\n //c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));\n mt[kk] = unsigned32(mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]);\n }\n for (;kk<N-1;kk++) {\n //c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);\n //c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));\n mt[kk] = unsigned32(mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]);\n }\n //c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);\n //c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];\n y = unsigned32((mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK));\n mt[N-1] = unsigned32(mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]);\n mti = 0;\n }\n\n y = mt[mti++];\n\n /* Tempering */\n //c//y ^= (y >> 11);\n //c//y ^= (y << 7) & 0x9d2c5680;\n //c//y ^= (y << 15) & 0xefc60000;\n //c//y ^= (y >> 18);\n y = unsigned32(y ^ (y >>> 11));\n y = unsigned32(y ^ ((y << 7) & 0x9d2c5680));\n y = unsigned32(y ^ ((y << 15) & 0xefc60000));\n y = unsigned32(y ^ (y >>> 18));\n\n return y;\n }\n\n /* generates a random number on [0,0x7fffffff]-interval */\n //c//long genrand_int31(void)\n function genrand_int31() {\n //c//return (genrand_int32()>>1);\n return (genrand_int32()>>>1);\n }\n\n /* generates a random number on [0,1]-real-interval */\n //c//double genrand_real1(void)\n function genrand_real1() {\n return genrand_int32()*(1.0/4294967295.0);\n /* divided by 2^32-1 */\n }\n\n /* generates a random number on [0,1)-real-interval */\n //c//double genrand_real2(void)\n function genrand_real2() {\n return genrand_int32()*(1.0/4294967296.0);\n /* divided by 2^32 */\n }\n\n /* generates a random number on (0,1)-real-interval */\n //c//double genrand_real3(void)\n function genrand_real3() {\n return ((genrand_int32()) + 0.5)*(1.0/4294967296.0);\n /* divided by 2^32 */\n }\n\n /* generates a random number on [0,1) with 53-bit resolution*/\n //c//double genrand_res53(void)\n function genrand_res53() {\n //c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;\n var a=genrand_int32()>>>5, b=genrand_int32()>>>6;\n return (a*67108864.0+b)*(1.0/9007199254740992.0);\n }\n /* These real versions are due to Isaku Wada, 2002/01/09 added */\n\n var random = genrand_res53;\n\n random.seed = function (seed) {\n if (! seed) {\n seed = Date.now();\n }\n if (typeof seed != \"number\") {\n seed = parseInt(seed, 10);\n }\n if ((seed !== 0 && ! seed) || isNaN(seed)) {\n throw \"Bad seed\";\n }\n init_genrand(seed);\n };\n\n random.seed(seed);\n\n random.int31 = genrand_int31;\n random.real1 = genrand_real1;\n random.real2 = genrand_real2;\n random.real3 = genrand_real3;\n random.res53 = genrand_res53;\n \n // Added for compatibility with Python\n random.getstate = function(){return [VERSION, mt, mti]}\n \n random.setstate = function(state){\n mt = state[1]\n mti = state[2]\n }\n\n return random;\n\n}\n\nfunction _Random(){\n var _random = RandomStream()\n \n _b_ = $B.builtins\n \n var NV_MAGICCONST = 4 * Math.exp(-0.5)/Math.sqrt(2),\n gauss_next = null\n \n function _randbelow(x){\n return Math.floor(x*_random())\n }\n \n function _urandom(n){\n /*\n urandom(n) -> str\n Return n random bytes suitable for cryptographic use.\n */\n \n var randbytes= []\n for(i=0;i<n;i++){randbytes.push(parseInt(_random()*256))}\n return _b_.bytes(randbytes)\n }\n \n var res = {\n // magic constants\n NV_MAGICCONST: 1.71552776992141,\n TWOPI: 6.28318530718,\n LOG4: 1.38629436111989,\n SG_MAGICCONST: 2.50407739677627,\n\n choice: function(seq){\n var $ = $B.args('choice', 1,\n {seq:null},['seq'],arguments, {}, null, null),\n seq = $.seq\n var len, rank\n if(Array.isArray(seq)){len = seq.length}\n else{len = _b_.getattr(seq,'__len__')()}\n if(len==0){throw _b_.IndexError(\"Cannot choose from an empty sequence\")}\n rank = parseInt(_random()*len)\n if(Array.isArray(seq)){return seq[rank]}\n else{return _b_.getattr(seq,'__getitem__')(rank)}\n },\n \n expovariate: function(lambd){\n /*\n Exponential distribution.\n \n lambd is 1.0 divided by the desired mean. It should be\n nonzero. (The parameter would be called \"lambda\", but that is\n a reserved word in Python.) Returned values range from 0 to\n positive infinity if lambd is positive, and from negative\n infinity to 0 if lambd is negative.\n \n */\n // lambd: rate lambd = 1/mean\n // ('lambda' is a Python reserved word)\n \n // we use 1-random() instead of random() to preclude the\n // possibility of taking the log of zero.\n return -Math.log(1.0 - _random())/lambd\n },\n \n gammavariate: function(alpha, beta){\n /* Gamma distribution. Not the gamma function!\n \n Conditions on the parameters are alpha > 0 and beta > 0.\n \n The probability distribution function is:\n \n x ** (alpha - 1) * math.exp(-x / beta)\n pdf(x) = --------------------------------------\n math.gamma(alpha) * beta ** alpha\n \n */\n \n // alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2\n \n // Warning: a few older sources define the gamma distribution in terms\n // of alpha > -1.0\n \n var $ = $B.args('gammavariate', 2,\n {alpha:null, beta:null}, ['alpha', 'beta'],\n arguments, {}, null, null),\n alpha = $.alpha,\n beta = $.beta,\n LOG4 = Math.log(4),\n SG_MAGICCONST = 1.0 + Math.log(4.5)\n \n if(alpha <= 0.0 || beta <= 0.0){\n throw _b_.ValueError('gammavariate: alpha and beta must be > 0.0')\n }\n \n if(alpha > 1.0){\n \n // Uses R.C.H. Cheng, \"The generation of Gamma\n // variables with non-integral shape parameters\",\n // Applied Statistics, (1977), 26, No. 1, p71-74\n \n var ainv = Math.sqrt(2.0 * alpha - 1.0),\n bbb = alpha - LOG4,\n ccc = alpha + ainv\n \n while(true){\n var u1 = _random()\n if(!((1e-7 < u1) && (u1 < .9999999))){\n continue\n }\n var u2 = 1.0 - _random(),\n v = Math.log(u1/(1.0-u1))/ainv,\n x = alpha*Math.exp(v),\n z = u1*u1*u2,\n r = bbb+ccc*v-x\n if((r + SG_MAGICCONST - 4.5*z >= 0.0) || r >= Math.log(z)){\n return x * beta\n }\n }\n }else if(alpha == 1.0){\n // expovariate(1)\n var u = _random()\n while(u <= 1e-7){u = _random()}\n return -Math.log(u) * beta\n }else{\n // alpha is between 0 and 1 (exclusive)\n \n // Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle\n \n while(true){\n var u = _random(),\n b = (Math.E + alpha)/Math.E,\n p = b*u,\n x\n if(p <= 1.0){x = Math.pow(p, (1.0/alpha))}\n else{x = -Math.log((b-p)/alpha)}\n var u1 = _random()\n if(p > 1.0){\n if(u1 <= Math.pow(x, alpha - 1.0)){\n break\n }\n }else if(u1 <= Math.exp(-x)){\n break\n }\n }\n return x * beta\n }\n },\n \n gauss:function(){\n \n /* Gaussian distribution.\n \n mu is the mean, and sigma is the standard deviation. This is\n slightly faster than the normalvariate() function.\n \n Not thread-safe without a lock around calls.\n \n # When x and y are two variables from [0, 1), uniformly\n # distributed, then\n #\n # cos(2*pi*x)*sqrt(-2*log(1-y))\n # sin(2*pi*x)*sqrt(-2*log(1-y))\n #\n # are two *independent* variables with normal distribution\n # (mu = 0, sigma = 1).\n # (Lambert Meertens)\n # (corrected version; bug discovered by Mike Miller, fixed by LM)\n \n # Multithreading note: When two threads call this function\n # simultaneously, it is possible that they will receive the\n # same return value. The window is very small though. To\n # avoid this, you have to use a lock around all calls. (I\n # didn't want to slow this down in the serial case by using a\n # lock here.)\n */\n \n var $ = $B.args('gauss', 2, {mu:null, sigma:null},\n ['mu', 'sigma'], arguments, {}, null, null),\n mu = $.mu,\n sigma = $.sigma\n \n var z = gauss_next\n gauss_next = null\n if(z===null){\n var x2pi = _random() * Math.PI * 2,\n g2rad = Math.sqrt(-2.0 * Math.log(1.0 - _random())),\n z = Math.cos(x2pi) * g2rad\n gauss_next = Math.sin(x2pi) * g2rad\n }\n return mu + z*sigma\n },\n \n getrandbits: function(k){\n var $ = $B.args('getrandbits', 1,\n {k:null},['k'],arguments, {}, null, null),\n k = $B.$GetInt($.k)\n // getrandbits(k) -> x. Generates a long int with k random bits.\n if(k <= 0){\n throw _b_.ValueError('number of bits must be greater than zero')\n }\n if(k != _b_.int(k)){\n throw _b_.TypeError('number of bits should be an integer')\n }\n var numbytes = (k + 7), // bits / 8 and rounded up\n x = _b_.int.$dict.from_bytes(_urandom(numbytes), 'big')\n return _b_.getattr(x, '__rshift__')(\n _b_.getattr(numbytes*8,'__sub__')(k))\n },\n \n getstate: function(){\n // Return internal state; can be passed to setstate() later.\n var $ = $B.args('getstate', 0, {}, [], arguments, {}, null, null)\n return _random.getstate()\n },\n \n normalvariate: function(mu, sigma){\n /*\n Normal distribution.\n \n mu is the mean, and sigma is the standard deviation.\n \n */\n \n // mu = mean, sigma = standard deviation\n \n // Uses Kinderman and Monahan method. Reference: Kinderman,\n // A.J. and Monahan, J.F., \"Computer generation of random\n // variables using the ratio of uniform deviates\", ACM Trans\n // Math Software, 3, (1977), pp257-260.\n \n var $=$B.args('normalvariate', 2,\n {mu:null, sigma:null}, ['mu', 'sigma'],\n arguments, {}, null, null),\n mu = $.mu,\n sigma = $.sigma\n \n while(true){\n var u1 = _random(),\n u2 = 1.0 - _random(),\n z = NV_MAGICCONST*(u1-0.5)/u2,\n zz = z*z/4.0\n if(zz <= -Math.log(u2)){break}\n }\n return mu + z*sigma\n },\n \n paretovariate: function(){\n /* Pareto distribution. alpha is the shape parameter.*/\n // Jain, pg. 495\n \n var $ = $B.args('paretovariate', 1, {alpha:null}, ['alpha'],\n arguments, {}, null, null)\n \n var u = 1 - _random()\n return 1 / Math.pow(u,1/$.alpha)\n },\n \n randint: function(a, b){\n var $ = $B.args('randint', 2,\n {a:null, b:null},\n ['a', 'b'],\n arguments, {}, null, null)\n return parseInt(_random()*($.b-$.a+1)+$.a)\n },\n \n random: _random,\n \n randrange: function(){\n var $ = $B.args('randrange', 3,\n {x:null, stop:null, step:null},\n ['x', 'stop', 'step'],\n arguments, {stop:null, step:null}, null, null)\n if($.stop===null){\n var start = 0, stop = $.x, step = 1\n }else{\n var start = $.x, stop = $.stop, \n step = $.step===null ? 1 : $.step\n if(step==0){throw _b_.ValueError('step cannot be 0')}\n }\n if(typeof start=='number' && typeof stop == 'number' &&\n typeof step=='number'){\n return start+step*Math.floor(_random()*Math.floor((stop-start)/step))\n }else{\n var d = _b_.getattr(stop,'__sub__')(start)\n d = _b_.getattr(d, '__floordiv__')(step)\n // Force d to be a LongInt\n d = $B.LongInt(d)\n // d is a long integer with n digits ; to choose a random number\n // between 0 and d the most simple is to take a random digit\n // at each position, except the first one\n var s = d.value, _len = s.length,\n res = Math.floor(_random()*(parseInt(s.charAt(0))+(_len==1 ? 0 : 1)))+''\n var same_start = res.charAt(0)==s.charAt(0)\n for(var i=1;i<_len;i++){\n if(same_start){\n // If it's the last digit, don't allow stop as valid\n if(i==_len-1){\n res += Math.floor(_random()*parseInt(s.charAt(i)))+''\n }else{\n res += Math.floor(_random()*(parseInt(s.charAt(i))+1))+''\n same_start = res.charAt(i)==s.charAt(i)\n }\n }else{\n res += Math.floor(_random()*10)+''\n }\n }\n var offset = {__class__:$B.LongInt.$dict, value: res, \n pos: true}\n d = _b_.getattr(step, '__mul__')(offset)\n d = _b_.getattr(start, '__add__')(d)\n return _b_.int(d)\n }\n },\n \n sample: function(){\n /*\n Chooses k unique random elements from a population sequence or set.\n \n Returns a new list containing elements from the population while\n leaving the original population unchanged. The resulting list is\n in selection order so that all sub-slices will also be valid random\n samples. This allows raffle winners (the sample) to be partitioned\n into grand prize and second place winners (the subslices).\n \n Members of the population need not be hashable or unique. If the\n population contains repeats, then each occurrence is a possible\n selection in the sample.\n \n To choose a sample in a range of integers, use range as an argument.\n This is especially fast and space efficient for sampling from a\n large population: sample(range(10000000), 60)\n \n # Sampling without replacement entails tracking either potential\n # selections (the pool) in a list or previous selections in a set.\n \n # When the number of selections is small compared to the\n # population, then tracking selections is efficient, requiring\n # only a small set and an occasional reselection. For\n # a larger number of selections, the pool tracking method is\n # preferred since the list takes less space than the\n # set and it doesn't suffer from frequent reselections.'\n \n */\n var $ = $B.args('sample',2,{population:null,k:null},\n ['population','k'], arguments,{},null,null),\n population = $.population,\n k = $.k\n \n if(!_b_.hasattr(population, '__len__')){\n throw _b_.TypeError(\"Population must be a sequence or set. For dicts, use list(d).\")\n }\n var n = _b_.getattr(population, '__len__')()\n \n if(k<0 || k>n){\n throw _b_.ValueError(\"Sample larger than population\")\n }\n var result = [],\n setsize = 21 // size of a small set minus size of an empty list\n if(k > 5){\n setsize += Math.pow(4, Math.ceil(Math.log(k * 3, 4))) // table size for big sets\n }\n if(n <= setsize){\n // An n-length list is smaller than a k-length set\n if(Array.isArray(population)){\n var pool = population.slice()\n }else{var pool = _b_.list(population)}\n for(var i=0;i<k;i++){ //invariant: non-selected at [0,n-i)\n var j = _randbelow(n-i)\n result[i] = pool[j]\n pool[j] = pool[n-i-1] // move non-selected item into vacancy\n }\n }else{\n selected = {}\n for(var i=0;i<k;i++){\n var j = _randbelow(n)\n while(selected[j]!==undefined){\n j = _randbelow(n)\n }\n selected[j] = true\n result[i] = Array.isArray(population) ? population[j] :\n _b_.getattr(population, '__getitem__')(j)\n }\n }\n return result\n },\n \n seed: function(){\n /*\n Initialize internal state from hashable object.\n \n None or no argument seeds from current time or from an operating\n system specific randomness source if available.\n \n If *a* is an int, all bits are used.\n */\n var $=$B.args('seed',2,{a:null, version:null},['a', 'version'],\n arguments,{a:new Date(), version:2},null,null),\n a = $.a,\n version = $.version\n \n if(version==1){a = _b_.hash(a)}\n else if(version==2){\n if(_b_.isinstance(a, _b_.str)){\n a = _b_.int.$dict.from_bytes(_b_.bytes(a, 'utf-8'), 'big')\n }else if(_b_.isinstance(a, [_b_.bytes, _b_.bytearray])){\n a = _b_.int.$dict.from_bytes(a, 'big')\n }else if(!_b_.isinstance(a, _b_.int)){\n throw _b_.TypeError('wrong argument')\n }\n if(a.__class__===$B.LongInt.$dict){\n // In this implementation, seed() only accepts safe integers\n // Generate a random one from the underlying string value,\n // using an arbitrary seed (99) to always return the same\n // integer\n var numbers = a.value, res = '', pos\n _random.seed(99)\n for(var i=0;i<17;i++){\n pos = parseInt(_random()*numbers.length)\n res += numbers.charAt(pos)\n }\n a = parseInt(res)\n }\n }else{\n throw ValueError('version can only be 1 or 2')\n }\n \n _random.seed(a)\n gauss_next = null\n },\n \n setstate: function(state){\n // Restore internal state from object returned by getstate().\n var $ = $B.args('setstate', 1, {state:null}, ['state'], \n arguments, {}, null, null)\n var state = _random.getstate()\n if(!Array.isArray($.state)){\n throw _b_.TypeError('state must be a list, not '+\n $B.get_class($.state).__name__)\n }\n if($.state.length<state.length){\n throw _b_.ValueError(\"need more than \"+$.state.length+\n \" values to unpack\")\n }else if($.state.length>state.length){\n throw _b_.ValueError(\"too many values to unpack (expected \"+\n state.length+\")\")\n }\n if($.state[0]!=3){\n throw _b_.ValueError(\"ValueError: state with version \"+\n $.state[0]+\" passed to Random.setstate() of version 3\")\n }\n var second = _b_.list($.state[1])\n if(second.length!==state[1].length){\n throw _b_.ValueError('state vector is the wrong size')\n }\n for(var i=0;i<second.length;i++){\n if(typeof second[i] != 'number'){\n throw _b_.ValueError('state vector items must be integers')\n }\n }\n _random.setstate($.state)\n },\n \n shuffle: function(x, random){\n /*\n x, random=random.random -> shuffle list x in place; return None.\n \n Optional arg random is a 0-argument function returning a random\n float in [0.0, 1.0); by default, the standard random.random.\n */\n \n var $ = $B.args('shuffle',2,{x:null,random:null},\n ['x','random'],\n arguments,{random:null},null,null),\n x = $.x,\n random = $.random\n \n if(random===null){random=_random}\n \n if(Array.isArray(x)){\n for(var i=x.length-1;i>=0;i--){\n var j = Math.floor(random() * (i+1)),\n temp = x[j]\n x[j] = x[i]\n x[i] = temp\n }\n }else{\n var len = _b_.getattr(x, '__len__')(), temp,\n x_get = _b_.getattr(x, '__getitem__'),\n x_set = _b_.getattr(x, '__setitem__')\n \n for(i=len-1;i>=0;i--){\n var j = Math.floor(random() * (i+1)),\n temp = x_get(j)\n x_set(j, x_get(i))\n x_set(i, temp)\n }\n }\n },\n \n triangular: function(){\n /*\n Triangular distribution.\n \n Continuous distribution bounded by given lower and upper limits,\n and having a given mode value in-between.\n \n http://en.wikipedia.org/wiki/Triangular_distribution\n */\n var $=$B.args('triangular',3,\n {low:null, high:null, mode:null},\n ['low', 'high', 'mode'],\n arguments,{low:0, high:1, mode:null}, null, null),\n low = $.low,\n high = $.high,\n mode = $.mode\n \n var u = _random(),\n c = mode===null ? 0.5 : (mode - low) / (high - low)\n if(u > c){\n u = 1 - u\n c = 1 - c\n var temp = low\n low = high\n high = temp\n }\n return low + (high - low) * Math.pow(u * c, 0.5)\n },\n \n uniform: function(){\n var $ = $B.args('uniform',2,{a:null,b:null},['a','b'],\n arguments,{},null,null),\n a = $B.$GetInt($.a),\n b = $B.$GetInt($.b)\n \n return a + (b-a)*_random()\n },\n \n vonmisesvariate: function(mu, kappa){\n /* Circular data distribution.\n \n mu is the mean angle, expressed in radians between 0 and 2*pi, and\n kappa is the concentration parameter, which must be greater than or\n equal to zero. If kappa is equal to zero, this distribution reduces\n to a uniform random angle over the range 0 to 2*pi.\n \n */\n // mu: mean angle (in radians between 0 and 2*pi)\n // kappa: concentration parameter kappa (>= 0)\n // if kappa = 0 generate uniform random angle\n \n // Based upon an algorithm published in: Fisher, N.I.,\n // \"Statistical Analysis of Circular Data\", Cambridge\n // University Press, 1993.\n \n // Thanks to Magnus Kessler for a correction to the\n // implementation of step 4.\n \n var $=$B.args('vonmisesvariate', 2,\n {mu: null, kappa:null}, ['mu', 'kappa'],\n arguments, {}, null, null),\n mu = $.mu,\n kappa = $.kappa,\n TWOPI = 2*Math.PI\n \n if(kappa <= 1e-6){return TWOPI * _random()}\n \n var s = 0.5 / kappa,\n r = s + Math.sqrt(1.0 + s * s)\n \n while(true){\n var u1 = _random(),\n z = Math.cos(Math.PI * u1),\n d = z / (r + z),\n u2 = _random()\n if((u2 < 1.0 - d * d) || \n (u2 <= (1.0 - d) * Math.exp(d))){\n break\n }\n }\n var q = 1.0 / r,\n f = (q + z) / (1.0 + q * z),\n u3 = _random()\n if(u3 > 0.5){var theta = (mu + Math.acos(f)) % TWOPI}\n else{var theta = (mu - Math.acos(f)) % TWOPI}\n return theta\n },\n \n weibullvariate: function(){\n /*Weibull distribution.\n \n alpha is the scale parameter and beta is the shape parameter.\n \n */\n // Jain, pg. 499; bug fix courtesy Bill Arms\n \n var $ = $B.args('weibullvariate', 2, {alpha:null, beta:null},\n ['alpha', 'beta'], arguments, {}, null, null),\n alpha = $.alpha,\n beta = $.beta\n \n var u = 1 - _random()\n return alpha * Math.pow(-Math.log(u), 1/beta)\n },\n \n VERSION: VERSION\n }\n\n res.lognormvariate = function(){\n /*\n Log normal distribution.\n \n If you take the natural logarithm of this distribution, you'll get a\n normal distribution with mean mu and standard deviation sigma.\n mu can have any value, and sigma must be greater than zero.\n \n */\n \n return Math.exp(res.normalvariate.apply(null, arguments))\n }\n \n res.betavariate = function(){\n /* Beta distribution.\n \n Conditions on the parameters are alpha > 0 and beta > 0.\n Returned values range between 0 and 1.\n \n \n # This version due to Janne Sinkkonen, and matches all the std\n # texts (e.g., Knuth Vol 2 Ed 3 pg 134 \"the beta distribution\").\n */\n \n var $ = $B.args('betavariate', 2, {alpha:null, beta:null},\n ['alpha', 'beta'], arguments, {}, null, null),\n alpha = $.alpha,\n beta = $.beta\n \n var y = res.gammavariate(alpha, 1)\n if(y == 0){return _b_.float(0)}\n else{return y / (y + res.gammavariate(beta, 1))}\n }\n \n return res\n\n}\n\nfunction Random(){\n var obj = {__class__: Random.$dict}\n Random.$dict.__init__(obj)\n return obj\n}\nRandom.__class__ = $B.$factory\nRandom.$dict = {\n __class__: $B.$type,\n __name__: 'Random',\n $factory: Random,\n __init__: function(self){self.$r = _Random()},\n __getattribute__: function(self, attr){return self.$r[attr]}\n}\nRandom.$dict.__mro__ = [$B.builtins.object.$dict]\n\nvar $module = _Random()\n\n$module.Random = Random\n\n$module.SystemRandom = function(){\n var f = function(){return {__class__:f.$dict}}\n f.__class__ = $B.$factory\n f.$dict = {\n __class__: $B.$type,\n __name__: 'SystemRandom',\n $factory: f,\n __getattribute__: function(){\n throw $B.builtins.NotImplementedError()\n }\n }\n f.$dict.__mro__ = [$B.builtins.object.$dict]\n return f()\n}\n\nreturn $module\n\n})(__BRYTHON__)\n\n"]}