Example #1
0
    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)
Example #2
0
    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)
Example #3
0
    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 __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)
Example #5
0
    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 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
Example #7
0
    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)
Example #8
0
  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 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 randomInt(n, case=None):
    if case==None:
        r = Random()
    else:    
        r = Random(case)
    i = r.nextInt(n)
    return i
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 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))]
Example #13
0
 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
Example #14
0
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)		
Example #15
0
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)		
Example #16
0
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)
Example #17
0
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
Example #18
0
    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()
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)
Example #20
0
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 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)
Example #22
0
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']))
Example #23
0
 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()
Example #24
0
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'])
Example #25
0
    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)
Example #26
0
    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)
Example #27
0
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
Example #28
0
    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;
Example #29
0
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())))
Example #30
0
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
Example #31
0
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
Example #32
0
    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()
Example #33
0
    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)
Example #34
0
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
class RocketboxFactory(ObjectFactory):
    def __init__(self, template):
        ObjectFactory.__init__(self, template)
        self.name = 'Pedestrian'
        self.displayContext = None
        self.rand = Random()

    def setName(self, name):
        self.name = name

    def getName(self):
        return self.name

    def setDisplayContext(self, dc):
        self.displayContext = dc

    def getDisplayContext(self):
        return self.displayContext

    def makeObject(self, spawnData, instanceOid, loc):
        override = Template()
        override.put(WorldManagerClient.NAMESPACE,
                     WorldManagerClient.TEMPL_LOC, loc)
        override.put(WorldManagerClient.NAMESPACE,
                     WorldManagerClient.TEMPL_NAME, self.getName())
        override.put(WorldManagerClient.NAMESPACE,
                     WorldManagerClient.TEMPL_DISPLAY_CONTEXT,
                     pedDC[self.rand.nextInt(21)])
        obj = ObjectFactory.makeObject(self, spawnData, instanceOid, override)
        obj.addBehavior(BaseBehavior())
        mobPt = []
        mobPt.append(InstanceClient.getMarkerPoint(instanceOid, "MobPt0"))
        mobPt.append(InstanceClient.getMarkerPoint(instanceOid, "MobPt1"))
        mobPt.append(InstanceClient.getMarkerPoint(instanceOid, "MobPt2"))
        mobPt.append(InstanceClient.getMarkerPoint(instanceOid, "MobPt3"))
        mobPt.append(InstanceClient.getMarkerPoint(instanceOid, "MobPt4"))
        mobPt.append(InstanceClient.getMarkerPoint(instanceOid, "MobPt5"))
        mobPt.append(InstanceClient.getMarkerPoint(instanceOid, "MobPt6"))
        mobPt.append(InstanceClient.getMarkerPoint(instanceOid, "MobPt7"))
        mobPt.append(InstanceClient.getMarkerPoint(instanceOid, "MobPt8"))
        behav = AdvancedPatrolBehavior(mobPt)
        behav.setLingerTime(0)
        behav.setMovementSpeed(1500)
        obj.addBehavior(behav)
        return obj
Example #36
0
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
Example #37
0
class Hanoi(FlipTile):
    '''
    Nested squares, which can either sync to the beat or run
    at high speed.
    '''

    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

    def kick(self):
        idx = self.__random.nextInt(4)
        block = self.__blocks[idx]
        state = self.__states[idx]
        frame = self.getFrame()

        if state:
            frame.show(block)
        else:
            frame.hide(block)
               
        self.__states[idx] = not state

    def sync(self, bar, beat):
	if self.__inSync:
            self.kick()

    def count(self, n):
        if not self.__inSync:
            self.kick()
Example #38
0
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 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
Example #40
0
import sys
from java.util import Random

#=========TEST UTILS===========


def randomInt(n, case=None):
    if case == None:
        r = Random()
    else:
        r = Random(case)
    i = r.nextInt(n)
    return i


def randomBoolean(chance, case=None):
    if case == None:
        r = Random()
    else:
        r = Random(case)
    b = r.nextFloat() < chance
    return b


