def barbarianLedge(player, obstacle, obj): if(player.getLocation().getY() != 3547): player.removeAttribute('busy') return random = Random() random= random.nextInt(player.getSkills().getLevel(Skills.AGILITY)) success = True if(random< 20): success = False player.face(Location.create(0, player.getLocation().getY(), 0)) if(success): barbAgilityCourseLvl = player.getAttribute('barbarianAgilityCourse') if(barbAgilityCourseLvl == 2): player.setAttribute('barbarianAgilityCourse', 3) player.playAnimation(Animation.create(753)) Agility.setRunningToggled(player, False, 8) Agility.forceWalkingQueue(player, None, 2532, 3546, 4, 2, False) Agility.forceWalkingQueue(player, Animation.create(756), 2532, 3547, 0, 4, False) Agility.forceTeleport(player, Animation.create(828), Location.create(2532, 3546, 0), 7, 8) player.getSkills().addExperience(Skills.AGILITY, obstacle.getExperience()) else: Agility.setRunningToggled(player, False, 8) Agility.forceTeleport(player, None, Location.create(2534, 3546, 1), 3, 3) Agility.forceWalkingQueue(player, None, 2536, 3547, 6, 3, True) Agility.forceTeleport(player, Animation.create(766), Location.create(2534, 3546, 0), 3, 5) Agility.forceWalkingQueue(player, Animation.create(756), 2534, 3547, 0, 2, False) Agility.damage(player, 5, 6)
def barbarianLogBalance(player, obstacle, obj): if(player.getLocation().getY() != 3546): player.removeAttribute('busy') return random = Random() random= random.nextInt(player.getSkills().getLevel(Skills.AGILITY)) success = True if(random< 20): success = False if(success): barbAgilityCourseLvl = player.getAttribute('barbarianAgilityCourse') if(barbAgilityCourseLvl == 1): player.setAttribute('barbarianAgilityCourse', 2) Agility.setRunningToggled(player, False, 12) Agility.forceWalkingQueue(player, Animation.create(762), 2541, 3546, 0, 11, True) player.getSkills().addExperience(Skills.AGILITY, obstacle.getExperience()) else: player.face(Location.create(0, player.getLocation().getY(),0)) Agility.forceTeleport(player, Animation.create(773), Location.create(2545, 3547, 0), 10, 12) Agility.setRunningToggled(player, False, 16) Agility.forceWalkingQueue(player, Animation.create(772), 2545, 3549, 12, 4, False) Agility.forceWalkingQueue(player, Animation.create(772), 2546, 3550, 13, 3, False) Agility.forceWalkingQueue(player, Animation.create(762), 2545, 3546, 0, 7, False) forceMovementVars = [ 0, 0, 0, 1, 25, 30, 3, 2 ] Agility.forceMovement(player, Animation.create(771), forceMovementVars, 8, False) Agility.forceTeleport(player, None, Location.create(2546, 3550, 0), 16, 16)
def travelling_salesman(): N = 50 random = Random() random.setSeed(0) points = [[0 for x in xrange(2)] for x in xrange(N)] for i in range(0, len(points)): points[i][0] = random.nextDouble() points[i][1] = random.nextDouble() fill = [N] * N ranges = array('i', fill) odd_mimic = DiscreteUniformDistribution(ranges) odd = DiscretePermutationDistribution(N) ef = TravelingSalesmanRouteEvaluationFunction(points) nf = SwapNeighbor() mf = SwapMutation() cf = TravelingSalesmanCrossOver(ef) rhc_generic("TSPrhc50", ef, odd, nf, 1.0, 10000, 10, 5) sa_generic("TSPsa50", ef, odd, nf, 1.0, 10000, 10, 5, ([1E12, 1E6], [0.999, 0.99, 0.95])) ga_generic("TSPga50", ef, odd, mf, cf, 50.0, 10000, 10, 1, ([2000, 200], [0.5, 0.25], [0.25, 0.1, 0.02])) mimic_discrete("TSPmimic50", ef, odd_mimic, ranges, 300.0, 10000, 10, 1, ([200], [100], [0.1, 0.5, 0.9])) print "TSP all done"
def barbarianRopeSwing(player, obstacle, obj): if(!player.getLocation().equals(Location.create(2551, 3554, 0))): player.removeAttribute('busy') return random = Random() random= random.nextInt(player.getSkills().getLevel(Skills.AGILITY)) success = True if(random< 20): success = False Agility.animateObject(obj, Animation.create(54), 0) Agility.animateObject(obj, Animation.create(55), 2) if(success): barbAgilityCourseLvl = player.getAttribute('barbarianAgilityCourse') if(barbAgilityCourseLvl == None): player.setAttribute('barbarianAgilityCourse', 1) forceMovementVars = [ 0, 0, 0, -5, 30, 50, 2, 2 ] Agility.forceMovement(player, Animation.create(751), forceMovementVars, 1, True) player.getSkills().addExperience(Skills.AGILITY, obstacle.getExperience()) else: forceMovementVars = [ 0, 0, 0, -3, 30, 50, 2, 2 ] Agility.forceMovement(player, Animation.create(751), forceMovementVars, 1, True) Agility.forceTeleport(player, Animation.create(766), Location.create(2551, 9951, 0), 3, 6) Agility.forceWalkingQueue(player, None, 2549, 9951, 7, 2, True) Agility.setRunningToggled(player, False, 9) Agility.damage(player, 5, 7)
def cdo(variable,user_cdo_options): """ Does a cdo operation on grid supplied and returns a grid. The function outsources the grid to CDOs (code.zmaw.de/cdo) user option decides what operation can be done. evalues in cdo as cdo user_cdo_options variable_written_to_temp_file.nc output_temp_file.nc """ import java from java.util import Random import sys import commands from visad import VisADException rand = Random() file_prefix=rand.nextInt(9999) file_inp=str(file_prefix)+"_inp.nc" exportGridToNetcdf(variable,file_inp) timeunit=GridUtil.getTimeSet(variable).getSetUnits()[0] if (str(timeunit).split()[0]=="s"): newtimeunit=str(timeunit).replace("s","seconds",1) nco_status=commands.getstatusoutput("ncatted -a units,time,m,c,"+"\""+newtimeunit+"\""+" "+file_inp) if (nco_status[0]): raise VisADException(nco_status[1]) file_out=str(file_prefix)+"_out.nc" cdo_status=commands.getstatusoutput("cdo "+user_cdo_options+" "+file_inp+" "+file_out) if (cdo_status[0]): raise VisADException(cdo_status[1]) dstemp = makeDataSource(file_out) varout=getData(dstemp.getName()) return varout
def lnupq(v0,v1,nt,ni,randomi,moreps): umax = nt-1 p = zerofloat(nt) q = zerofloat(nt) u = zerofloat(nt) si = SincInterpolator.fromErrorAndFrequency(0.01,0.40) print "max length = "+str(si.getMaximumLength()) if (v0==v1): print "v0==v1" minDepth = 0.0 dz = 5.0 for n in range(nt): u[n] = ((v0*n/2.0)-minDepth)/dz dq = (umax-50)/float(ni+1) ts = rampfloat(dq+31,dq,ni) ran = Random(55) #rj=1.0 for ji in range(ni): rj = 1.0 if randomi: rj = 2.0*ran.nextFloat()-1.0 tq = ts[ji]#time u tp = 2.0*(dz*tq+minDepth)/v0#time t(u) #print "tq = "+str(tq) #print "tp = "+str(tp) si.accumulate(tp,rj,nt,1.0,0.0,p) si.accumulate(tq,rj,nt,1.0,0.0,q) itmin = 0 itmax = int(2.0*(dz*ts[ni-1]+minDepth)/v0+0.5) return u,p,q,itmin,itmax
def __call__(self): sheets = 10 random = Random() worksheet = str(40 + random.nextInt(sheets)) base_url = 'http://localhost:8080/home/admin/%s' % worksheet request = newCellTest.wrap(HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id","0"),)) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) a = random.nextInt(2**30) b = random.nextInt(2**30) evalData = ( NVPair("id", new_cell), NVPair("input", "factor(%s%s)"% (a,b)), NVPair("newcell", "0"),) result = request.POST(evalData) count = 0 while (True): request = updateTest.wrap(HTTPRequest(url=base_url + "/cell_update")) getData = ( NVPair("id", new_cell),) result = request.POST(getData) count += 1 if result.text.find('pre') != -1: print 'wait %s test factor %s%s = %s' % (count, a, b, strip_answer(result.text)) break request = deleteCellTest.wrap(HTTPRequest(url=base_url + "/delete_cell")) getData = ( NVPair("id", new_cell),) result = request.POST(getData)
def page1(self): """POST EchoService (request 101).""" r = Random() val = r.nextInt(3)+1 cnt = 0 mesg = '' # dummy data to generate the wanted amount of payload. adder contains 1024 characters = 1KB. adder = 'abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789 abcdefghijklmnop' # change the "while" number to change the size of the message payload, the number represents no of KB, 1 = 1KB, 100= 100KB and so on. while (cnt < 1): mesg = mesg + adder cnt = cnt + 1 result = request101.POST('/Echo', '{"id":"' + str(val) + '" , "message":"' + mesg + '"}', ( NVPair('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/15.0 Firefox/15.0a1'), NVPair('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), NVPair('Accept-Language', 'null'), NVPair('Accept-Encoding', 'gzip, deflate'), NVPair('Content-Type', 'text/plain; charset=UTF-8'), NVPair('Cache-Control', 'no-cache'), )) return result
def __call__(self): sheets = 10 random = Random() worksheet = str(40 + random.nextInt(sheets)) base_url = "http://localhost:8080/home/admin/%s" % worksheet request = newCellTest.wrap(HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id", "0"),)) new_cell = result.text.split()[0].rstrip("___S_A_G_E___") request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) a, b = random.nextInt(10 ** 1), random.nextInt(10 ** 1) evalData = (NVPair("id", new_cell), NVPair("input", "%s * %s" % (a, b)), NVPair("newcell", "0")) result = request.POST(evalData) count = 0 while True: request = updateTest.wrap(HTTPRequest(url=base_url + "/cell_update")) getData = (NVPair("id", new_cell),) result = request.POST(getData) count += 1 if result.text.find("pre") != -1: print "wait", count, "test", a, "*", b, "=", strip_answer(result.text) break request = deleteCellTest.wrap(HTTPRequest(url=base_url + "/delete_cell")) getData = (NVPair("id", new_cell),) result = request.POST(getData)
class PixelFlip(Tile): """A random pattern with single pixel flips.""" def __init__(self): Tile.__init__(self, 1, 1) self.__random = Random() b = Block(8, 8) for i in range(0, 8): for j in range(0, 8): if self.__random.nextBoolean(): b.setLamp(i, j, LampState.ON) else: b.setLamp(i, j, LampState.OFF) self.getFrame().add(b, 0, 0) self.__block = b def count(self, n): i = self.__random.nextInt(8) j = self.__random.nextInt(8) b = self.__block if b.getLamp(i, j) == LampState.ON: b.setLamp(i, j, LampState.OFF) else: b.setLamp(i, j, LampState.ON)
def __call__(self): random = Random() worksheet = random.nextInt(10) base_url = 'http://localhost:8080/home/admin/%s' % worksheet request = newCellTest.wrap( HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id", "0"), )) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) a, b = random.nextInt(10**1), random.nextInt(10**1) evalData = ( NVPair("id", new_cell), NVPair("input", "%s * %s" % (a, b)), NVPair("newcell", "0"), ) result = request.POST(evalData) count = 0 while (True): request = updateTest.wrap( HTTPRequest(url=base_url + "/cell_update")) getData = (NVPair("id", new_cell), ) result = request.POST(getData) count += 1 if result.text.find('pre') != -1: print 'wait', count, 'test', a, '*', b, '=', strip_answer( result.text) break request = deleteCellTest.wrap( HTTPRequest(url=base_url + "/delete_cell")) getData = (NVPair("id", new_cell), ) result = request.POST(getData)
def randomLastName(case=None): if case==None: r = Random() else: r = Random(case) lastNames = ["Anderson", "Baker", "Collins", "Delacruz", "Evans", "Forster", "Gardener", "Hoskins", "Iverson", "Jacoby", "Kelwell", "Lewis", "MacDonald", "Neville", "O'Malley", "Petersen", "Quinn", "Roberts", "Sullivan", "Thomas", "Ulverston", "Vickers", "Watson"] return lastNames[r.nextInt(len(lastNames))]
def randomInt(n, case=None): if case==None: r = Random() else: r = Random(case) i = r.nextInt(n) return i
def __call__(self): sheets = 10 random = Random() worksheet = str(40 + random.nextInt(sheets)) base_url = 'http://localhost:8000/home/admin/%s' % worksheet request = newCellTest.wrap(HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id","0"),)) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) a = random.nextInt(2**30) b = random.nextInt(2**30) evalData = ( NVPair("id", new_cell), NVPair("input", "factor(%s%s)"% (a,b)), NVPair("newcell", "0"),) result = request.POST(evalData) count = 0 while (True): request = updateTest.wrap(HTTPRequest(url=base_url + "/cell_update")) getData = ( NVPair("id", new_cell),) result = request.POST(getData) count += 1 if result.text.find('pre') != -1: print 'wait %s test factor %s%s = %s' % (count, a, b, strip_answer(result.text)) break request = deleteCellTest.wrap(HTTPRequest(url=base_url + "/delete_cell")) getData = ( NVPair("id", new_cell),) result = request.POST(getData)
def randomFirstName(case=None): if case==None: r = Random() else: r = Random(case) firstNames = ["Alan", "Betty", "Carlos", "Denise", "Edward", "Felicity", "Graham", "Harriet", "Ivan", "Judith", "Keith", "Lucy", "Michael", "Nicola", "Owen", "Patsy", "Quentin", "Rosemary", "Stephen", "Tracey", "Ulrich", "Viola", "William"] return firstNames[r.nextInt(len(firstNames))]
def randomBoolean(chance, case=None): if case==None: r = Random() else: r = Random(case) b = r.nextFloat()<chance return b
def __call__(self): random = Random() worksheet = random.nextInt(10) base_url = 'http://localhost:8080/home/admin/%s' % worksheet request = newCellTest.wrap(HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id","0"),)) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) a, b = random.nextInt(10**1), random.nextInt(10**1) evalData = ( NVPair("id", new_cell), NVPair("input", "%s * %s"% (a,b)), NVPair("newcell", "0"),) result = request.POST(evalData) count = 0 while (True): request = updateTest.wrap(HTTPRequest(url=base_url + "/cell_update")) getData = ( NVPair("id", new_cell),) result = request.POST(getData) count += 1 if result.text.find('pre') != -1: print('wait', count, 'test', a, '*', b, '=', strip_answer(result.text)) break request = deleteCellTest.wrap(HTTPRequest(url=base_url + "/delete_cell")) getData = ( NVPair("id", new_cell),) result = request.POST(getData)
def __init__(self): self._activity = android.PythonActivity.setListener(self) self.players = [] self.player_progress = None self.sentence_pairs = None self.winner_label = None self.next_button = None self.random = Random()
def process(self, millis): rng = Random() if rng.nextBoolean(): print "Came up heads" else: print "Came up tails" fundBPath = 'http://www.jisilu.cn/data/sfnew/fundb_list/?___t=' + millis r=requests.get(fundBPath) return r.text
def random_str_java( randomlength=8, chars='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789' ): str = '' length = len(chars) - 1 rng = Random() for i in range(randomlength): str += chars[rng.nextInt(length)] return str
def DistinctColors(nColor): Rnd = Random() cls = [ Color.red, Color.pink, Color.orange, Color.yellow, Color.green, Color.magenta, Color.cyan, Color.blue ] CL = [] for ii in range(0, nColor): idx = Rnd.nextInt(len(cls)) CL.append(cls[idx]) return CL
def test_JavaFunctionSigs(self): from java.util import Random # Check the no args case self.assertEqual('()', getFunctionCallSigs(Random().nextBoolean)) # Check the single call method case self.assertEqual('(<long>)', getFunctionCallSigs(Random().setSeed)) # Check the many ways to call case self.assertEqual('() -OR- (<long>) -OR- (<int>, <int>) -OR- (<long>, <int>, <int>)', getFunctionCallSigs(Random().ints)) # Try a different join method self.assertEqual('()|(<long>)|(<int>, <int>)|(<long>, <int>, <int>)', getFunctionCallSigs(Random().ints, joinClause='|'))
def jumble(self): rand = Random(); for i in range(self.numcells): while True: ri = rand.nextInt(self.numlocs) if ri != i: break tmp = self.cells[i] self.cells[i] = self.cells[ri] self.cells[ri] = tmp;
def onBirth(self) : super(Bee,self).onBirth() self.addTag("bee") self.addTag("enemy") self.addTag("deadly") self.addTag("soft") if self.random is None : if self.randomSeed == 0 : self.random = Random() else : self.random = Random( self.randomSeed )
def addNoise(pixels): r = Random() i = 0 for p in pixels: if p < 0: p = 256 - p rand = p + r.nextInt(256) - 128 if rand > 255: rand = 255 if rand < 0: rand = 0 if rand > 127: rand = rand - 256 # back to -128 to -1 pixels[i] = rand # can't assign 'rand' to 'p', because 'p' is a copy i += 1
def __init__(self): DisposableTile.__init__(self, 10) self.__random = Random() widget = Block('010 111 010') self.getFrame().add(widget, 0, 0) self.__widget = widget # Add the 'blow-up' on top - but hide it. bang = Block(8, 8).fill(LampState.ON) self.getFrame().add(bang, 0, 0).hide(bang) self.__bang = bang
def __call__(self): worksheet = '1' request = protectedResourceTest.wrap( HTTPRequest(url="http://localhost:8000/")) result = request.GET() result = maybeAuthenticate(result) result = request.GET('/home/%s/%s/' % (user, worksheet)) #print 'test sheet seen: ', (result.text.find('test') != -1) #print result.text base_url = 'http://localhost:8000/home/%s/%s' % (user, worksheet) request = newCellTest.wrap( HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id", "0"), )) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') #print 'new cell number', new_cell request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) random = Random() a, b = random.nextInt(10**1), random.nextInt(10**1) # print 'random test',a,b, evalData = ( NVPair("id", new_cell), NVPair("input", "%s * %s" % (a, b)), NVPair("newcell", "0"), ) result = request.POST(evalData) #print 'input', result.text count = 0 while (True): #grinder.sleep(5000) request = updateTest.wrap( HTTPRequest(url=base_url + "/cell_update")) getData = (NVPair("id", new_cell), ) result = request.POST(getData) #print 'full result:', result.text count += 1 if result.text.find('pre') != -1: #print 'full result:', result.text print 'wait', count, 'test', a, '*', b, '=', strip_answer( result.text) break request = deleteCellTest.wrap( HTTPRequest(url=base_url + "/delete_cell")) getData = (NVPair("id", new_cell), ) result = request.POST(getData)
def randomPostCode(case=None): if case==None: r = Random() else: r = Random(case) postCodesA1 = ["E", "W", "N", "S", "SO", "GU", "PO", "NO", "BT"] postCodeA1 = postCodesA1[r.nextInt(len(postCodesA1))] numeric1 = str(1+r.nextInt(25)) numeric2 = str(1+r.nextInt(10)) postCodesA2 = ["AB", "HJ", "GR", "OP", "GA", "NM", "GC", "DS", "AV"] postCodeA2 = postCodesA2[r.nextInt(len(postCodesA2))] return postCodeA1+numeric1+" "+numeric2+postCodeA2
def __call__(self): r = Random() s = self.connection.createStatement() q = t.wrap(s) ip = "%i.%i.%i.%i" % ((r.nextInt() % 256), (r.nextInt() % 256), (r.nextInt() % 256), (r.nextInt() % 256)) # Using BETWEEN #q.execute("select country_code from ip_country_bad where inet_aton('%s') between ip_from and ip_to" % ip ) # Using MBRCONTAINS #q.execute("select country_code from ip_country where mbrcontains(ip_poly, pointfromwkb(point(inet_aton('%s'), 0)))" % ip ) s.close()
def __init__(self, inSync): FlipTile.__init__(self, 5) self.__blocks = [] self.__states = [] self.__random = Random() for border in range(4): size = 8 - border * 2 b = Block(size, size).fill(LampState.FLIP) self.getFrame().add(b, border, border) self.__blocks.append(b) self.__states.append(False) self.__inSync = inSync
class VectorUHash: def __init__(self, seed): self.random = Random(seed) self.seed = seed def __hash(self, b): self.random.setSeed(self.seed) p = 0 sum = 0 while p < len(b): c = 0 d = [0,0,0,0] while p < len(b) and c < 4: d[c] = ord(b[p]) c += 1 p += 1 x1 = (int(d[0]) & 0xff) + ((int(d[1]) & 0xff) << 8) +\ ((int(d[2]) & 0xff) << 16) + ((int(d[3]) & 0xff) << 24) c = 0 e = [0,0,0,0] while p < len(b) and c < 4: e[c] = ord(b[p]) c += 1 p += 1 x2 = (int(e[0]) & 0xff) + ((int(e[1]) & 0xff) << 8) +\ ((int(e[2]) & 0xff) << 16) + ((int(e[3]) & 0xff) << 24) a1 = self.random.nextLong() a2 = self.random.nextLong() a1 |= 1 a2 |= 1 x1 += a1 x2 += a2 if x2 != 0: x1 *= x2 sum += x1 return int(sum & 0x7fffffff) def hashbytes(self, bytes): return self.__hash(bytes)
def check_big_compress_buffer(self, size, compress_func): _1M = 1024 * 1024 if not is_jython: # Generate 10MB worth of random, and expand it by repeating it. # The assumption is that zlib's memory is not big enough to exploit # such spread out redundancy. fmt = "%%0%dx" % (2 * _1M) data = ''.join([binascii.a2b_hex(fmt % random.getrandbits(8 * _1M)) for i in range(10)]) data = data * (size // len(data) + 1) else: # # The original version of this test passes fine on cpython, # but appears to hang on jython, because of the time taken to # format a very large integer as a hexadecimal string. # See this issue for details # http://bugs.jython.org/issue2013 # Since testing string formatting is not the purpose of the test # it is necessary to generate the random test data in a different # way on jython. (There may be a better way than what I have # implemented here) # from java.math import BigInteger from java.util import Random num_bits = 8 * _1M # causes "java.lang.OutOfMemoryError: Java heap space" num_bits = _1M data = ''.join([str(BigInteger((num_bits), Random()).toByteArray()) for i in range(10)]) try: compress_func(data) finally: # Release memory data = None
def __init__(self): self.logfile = TimedFileLogger('/tmp/log.crtrlog') self.environment = CreateRobot() self.environment.fullMode() self.latencyTimer = Chrono() self.clock = Clock("CreateNexting") self.rewards = self.createRewardFunction() self.actions = [CreateAction(-200, +200)] self.behaviourPolicy = RandomPolicy(Random(0), self.actions) self.obsHistory = ObsHistory(10, self.environment.legend()) self.representation = TileCodersNoHashing( self.obsHistory.historyVectorSize(), 0, 4096) self.representation.includeActiveFeature() for name in self.sensorsOfInterest: for timeShift in range(self.HistoryLength): indexes = self.obsHistory.selectIndexes(timeShift, name) self.representation.addTileCoder(indexes, 64, 8) self.demons = DemonScheduler() self.verifiers = [] for rewardFunction in self.rewards: for gamma in [0, 0.5, 0.75, 7 / 8., 15 / 16.]: demon = self.createOnPolicyPredictionDemon( rewardFunction, gamma) verifier = PredictionDemonVerifier(demon) self.verifiers.append(verifier) self.demons.add(demon) self.demonToData[demon] = (verifier, rewardFunction.label() + str(gamma)) self.x_t = None
def minfill(bn, reps=6): cpts = bn.cpts() subdomains = list(cpts) record = EO.minFill(subdomains, reps, Random(0)) order = record.order.toArray() size = record.size return order, size
def doInBackground(self): #----------------------------------------------------------------------- # Use a (pseudo) random number generator to simulate progress #----------------------------------------------------------------------- try: random = Random() progress = 0 self.super__setProgress(progress) # Simulated startup time sleep((random.nextInt(1400) + 100) / 1000.0) while progress < 100: sleep((random.nextInt(1400) + 100) / 1000.0) progress = min(progress + random.nextInt(10) + 1, 100) self.super__setProgress(progress) except KeyboardInterrupt, ki: pass
def randomSequence(): n = 1001 x = zerofloat(n) for i in range(n): rn = Random().nextFloat(); x[i] = rn return x
class Bang(DisposableTile): """ Tile which goes bang on beat 8 of the bar, and doesn't reset. Until then, it has a convincing behaviour as a crosshair. """ def __init__(self): DisposableTile.__init__(self, 10) self.__random = Random() widget = Block("010 111 010") self.getFrame().add(widget, 0, 0) self.__widget = widget # Add the 'blow-up' on top - but hide it. bang = Block(8, 8).fill(LampState.ON) self.getFrame().add(bang, 0, 0).hide(bang) self.__bang = bang def count(self, n): x = self.__random.nextInt(6) y = self.__random.nextInt(6) self.getFrame().moveTo(self.__widget, x, y) def sync(self, bar, beat): if beat == 7: self.getFrame().show(self.__bang)
class Bang(DisposableTile): ''' Tile which goes bang on beat 8 of the bar, and doesn't reset. Until then, it has a convincing behaviour as a crosshair. ''' def __init__(self): DisposableTile.__init__(self, 10) self.__random = Random() widget = Block('010 111 010') self.getFrame().add(widget, 0, 0) self.__widget = widget # Add the 'blow-up' on top - but hide it. bang = Block(8, 8).fill(LampState.ON) self.getFrame().add(bang, 0, 0).hide(bang) self.__bang = bang def count(self, n): x = self.__random.nextInt(6) y = self.__random.nextInt(6) self.getFrame().moveTo(self.__widget, x, y) def sync(self, bar, beat): if beat == 7: self.getFrame().show(self.__bang)
def cdo2(variable1, variable2, user_cdo_options): """ Does a cdo operation on 2 grids supplied and returns a grid. The function outsources the two grids to CDOs (code.zmaw.de/cdo) user option decides what operation can be done. evalues in cdo as cdo user_cdo_options variable1_written_to_temp_file.nc variable2_written.nc output_temp_file.nc """ import java from java.util import Random import sys import commands from visad import VisADException rand = Random() file_prefix = rand.nextInt(9999) file_inp1 = str(file_prefix) + "_inp1.nc" file_inp2 = str(file_prefix) + "_inp2.nc" exportGridToNetcdf(variable1, file_inp1) exportGridToNetcdf(variable2, file_inp2) timeunit1 = GridUtil.getTimeSet(variable1).getSetUnits()[0] timeunit2 = GridUtil.getTimeSet(variable2).getSetUnits()[0] if (str(timeunit1).split()[0] == "s"): newtimeunit1 = str(timeunit1).replace("s", "seconds", 1) nco_status = commands.getstatusoutput("ncatted -a units,time,m,c," + "\"" + newtimeunit1 + "\"" + " " + file_inp1) if (nco_status[0]): raise VisADException(nco_status[1]) if (str(timeunit2).split()[0] == "s"): newtimeunit2 = str(timeunit2).replace("s", "seconds", 1) nco_status = commands.getstatusoutput("ncatted -a units,time,m,c," + "\"" + newtimeunit2 + "\"" + " " + file_inp2) if (nco_status[0]): raise VisADException(nco_status[1]) file_out = str(file_prefix) + "_out.nc" cdo_status = commands.getstatusoutput("cdo " + user_cdo_options + " " + file_inp1 + " " + file_inp2 + " " + file_out) if (cdo_status[0]): raise VisADException(cdo_status[1]) dstemp = makeDataSource(file_out) varout = getData(dstemp.getName()) return varout
def randomImage1(): n1,n2 = 1001,1002 x = zerofloat(n1,n2) for j in range(n2): for i in range(n1): rn = Random().nextFloat(); x[j][i] = rn return x
def onProvideArgs(self, context): if "arg1" in context.provide: context.provided["arg1"] = ProvidedValue().withValue( "v" + str(Random().nextInt(100) + 1)) if "arg2" in context.provide: TimeUnit.SECONDS.sleep(5) context.provided["arg2"] = ProvidedValue().withValue( "First arg is " + context.current["arg1"])
def doInBackground(self): #----------------------------------------------------------------------- # Use a (pseudo) random number generator to simulate progress #----------------------------------------------------------------------- try: random = Random() progress = 0 self.setProgress(progress) while progress < 100: sleep((random.nextInt(1400) + 100) / 1000.0) progress = min(progress + random.nextInt(10) + 1, 100) self.setProgress(progress) except: Type, value = sys.exc_info()[:2] print 'Error:', str(Type) print 'value:', str(value) sys.exit()
def evalss(): wait = 250 random = Random() a, b = (random.nextInt(), random.nextInt()) #input = '%s*%s' % (a, b) input = 'from+sage.all+import+*;factor(ZZ.random_element(10**40))' result = request.GET('/execute?input=%s' % input) id = result.text count = 0 while (True): grinder.sleep(wait) result = request.GET('/get?id=%s' % id) count += 1 if result.text.find('wait') == -1: break ans = eval(result.text) print 'test waited%s ans = %s' % (count, ans['output'])
def evalss(): wait = 250 random = Random() a, b = (random.nextInt(), random.nextInt()) #input = '%s*%s' % (a, b) input = 'from+sage.all+import+*;factor(ZZ.random_element(10**40))' result = request.GET('/execute?input=%s' % input) id = result.text count = 0 while (True): grinder.sleep(wait) result = request.GET('/get?id=%s' % id) count += 1 if result.text.find('wait') == -1: break ans = eval(result.text) print('test waited%s ans = %s' % (count, ans['output']))
def test_java_accessing_items_added_in_python(self): # Test a type that should be coerced into a Java type, a Java # instance that should be wrapped, and a Python instance that # should pass through as itself with str, Random and tuple # respectively. s = set(["value", Random(), ("tuple", "of", "stuff")]) PySetInJavaTest.accessAndRemovePySetItems(s) # Check that the Java removal affected the underlying set self.assertEqual(0, len(s))
def getRandomList(listSize): templist = [] listSize = min(listSize, len(self.skill_data.keys())) while len(templist) < listSize: temp = self.skill_data.keys()[Random().nextInt( len(self.skill_data.keys()))] if temp not in templist: templist += [temp] return templist
def __call__(self): worksheet = '1' request = protectedResourceTest.wrap( HTTPRequest(url="http://localhost:8080/")) result = request.GET() result = maybeAuthenticate(result) result = request.GET('/home/%s/%s/' % (user, worksheet)) base_url = 'http://localhost:8080/home/%s/%s' % (user, worksheet) request = newCellTest.wrap( HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id", "0"), )) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) random = Random() a, b = random.nextInt(10**1), random.nextInt(10**1) evalData = ( NVPair("id", new_cell), NVPair("input", "%s * %s" % (a, b)), NVPair("newcell", "0"), ) result = request.POST(evalData) count = 0 while (True): #grinder.sleep(5000) request = updateTest.wrap( HTTPRequest(url=base_url + "/cell_update")) getData = (NVPair("id", new_cell), ) result = request.POST(getData) count += 1 if result.text.find('pre') != -1: txt = 'wait {} test {} * {} = {}' print(txt.format(count, a, b, strip_answer(result.text))) break request = deleteCellTest.wrap( HTTPRequest(url=base_url + "/delete_cell")) getData = (NVPair("id", new_cell), ) result = request.POST(getData)
def __call__(self): worksheet = '1' request = protectedResourceTest.wrap( HTTPRequest(url="http://localhost:8000/")) result = request.GET() result = maybeAuthenticate(result) result = request.GET('/home/%s/%s/' % (user, worksheet)) #print 'test sheet seen: ', (result.text.find('test') != -1) #print result.text base_url = 'http://localhost:8000/home/%s/%s' % (user, worksheet) request = newCellTest.wrap(HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id","0"),)) new_cell = result.text.split()[0].rstrip('___S_A_G_E___') #print 'new cell number', new_cell request = evaluationTest.wrap(HTTPRequest(url=base_url + "/eval")) random = Random() a, b = random.nextInt(10**1), random.nextInt(10**1) # print 'random test',a,b, evalData = ( NVPair("id", new_cell), NVPair("input", "%s * %s"% (a,b)), NVPair("newcell", "0"),) result = request.POST(evalData) #print 'input', result.text count = 0 while (True): #grinder.sleep(5000) request = updateTest.wrap(HTTPRequest(url=base_url + "/cell_update")) getData = ( NVPair("id", new_cell),) result = request.POST(getData) #print 'full result:', result.text count += 1 if result.text.find('pre') != -1: #print 'full result:', result.text print 'wait',count,'test',a,'*',b,'=', strip_answer(result.text) break request = deleteCellTest.wrap(HTTPRequest(url=base_url + "/delete_cell")) getData = ( NVPair("id", new_cell),) result = request.POST(getData)
def my_spawn(player, mobid, dist, perm): mobt = NpcTable.getInstance().getTemplate(mobid) if not mobt: return spawn = L2Spawn(mobt) spawn.setInstanceId(0) if Config.SAVE_GMSPAWN_ON_CUSTOM: spawn.setCustom(True) spawn.setLocx(player.getX()-dist+Random().nextInt(dist*2)) spawn.setLocy(player.getY()-dist+Random().nextInt(dist*2)) spawn.setLocz(player.getZ()) spawn.setHeading(player.getHeading()) spawn.setAmount(1); spawn.setRespawnDelay(0) if perm: SpawnTable.getInstance().addNewSpawn(spawn, True) spawn.init() else: spawn.stopRespawn() spawn.doSpawn()
def cdoSubGrid(variable, user_nlon, user_nlat): """ Computes a subgrid difference between a fine resolution and coarsened resolution grid (from regriding the original grid to user_nlon and user_nlat) using CDOs.Works best for regular grids. Note: Also needs ncatted from NCO's also to be on your path. """ import java from java.util import Random import sys import commands import os try: os.remove(idv.getObjectStore().getJythonCacheDir() + "/Lib/threading.py") except: pass from visad import VisADException rand = Random() file_prefix = rand.nextInt(9999) file_inp = str(file_prefix) + "_inp.nc" exportGridToNetcdf(variable, file_inp) timeunit = GridUtil.getTimeSet(variable).getSetUnits()[0] if (str(timeunit).split()[0] == "s"): newtimeunit = str(timeunit).replace("s", "seconds", 1) nco_status = commands.getstatusoutput("ncatted -a units,time,m,c," + "\"" + newtimeunit + "\"" + " " + file_inp) if (nco_status[0]): raise VisADException(nco_status[1]) file_out = str(file_prefix) + "_out.nc" cdo_command = "cdo sub " + file_inp + " -remapnn," + file_inp + " -remapcon,r" + user_nlon + "x" + user_nlat + " " + file_inp + " " + file_out cdo_status = commands.getstatusoutput(cdo_command) if (cdo_status[0]): raise VisADException(cdo_status[1]) dstemp = makeDataSource(file_out) varout = getData(dstemp.getName()) return varout
def onBirth(self) : game.sceneDirector.collectablesRemaining += 1 self.addTag("hittable") self.addTag("beehive") # If the seed is zero, then start with a random seed, otherwise be predictable if self.randomSeed == 0 : self.random = Random() else : self.random = Random(self.randomSeed) self.costumeFeatures.update(self) # Its a roundedProperties if not self.needsProdding : self.prodded() super(Beehive,self).onBirth() self.rolls = self.hasTag("roundedSE") self.attached = self.rolls # The round beehive is attached (won't wall until prodded).
class MindlessAutoTiler(AutoTiler): """An edge is chosen at random then from all the tiles that fit that edge (if there are any) one is chosen at random and added to the tiling.""" def __init__(self, prototileSet): AutoTiler.__init__(self, SimplePatch(), prototileSet) self.random = Random() self.fittingTiler = FittingTiler(self.patch, prototileSet) allTiles = prototileSet.getAllTiles() self.patch.add(allTiles.get(self.random.nextInt(allTiles.size()))) def addRandomTile(self, edge): fittingTiles = self.fittingTiler.getFittingTiles(edge); if fittingTiles.isEmpty(): return None return self.patch.add(fittingTiles.get(self.random.nextInt(fittingTiles.size()))) def addTile(self): edges = self.patch.getSides() return self.addRandomTile(edges.get(self.random.nextInt(edges.size())))
def __init__(self): self.environment = CritterbotSimulator() self.latencyTimer = Chrono() self.rewards = self.createRewardFunction() self.actions = XYThetaAction.sevenActions() self.behaviourPolicy = RandomPolicy(Random(0), self.actions) self.representation = TileCodersNoHashing(self.environment.legend().nbLabels(), -2000, 2000) self.representation.includeActiveFeature() self.demons = DemonScheduler() for rewardFunction in self.rewards: self.demons.add(self.createOffPolicyControlDemon(rewardFunction)) self.x_t = None
def __init__(self): DisposableTile.__init__(self, 10) self.__random = Random() widget = Block("010 111 010") self.getFrame().add(widget, 0, 0) self.__widget = widget # Add the 'blow-up' on top - but hide it. bang = Block(8, 8).fill(LampState.ON) self.getFrame().add(bang, 0, 0).hide(bang) self.__bang = bang
def knapsack(): # Random number generator */ random = Random() random.setSeed(0) NUM_ITEMS = 40 # The number of items COPIES_EACH = 4 # The number of copies each MAX_WEIGHT = 50 # The maximum weight for a single element MAX_VOLUME = 50 # The maximum volume for a single element KNAPSACK_VOLUME = MAX_VOLUME * NUM_ITEMS * COPIES_EACH * .4 # The volume of the knapsack # create copies fill = [COPIES_EACH] * NUM_ITEMS copies = array('i', fill) # create weights and volumes fill = [0] * NUM_ITEMS weights = array('d', fill) volumes = array('d', fill) for i in range(0, NUM_ITEMS): weights[i] = random.nextDouble() * MAX_WEIGHT volumes[i] = random.nextDouble() * MAX_VOLUME # create range fill = [COPIES_EACH + 1] * NUM_ITEMS ranges = array('i', fill) ef = KnapsackEvaluationFunction(weights, volumes, KNAPSACK_VOLUME, copies) odd = DiscreteUniformDistribution(ranges) nf = DiscreteChangeOneNeighbor(ranges) mf = DiscreteChangeOneMutation(ranges) cf = UniformCrossOver() rhc_generic("KnSrhc50", ef, odd, nf, 1.0, 10000, 10, 5) sa_generic("KnSsa50", ef, odd, nf, 1.0, 10000, 10, 5, ([1E12, 1E6], [0.999, 0.99, 0.95])) ga_generic("KnSga50", ef, odd, mf, cf, 50.0, 10000, 10, 1, ([2000, 200], [0.5, 0.25], [0.25, 0.1, 0.02])) mimic_discrete("KnSmimic50", ef, odd, ranges, 300.0, 10000, 10, 1, ([200], [100], [0.1, 0.5, 0.9])) print "KnS all done"
def cdoSubGrid(variable,user_nlon,user_nlat): """ Computes a subgrid difference between a fine resolution and coarsened resolution grid (from regriding the original grid to user_nlon and user_nlat) using CDOs.Works best for regular grids. Note: Also needs ncatted from NCO's also to be on your path. """ import java from java.util import Random import sys import commands import os try: os.remove(idv.getObjectStore().getJythonCacheDir()+"/Lib/threading.py") except: pass from visad import VisADException rand = Random() file_prefix=rand.nextInt(9999) file_inp=str(file_prefix)+"_inp.nc" exportGridToNetcdf(variable,file_inp) timeunit=GridUtil.getTimeSet(variable).getSetUnits()[0] if (str(timeunit).split()[0]=="s"): newtimeunit=str(timeunit).replace("s","seconds",1) nco_status=commands.getstatusoutput("ncatted -a units,time,m,c,"+"\""+newtimeunit+"\""+" "+file_inp) if (nco_status[0]): raise VisADException(nco_status[1]) file_out=str(file_prefix)+"_out.nc" cdo_command="cdo sub "+file_inp+" -remapnn,"+file_inp+" -remapcon,r"+user_nlon+"x"+user_nlat+" "+file_inp+" "+file_out cdo_status=commands.getstatusoutput(cdo_command) if (cdo_status[0]): raise VisADException(cdo_status[1]) dstemp = makeDataSource(file_out) varout=getData(dstemp.getName()) return varout
def sqrtupq(r0,r1,v,nt,ni): umax = nt-1 p = zerofloat(nt) q = zerofloat(nt) u = zerofloat(nt) si = SincInterpolator.fromErrorAndFrequency(0.01,0.45) if (r0==r1): for n in range(nt): u[n] = r0*n+v dq = umax/float(ni+1) ts = rampfloat(dq,dq,ni) ran = Random(55) for ji in range(ni): rj = 2.0*ran.nextFloat()-1.0 tq = ts[ji]#time u tp = (tq-v)/r0#time t(u) si.accumulate(tp,rj,nt,1.0,0.0,p) si.accumulate(tq,rj,nt,1.0,0.0,q) itmin = 0 itmax = int((tq-v)/r0+0.5) return u,p,q,itmin,itmax else: a = 2.0*(pow(r1,3.0)-pow(r0,3.0))/(3.0*(umax-v)) b = r0*r0 for n in range(nt): u[n] = (2.0/(3.0*a))*(pow((a*n+b),(3.0/2.0))-pow(b,(3.0/2.0)))+v dq = umax/float(ni+1) ts = rampfloat(dq,dq,ni) si = SincInterpolator.fromErrorAndFrequency(0.01,0.45) ran = Random(55) for ji in range(ni): rj = 2.0*ran.nextFloat()-1.0 tq = ts[ji]#time u tp = (1.0/a)*(pow(3.0*a*(tq-v)/2.0+pow(b,3.0/2.0),(2.0/3.0))-b)#time t(u) si.accumulate(tp,rj,nt,1.0,0.0,p) si.accumulate(tq,rj,nt,1.0,0.0,q) itmin = 0 itmax = int(((1.0/a)*(pow(3.0*a*(umax-v)/2.0+pow(b,3.0/2.0),(2.0/3.0))-b))+0.5) return u,p,q,itmin,itmax
def doInBackground(self): #----------------------------------------------------------------------- # Initialize / clear the textArea #----------------------------------------------------------------------- self.btn.setEnabled(0) # Disable the "start" button #----------------------------------------------------------------------- # Create a (pseudo) random number generator to simulate progress #----------------------------------------------------------------------- try: random = Random() progress = 0 self.PB.setValue(progress) while progress < 100: sleep((random.nextInt(1400) + 100) / 1000.0) progress = min(progress + random.nextInt(10) + 1, 100) self.PB.setValue(progress) except: Type, value = sys.exc_info()[:2] print 'Error:', str(Type) print 'value:', str(value) sys.exit()
def page1(self): """POST EchoService (request 101).""" r = Random() val = r.nextInt(3)+1 cnt = 0 mesg = '' # dummy data to generate the wanted amount of payload. adder contains 1024 characters = 1KB. adder = 'abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnopqrstuvwxyz 123456789abcdefghijklmnop' # change the "while" number to change the size of the message payload, the number represents no of KB, 1 = 1KB, 100= 100KB and so on. while (cnt < 1): mesg = mesg + adder cnt = cnt + 1 result = request101.POST('/EchoService', '<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.webservice.korsdrag.datanizze.se/\"><soapenv:Header/><soapenv:Body><ws:echoMessage><id>' + str(val) + '</id><message>' + mesg + '</message></ws:echoMessage></soapenv:Body></soapenv:Envelope>', ( NVPair('Accept-Encoding', 'gzip,deflate'), NVPair('Content-Type', 'text/xml;charset=UTF-8'), NVPair('User-Agent', 'Apache-HttpClient/4.1.1 (java 1.5)'), )) return result