def randomFirstName(case=None):
    if case == None:
        r = Random()
    else:
        r = Random(case)
    firstNames = [
        "Alan", "Betty", "Carlos", "Denise", "Edward", "Felicity", "Graham",
Example #41
0
from java.util import Random
r = Random()
sum = 0
for i in xrange(cnt):
    randomNum = r.nextInt()
    print randomNum
    sum += randomNum
Example #42
0
# -*- coding: cp950 -*-
# 載入java.util套件裡的Random類別
from java.util import Random

# 建立實例
rand = Random()

# 使用for敘述句
for x in range(10):
   # 呼叫Random.nextInt()方法
   print rand.nextInt()

Example #43
0
import math
from java.util import Random
from java.lang import Double

r = Random()

# Series 1 Outputs
#@OUTPUT Double[] series1_xvalues
#@OUTPUT Double[] series1_yvalues
#@OUTPUT Double[] series1_error
#@OUTPUT String series1_fillColor
#@OUTPUT String series1_strokeColor
#@OUTPUT Integer series1_strokeWidth

series1_strokeColor = "rgb(" + str(r.nextInt(255)) + "," + str(
    r.nextInt(255)) + "," + str(r.nextInt(255)) + ")"
series1_fillColor = series1_strokeColor
series1_strokeWidth = 1

series1_xvalues = []
series1_yvalues = []
series1_error = []

currentY = 0
for i in range(29):
    series1_xvalues.append(i)
    series1_yvalues.append(currentY)
    currentY += r.nextGaussian()
    series1_error.append(abs(r.nextGaussian()))
Example #44
0
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
from com.netease.qa.nce.test import SyncAPIClient
from com.netease.qa.nce.test import BasicAPIClient
from java.util import Random
import time

rand = Random()
prefix = rand.nextInt(1000000)

namelistFile=open("namelist", "w")
class TestRunner:
    
    def __init__(self):
        #sleepTime = grinder.threadNumber * 200  # per thread
        #grinder.sleep(sleepTime, 0)   
        self.namelist=[]
        self.basicCli = BasicAPIClient()
        self.syncCli = SyncAPIClient()
        #self.namespace = "perf" + str(grinder.threadNumber + 1)
        
        
    def createRC(self, rcName, namespace):
        success = self.syncCli.createRCWaitRunning(rcName, namespace)
        if(not success):
            grinder.getStatistics().getForCurrentTest().setSuccess(False)
            
    def expandRC(self, rcName, namespace, replicas):
        success = self.syncCli.updateRC(rcName, namespace, replicas)
        if(not success):
            grinder.getStatistics().getForCurrentTest().setSuccess(False)
Example #45
0
def acquireScannerLock(Framework):
    client = Framework.getConnectedClient()
    probe = CollectorsParameters.getValue(CollectorsParameters.KEY_PROBE_MGR_IP)
    if (probe is None) or (len(str(probe)) == 0):
        logger.debug('Probe manager ip is not specified in the DiscoveryProbe.properties file, using probe ID')
        probe = CollectorsParameters.getValue(CollectorsParameters.KEY_COLLECTORS_PROBE_NAME)
        if (probe is None) or (len(str(probe)) == 0):
            errorMessage = 'Failed to identify probe name. Lock was not set.'
            logger.debug(errorMessage)
            Framework.reportError(errorMessage)
            Framework.setStepExecutionStatus(WorkflowStepStatus.FATAL_FAILURE)
            return
    lockTime = System.currentTimeMillis()
    lockExpiration = System.currentTimeMillis() + LOCK_AGE_PERIOD_MILLISECONDS
    jobId =  Framework.getDiscoveryJobId()
    jobType = INVENTORY_JOB_TYPE
    lock = Lock(probe, jobType, jobId, lockTime, lockExpiration)
    lockValue = lock.getLockInfo()
    logger.debug('Trying to lock node with value:', lockValue)

    existingLock = setNewLockIfExistingLockEmpty(client, lockValue)
    if (existingLock is None) or (len(existingLock) == 0):
        # lock was acquired
        return lockValue
    else:
        # found existing lock on remote machine
        remoteLock = extractLock(existingLock)
        logger.debug('Node was already locked:', remoteLock.printLockInfo())
        if not remoteLock.isLockExpired():
            # the lock is more or less fresh
            if lock.isSameLock(remoteLock):
                # this is our own lock, just renew it
                logger.debug('Found lock of same probe/job pair, renewing lock on the node')
                options = HashMap()
                options.put(ScannerNodeLock, lockValue)
                client.setOptionsMap(options)
                return lockValue

            # check whether we need to forcefully remove lock, happens in call home based inventory discovery
            forceAcquire = Framework.getParameter("IsForceLockAcquire")
            if forceAcquire == 'true':
                options = HashMap()
                options.put(ScannerNodeLock, lockValue)
                client.setOptionsMap(options)
                return lockValue

            # if the remote lock was owned by a call home inventory job, we should cancel the current job
            if remoteLock.jobType == CALLHOME_JOB_TYPE:
                logger.debug('Remote node was locked by call home inventory job, will cancel the current ' + jobId)
                return ScannerNodeLockedByCallHome
            logger.debug('Found valid lock is of different job/probe, will try next time')
            return None

        logger.debug('The found lock is already aged, to be removed')
        if not removeLockOption(Framework):
            return None

        # as there can be another probe / job trying to connect to this node, after removing existing lock
        # we don't set our own lock directly (as it can be removed by another probe/job) but go to sleep for some
        # time
        r = Random()
        waitTime = r.nextInt() % 5 + 1
        logger.debug('Going to wait for ' + str(waitTime) + ' seconds before retry to lock')
        event = Event()
        event.wait(waitTime)
        existingLock1 = setNewLockIfExistingLockEmpty(client, lockValue)
        if (existingLock1 is None) or (len(existingLock1) == 0):
            # lock was acquired at last!!!!
            return lockValue

    # there are other lucky guys
    return None
Example #46
0
 def getRating(self):
     #print("Or filepath is: " + self.predSeed)
     random = Random(self.predSeed)
     #random.seed(self.predSeed)
     value = random.nextInt(10)
     return value
Example #47
0
from java.util import Random

rand = Random()

header = ['MONTH', 'SALES', 'OVERHEAD', 'REVENUE', 'PROFIT']
data = []
for month in [
        'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT',
        'NOV', 'DEC'
]:
    data.append([
        month,
        rand.nextInt(1000),
        rand.nextInt(1000),
        rand.nextInt(1000),
        rand.nextInt(1000)
    ])
Example #48
0
class Bee(Movable) :

    def __init__(self) :
        super(Bee,self).__init__()
        self.randomSeed = 0
        self.logic = 1
        self.direction = 1
        self.random = None
        self.jammedCount = 0 # How many clicks I've been stuck because of another bee getting in the way.
        self.pollinated = False
        self.pause = False # Pause while pollinating a flower.

    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 tick( self ) :

        Movable.tick(self)

        if self.pause :
            return

        if not self.isMoving() :
        
            if self.logic == 1 or self.logic == 2 :
                self.moveRound()
            else :
                self.moveRandom()
            
    def changeDirection( self, delta ) :
        self.direction = (self.direction + delta) % 4


    def moveRound( self ) :

        delta = 1 if self.logic == 1 else -1
        if self.tryToMoveForwards() :
            self.changeDirection( -delta )  
            return
        else :
            if self.lookDirection( self.direction, 100 ).hasTag("bee") :
                # If another bee is right in front of us, don't move. This will prevent bees moving
                # disrupting their (anti-)clockwise pattern.
                self.jammedCount += 1
                if self.jammedCount > 60 :
                    self.jammedCount = 0
                    self.logic = 3 - self.logic # Reverse direction Clockwise <-> Anticlockwise
                    self.changeDirection( -delta )
            else :
                self.changeDirection( delta )
           
    
    def moveRandom(self) :
    
        if self.random.nextInt( 20 ) == 0 :
            self.changeDirection(-1)

        elif self.random.nextInt( 20 ) == 0 :
            self.changeDirection(1)

        if not self.tryToMoveForwards() :
            self.changeDirection(self.direction + self.random.nextInt(3) + 1)
            
        self.tryToMoveForwards()
        # We only have two goes at moving forward!

    def tryToMoveForwards( self ) :
    
        forward = self.canMove()

        if forward :
            self.moveDirection( self.direction )
            self.jammedCount = 0
            return True

        return

    def onMessage( self, message ) :
        if message == "enteredHive" :
            self.actor.kill()
        
        elif message == "unpause" :
            self.pause = False
            

    def canMove(self) :
    
        self.event( "face-" + self.getDirectionAbbreviation(self.direction) )
        forward = self.lookDirection( self.direction, 100 )
        if forward.hasTag("enemySoft") :
            return True

        if (not self.pollinated) and forward.hasTag("flower") :
            self.pollinated = True
            self.event( "pollinate", "unpause" )
            self.pause = True
            return True
            
        if self.pollinated and forward.hasTag("beehive") :
            if forward.role.addPollen(1) :
                self.speed = 1 # Slow down to enter the hive.
                self.event( "enterHive", "enteredHive" ) # The bee must die before it hits the hive.
                return True
   
        return forward.hasTag("squash" + self.getDirectionAbbreviation(self.direction))

    # Boiler plate code - no need to change this
    def getProperties(self):
        return properties

    # Boiler plate code - no need to change this
    def getClassName(self):
        return ClassName( Role, self.__module__ + ".py" )
Example #49
0
from java.util import Random

rand = Random()

header = [ 'MONTH', 'SALES', 'OVERHEAD', 'REVENUE', 'PROFIT' ]
data = [ ]
for month in ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']:
  data.append([ month, rand.nextInt(1000), rand.nextInt(1000), rand.nextInt(1000), rand.nextInt(1000) ])
Example #50
0
class Beehive(Faller) :

    def __init__(self) :
        super(Beehive,self).__init__()

        self.bees = 0
        self.requiredPollen = 0
        self.beeLogic = 1
        self.beeDirection = 0
        self.randomSeed = 0
        self.spawnPeriod = 1
        self.needsProdding = False # When True, doesn't emit bees till shoved, or hit.
        
        self.attached = False # When True, the hive doesn't move, otherwise it falls.
        self.emitTimer = None
        self.pollen = 0 # Bees will add pollen if they visit a flower (Pumpkin) and then return here.

    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).

    def makeAMove(self) :
        if not self.attached :
            super(Beehive,self).makeAMove()
            
            
    def shove( self, pusher, dx, dy, speed ) :
        self.prodded()
        super(Beehive,self).shove(pusher, dx, dy, speed )


    def onHit( self, hitter, dx, dy ) :
        self.prodded()


    def prodded(self) :
        self.needsProdding = False
        self.attached = False
        if self.bees == 0 :
            if self.requiredPollen <= self.pollen :
                self.addTag("soft")
        else :
            self.emitTimer = Timer.createTimerSeconds(self.spawnPeriod)
        

    def onHalfInvaded( self, invader ) :
        if self.isMoving() :
            return
            
        if self.bees == 0 :

            if (invader.hasTag("collector")) :
                game.sceneDirector.collected(1)
                invader.talk( "_honey" )
                self.removeFromGrid()
                self.actor.deathEvent("collected")


    def canShove( self, pusher, dx, dy, speed, force) :
    
        if self.requiredPollen > self.pollen and pusher.hasTag("collector" ) :
            pusher.talk( "_collectPollen" )
            
        return Faller.canShove( self, pusher, dx, dy, speed, force )


    def tick(self) :
        super(Beehive,self).tick()

        if self.emitTimer :
            if self.emitTimer.isFinished() :
                if not self.isMoving() :

                    if self.emitBee() :
                        self.bees -= 1
                        if self.bees > 0 :
                            self.emitTimer.reset()
                        else :
                            self.emitTimer = None
                            if self.requiredPollen <= self.pollen :
                                self.addTag("soft")


    def emitBee(self) :
        if self.beeDirection == -1 :
            direction = self.random.nextInt(4)
        else :
            direction = self.beeDirection

        if self.emitBeeDirection(direction) :
            return True
            
        return False


    def emitBeeDirection(self, direction) :

        dx = self.getDeltaX( direction )
        dy  = self.getDeltaY( direction )

        outside = self.look( dx, dy, 100 ) # Look VERY fast
        
        if outside.hasTag("enemySoft") :
            resources = Itchy.getGame().resources
            squareSize = self.square.grid.squareSize
            
            costume = resources.getCostume("bee")
            
            beeActor = resources.createActor( costume, self.actor.stage )
            beeActor.moveTo( self.actor.x + squareSize * dx, self.actor.y + squareSize * dy )
            
            bee = beeActor.role
            bee.placeOnGrid( self.square.grid )
            bee.logic = self.beeLogic
            delta = 1 if self.beeLogic == 2 else -1
            bee.direction = (self.beeDirection + delta) % 4
            bee.random = self.random

            bee.pause = True # Wait for the "unpause" message, from the escape animation
            # Note, the order is important. This event will change the x,y, so must be after placeOnGrid.
            beeActor.event( "escape" + ( self.getDirectionAbbreviation(direction) ), "unpause" )
                        
            return True

        else :
            self.beeDirection = (self.beeDirection + 1) % 4
            
        return False


    def addPollen(self, amount) :
        if self.pollen >= self.requiredPollen :
            return False
            
        self.pollen += amount
        if self.requiredPollen <= self.pollen :
            self.addTag("soft")

        return True


    def createCostumeFeatures(self,costume) :
        return RoundFeatures(costume)


    # Boiler plate code - no need to change this
    def getProperties(self):
        return properties

    # Boiler plate code - no need to change this
    def getClassName(self):
        return ClassName( Role, self.__module__ + ".py" )
Example #51
0
class RocketboxFactory(ObjectFactory):
    def __init__(self, template):
        ObjectFactory.__init__(self, template)
        self.name = 'Pedestrian'
        self.displayContext = None
	self.rand = Random()
    def setName(self, name):
        self.name = name
    def getName(self):
        return self.name
    def setDisplayContext(self, dc):
        self.displayContext = dc
    def getDisplayContext(self):
        return self.displayContext
    def makeObject(self, spawnData, instanceOid, loc):
        override = Template()
        override.put(WorldManagerClient.NAMESPACE, WorldManagerClient.TEMPL_LOC, loc)
        override.put(WorldManagerClient.NAMESPACE, WorldManagerClient.TEMPL_NAME, self.getName())
        override.put(WorldManagerClient.NAMESPACE, WorldManagerClient.TEMPL_DISPLAY_CONTEXT, pedDC[self.rand.nextInt(21)])
        obj = ObjectFactory.makeObject(self, spawnData, instanceOid, override)
        obj.addBehavior(BaseBehavior())
	mobPt = []
	mobPt.append(InstanceClient.getMarkerPoint(instanceOid,"MobPt0"))
	mobPt.append(InstanceClient.getMarkerPoint(instanceOid,"MobPt1"))
	mobPt.append(InstanceClient.getMarkerPoint(instanceOid,"MobPt2"))
	mobPt.append(InstanceClient.getMarkerPoint(instanceOid,"MobPt3"))
	mobPt.append(InstanceClient.getMarkerPoint(instanceOid,"MobPt4"))
	mobPt.append(InstanceClient.getMarkerPoint(instanceOid,"MobPt5"))
	mobPt.append(InstanceClient.getMarkerPoint(instanceOid,"MobPt6"))
	mobPt.append(InstanceClient.getMarkerPoint(instanceOid,"MobPt7"))
	mobPt.append(InstanceClient.getMarkerPoint(instanceOid,"MobPt8"))
        behav = AdvancedPatrolBehavior(mobPt)
        behav.setLingerTime(0)
        behav.setMovementSpeed(1500)
        obj.addBehavior(behav)
        return obj
Example #52
0
class TranslateOffApp:
    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 onCreate(self):
        sentence_lines = iter(sentence_text.splitlines())
        all_sentence_pairs = list(zip(sentence_lines, sentence_lines))
        self.sentence_pairs = []
        while len(self.sentence_pairs) < 10 and all_sentence_pairs:
            # noinspection PyUnresolvedReferences
            i = self.random.nextInt(len(all_sentence_pairs))
            sentence_pair = all_sentence_pairs.pop(i)
            if len(sentence_pair[0]) <= 9:
                self.sentence_pairs.append(sentence_pair)

        self.players = [
            Player(self._activity, is_inverted, self.on_solved)
            for is_inverted in (True, False)
        ]
        self.player_progress = {player: 0 for player in self.players}
        vlayout = LinearLayout(self._activity)
        vlayout.setOrientation(LinearLayout.VERTICAL)

        for i, player in enumerate(self.players):
            if i:
                self.winner_label = TextView(self._activity)
                self.winner_label.setTextSize(50)
                # noinspection PyUnresolvedReferences
                self.winner_label.setLayoutParams(
                    LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT, 1))
                vlayout.addView(self.winner_label)
            player.opponent = self.players[(i + 1) % 2]
            player.on_create(vlayout)
            self.set_sentence(player)

        self._activity.setContentView(vlayout)

    def set_sentence(self, player):
        i = self.player_progress[player]
        text, translation = self.sentence_pairs[i]
        player.set_sentence(
            Sentence(text, translation, randrange=self.random.nextInt))

    def on_solved(self, player):
        i = self.player_progress[player] + 1
        if i < len(self.sentence_pairs):
            self.player_progress[player] = i
            self.set_sentence(player)
        else:
            if self.winner_label.getText():
                return
            if player.is_inverted:
                self.winner_label.setRotation(180)
            else:
                self.winner_label.setRotation(0)
            self.winner_label.setText('You Win!')
            player.opponent.unlimited_hints = True
Example #53
0
import math
from java.util import Random
from java.lang import Double

r = Random()

# Series 1 Outputs
#@OUTPUT Double[] series1_xvalues
#@OUTPUT Double[] series1_yvalues
#@OUTPUT Double[] series1_size
#@OUTPUT String[] series1_label
#@OUTPUT String[] series1_color
#@OUTPUT String series1_markerColor

series1_markerColor = "lightgreen"

series1_xvalues = []
series1_yvalues = []
series1_size = []
series1_color = []
series1_label = []

for i in range(99):
    series1_xvalues.append(Double.valueOf(r.nextGaussian()))
    series1_yvalues.append(Double.valueOf(r.nextGaussian()))
    series1_size.append(
        Double.valueOf(4 / math.sqrt(series1_xvalues[i] * series1_xvalues[i] +
                                     series1_yvalues[i] * series1_yvalues[i])))
    series1_color.append("rgb(" + str(r.nextInt(255)) + "," +
                         str(r.nextInt(255)) + "," + str(r.nextInt(255)) + ")")
    series1_label.append("point " + str(i))
Example #54
0
class Tapestry:
    '''
    A container which gives the appearance of a pannable array of
    tiles. In practice, it only needs to have two at any one time,
    arranged so that we can animate a pan from one to the other.
    We do keep a list of other possible tiles.
    '''

    def __init__(self, name):
        self.__name = name

        # General tools:
        self.__random = Random()

        # Full frame, which can hold two tiles next to each other (X or Y):
        ffr = Frame()

        # Window frame, original matching the monome, within which we move
        # the full frame

        wfr = Frame()

        # Cropped renderable, which is the one we actually render (so that we
        # don't overwrite any adjacent pixels in a bigger design).

        port = ViewPort(wfr, 0, 0, 8, 8)

        # Create a pool of tiles - we can populate __tilePool to hard-wire the
        # first tile if we want to test it explicitly.
        # Cursor() is a special-case, manually loaded for the first few bars.

        self.__fixedTiles = {
            'CURSOR' : Cursor(),
            'BANG' : Bang()
        }

        self.__tilePool = []

        self.__usedPool = [
            Moonbase(),
            Hanoi(False),
            Hanoi(True),
            Eclipse(),
            Spell(),
            Shards(1),
            Shards(3),
            Bars(),
            Border(),
            Flash4(4),
            Flash4(2),
            Cross(),
            Counter(),
            PixelFlip(),
            FourWay()
        ]

        # Set up the first tile:
        t = self.__chooseTile()

        # Set up out state: the stamp for our starting tile.
        ffr.add(t.getMasterFrame(), 0, 0)
        self.__this = TileState(t)
        self.__next00 = None

        # Locate the full frame at (0, 0) within the Monome.
        wfr.add(ffr, 0, 0)

        # We'll need these later:
        self.__fullFrame = ffr
        self.__windFrame = wfr
        self.__viewPort = port

        # Not used (yet), but let's be clean:
        self.__vector = (0, 0)

        self.__nudging = False

    def __chooseTile(self):
        '''
        select a tile (and immediately put it into the used pool);
        if all gone, refresh all from the used pool.
        '''
        if len(self.__tilePool) == 0:
            print self.__name + ": starting new tile pool"
            self.__tilePool = self.__usedPool
            self.__usedPool = []

        idx = self.__random.nextInt(len(self.__tilePool))
        t = self.__tilePool.pop(idx)

        if not t.disposable():
            self.__usedPool.append(t)

        print self.__name + ": tile: " + repr(t.__doc__)

        return t

    def prepare(self, bar, dx, dy, __1=0, __2=0):
        '''
        Prepare to shift from the current tile to the next one.
        Plug the new tile into the full frame at the destination point.
        (This frame will have the current tile at (0, 0).)
        '''
        ffr = self.__fullFrame

        # Invent a direction:
        v = (dx, dy)

        # Pick a random tile from our pool, or hard-wire the ones we need:

        if bar < 5:
            print 'Selecting CURSOR.'
            t = self.__fixedTiles['CURSOR']
        elif bar >= 29:
            print 'Selecting BANG.'
            t = self.__fixedTiles['BANG']
        else:
            t = self.__chooseTile()

        if t is self.__this.tile:
            self.__nudging = False
        else:
            self.__nudging = True
            # Set up our state, ready for the nudge/pan:
            ffr.add(t.getMasterFrame(), v[0] * 8, v[1] * 8)
            self.__next00 = TileState(t)
            self.__vector = v
            t.prepare()

    def nudge(self):
        if self.__nudging:
            'Offset from the current tile to the new one by one pixel.'
            (dx, dy) = self.__vector
            self.__windFrame.moveBy(self.__fullFrame, -dx, -dy)
            return self.__viewPort
        else:
            return None

    def done(self):
        'Finished nudging: tidy up.'
        if self.__nudging and not self.__next00 is None:
            ffr = self.__fullFrame
            wfr = self.__windFrame

            # Remove old tile from fullFrame:
            ffr.remove(self.__this.renderable)

            # Move new tile to (0, 0) within fullFrame:
            ffr.moveTo(self.__next00.renderable, 0, 0)

            #  Move fullFrame to (0, 0) within windFrame:
            wfr.moveTo(self.__fullFrame, 0, 0)

            # Establish new current tile:
            self.__this = self.__next00
            self.__next00 = None

    def sync(self, bar, beat):
        'Synchronise to a bar/beat position'
        self.__this.tile.sync(bar, beat - 1)

        n00 = self.__next00
        if not n00 is None: n00.tile.sync(bar, beat - 1)

        return self.__viewPort

    def clock(self, hundredths):
        'Synchronise to a stopwatch time'
        self.__this.tile.clock(hundredths)

        n00 = self.__next00
        if not n00 is None: n00.tile.clock(hundredths)

        return self.__viewPort