示例#1
0
def enter_roll_mode():
  global scr
  global mode
  global form
  mode='roll'
  f.change_mode('window')
  f.wipe()
  f.frame('Roll your character')
  f.selector.wipe()
  f.text(20,50,'Choose your race:',fg='green',size=12)
  race_choice=f.selector(['human','orc','dwarf','elf','half-troll'],race_choice_agent)
  race_choice.activate(20,75)
  race_choice.focus(0)
  map=w.load_map()
  c=[rand(0,31),rand(0,31)]
  form['coord']=c
  #f.inform('Your coordinates are: '+str(c))
  while (map[c[0]][c[1]]<40)|(map[c[0]][c[1]]>90): c=[rand(0,31),rand(0,31)]
  f.text(220,50,'Starting location:',fg='blue',size=12)
  f.text(240,80,'('+str(c[0])+','+str(c[1])+')',size=12)
  f.text(50,f.HEIGHT-50,"Press 's' to start...",fg='yellow',size=12)
  if map[c[0]][c[1]]<60:
    f.symbol(230//f.charsize,70//f.charsize+1,'+',color='green')
  else:
    f.symbol(230//f.charsize,70//f.charsize+1,'v',color='brown')
示例#2
0
	def update(self):
		#print "In tempSensor[" + str(self.id) + "].update()" #debug
		#if statement so other sensors can be easily added
		#only including the 22 here because that is all I have to test
		print "Reading Tempature Sensor: " + str(self.id)
		if self.sensorType == "DHT22":
			#read in the sensor
			for ii in range(self.retries):
				humidity, temperature = self.sensorLibrary.read(22, self.pin) ## 22 is what Adafruit_DHT.DHT22 returns in example .\Adafruit_Python_DHT\examples\AdafruitDHT.py
				if humidity is not None and temperature is not None:
					self.lastTemp = temperature
					self.lastHumd = humidity
					self.iteratationsToVal = ii
					print 'Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity)
					break # have the data, now leave
			else:
				self.iteratationsToVal = -9999
				print 'Failed to get reading'
		
		elif self.sensorType == "test": #test case
			from random import randint as rand
			self.lastTemp = rand(0,25)
			self.lastHumd = rand(0,100)
			self.iteratationsToVal = -1
			print "leaving Test"

		else:
			print("Error reading in temp sensor type. This should cause an exception")
def auto_corr(l):
    m = 10000
    c1 = 0.
    c2 = 0.
    cn = 0.
    delta = .3

    samples = np.zeros(m)
    samples[0] = rand()
    for ix in np.arange(m)-1:
        delta_x = delta*(2.*rand()-1)
        next_x = (samples[ix] + delta_x) % 1.
        if check_configuration(samples[ix], next_x, rand()):
            samples[ix+1] = next_x
        else:
            samples[ix+1] = samples[ix]

    for ix in np.arange(m-l):
        c1 += (samples[ix]*samples[ix+l])
    c1 *= (1./(m-l))
    for ix in np.arange(m):
        cn += samples[ix]
        c2 += samples[ix]**2
    cn = ((1./m)*cn)**2
    c2 *= (1./m)

    return (c1-cn)/(c2-cn)
def mc(number_of_samples, n1, n0):

    configs = np.zeros(number_of_samples)
    delta = .3
    configs[0] = rand()

    total_points = 0.

    sum = 0.
    sum_squared = 0.
    for ix in np.arange(len(configs))-1:
        delta_x = delta*(2.*rand()-1)
        next_x = (configs[ix] + delta_x) % 1.
        if check_configuration(configs[ix], next_x, rand()):
            configs[ix+1] = next_x
        else:
            configs[ix+1] = configs[ix]

        if ix >= n1:
            if not (ix-n1) % n0:
                sum += fx(configs[ix])/dist_fn(configs[ix])
                sum_squared += (fx(configs[ix])/dist_fn(configs[ix]))**2.
                total_points += 1.

    return sum, sum_squared, total_points
示例#5
0
def randTurn(field):
    first = True
    x,y = 0, 0
    while field[x][y] != "-" or first:
        first = False
        x, y = rand(0,18), rand(0,18)
    return x, y
示例#6
0
 def new(my, good, extent, f=None):
   if my == good:
     return my
   elif f:
     return good if rand() < extent * f else my
   else:
     return good if rand() < extent else my
 def get(self):
     token = rand(1000000, 9999999)
     template = JINJA_ENVIRONMENT.get_template('index.html')
     self.response.write(template.render({
         "randomNumber": rand(100, 999),
         "token": token
     }))
def writer(out_file):
    """
    param:
        out_file:
            the output filename for the csv


    """
            
    teams = []
    for number in range(1,2):
        for number in range(1,50):
            teams.append([str(number)])
        for number in range(1,50):
            teams.append([str(number)])
    #print teams
    for item in teams:
        #print item, '\n'
        item.append(rand(1,100))
        for number in range(1,11):
            item.append(rand(1,10))
        item.append(random.choice('yn'))

    #print teams

    data = csv.writer(out_file, delimiter=',')

    for item in teams:
        data.writerow(item)
示例#9
0
文件: bee.py 项目: tatarbrot/foraging
 def compute_a(self):
     r_ok = False
     while not r_ok:
         r = rand()
         r_ok = r > 0.1
     a = self.min_dist*rand()**(-1/r*2)
     return a
    def capillary_bundle_xy(self, xbundle, ybundle, sigma):
        """ Generate budle of capillaries """
        nxpol_capillary = (self.nx_capillary - 1)/2

        atemp = self.capillary_diameter * nxpol_capillary

        # Prepare/Clear returned lists
        xci = []
        yci = []
        for ix in range(-2*nxpol_capillary, 2*nxpol_capillary +1):
            for iy in range(-2*nxpol_capillary, 2*nxpol_capillary +1):

                x0 = self.capillary_diameter * ix +\
                    self.capillary_diameter/2.*iy + \
                    0.* sigma * (rand() - 0.5) * \
                    (self.capillary_diameter - self.channel_diameter)

                y0 = np.sqrt(3)/2 * self.capillary_diameter * iy +\
                    0.* sigma * (rand() - 0.5) * \
                    (self.capillary_diameter - self.channel_diameter)

                in_bundle = self.in_hexagon(x0, y0,\
                            self.capillary_diameter * nxpol_capillary)

                if in_bundle:
                    xci.append(xbundle + x0)
                    yci.append(ybundle + y0)

        return xci, yci
示例#11
0
def generate_ratings(num_types, num_users, ratings_per_user=20, num_items=100,
                     alpha=None, noise=-1, plsi=False):
    p = Poisson(ratings_per_user)
    ratings = [[rint(1,5) for i in range(num_items)] for i in range(num_types)]
    if alpha == None:
        alpha = [1]*num_types
    user_ratings = []
    user_indices = []
    type_dists = []
    for i in range(num_users):
        ratings_per_user = p.sample()
        if plsi:
            type_dist = normalize([rand() for t in range(num_types)])
        else:
            type_dist = dirichlet(alpha)
        type_dists.append(type_dist)
        rating = []
        indices = []
        for j in rsample(range(num_items), ratings_per_user):
            if rand() < noise:
                rating.append(rint(1,5))
            else:
                type = sample(type_dist)
                rating.append(ratings[type][j])
            indices.append(j)
        user_ratings.append(rating)
        user_indices.append(indices)
    user_ratings = user_indices, user_ratings
    
    return user_ratings, ratings, type_dists
示例#12
0
	def __init__(self, input_size, output_size, hidden_size=HIDDEN_SIZE, V=None, W=None):
		self.input_size = input_size
		self.output_size = output_size
		self.hidden_size = hidden_size

		self.V = [[rand() for x in xrange(self.hidden_size)] for y in xrange(self.input_size)] if not V else V
		self.W = [[rand() for x in xrange(self.output_size)] for y in xrange(self.hidden_size)] if not W else W
示例#13
0
def mazeDFS(width,height):
	stack   = []
	grid    = [[x%2*y%2 for x in range(width)] for y in range(height)]
	total   = ((width-1)/2)*((height-1)/2)
	cy      = rand(1,height,2)
	cx      = rand(1,width,2)
	visited = 1 

	while visited<total:
		possible= [[y,x] for y,x in
				  [[cy-2,cx],[cy,cx+2],[cy+2,cx],[cy,cx-2]]
				  if y>0 and x>0 and y<height-1 and x<width-1]

		neighbor= [[y,x] for y,x in possible if grid[y-1][x]!=2 and grid[y+1][x]!=2 and grid[y][x-1]!=2 and grid[y][x+1]!=2]

		if len(neighbor)>0:
			ny,nx   = neighbor[rand(0,len(neighbor))]
			wy      = ny if nx!=cx else (ny-1 if ny>cy else cy-1)
			wx      = nx if ny!=cy else (nx-1 if nx>cx else cx-1)

			grid[wy][wx] = 2
			stack.append([cy,cx])
			cy = ny
			cx = nx
			visited+=1
		else:
			cy,cx = stack.pop()

	grid[0][1] = 1
	grid[height-1][width-2] = 1
	return grid
示例#14
0
    def step(self, mutation_rate=1, crossover_rate = 1,
             number_of_individuals=0):
        highest_fitness_this_generation = 0
        fittest_individual_this_generation = None
        if number_of_individuals <= 0:
            number_of_individuals = len(self.population)
        while len(self.population.next_generation) < number_of_individuals:
            if self.sort_population_each_step:
                self.population.sort()
            if 0 < crossover_rate > rand():
                parent, other_parent = self.population.select_for_crossover()
                offspring = parent + other_parent # crossover
            else:
                offspring = self.population.select_for_mutation()
            if 0 < mutation_rate > rand():
                offspring = offspring.mutate()
            self.population.add_to_next_generation(offspring)
            if offspring.fitness > highest_fitness_this_generation:
                fittest_individual_this_generation = offspring
                highest_fitness_this_generation = offspring.fitness

        if highest_fitness_this_generation > self.highest_fitness_found:
            self.highest_fitness_found = fittest_individual_this_generation.fitness
            self.fittest_individual_found = fittest_individual_this_generation
        self.population.switch_to_next_generation()
        return fittest_individual_this_generation
def generate():
	S=""
	L = len(leafs)+int(rand()*10)-5
	L = max(1, L)
	for i in range(L):
		S += " "+randcase(words[int(rand()*len(words))])
	return S[1:]
示例#16
0
文件: map.py 项目: YeOldeDM/blogue
	def draw_map(self):
		for y in range(self.height):
			for x in range(self.width):
				self.sys.own.worldPosition = [x*S,y*S,0]
				if self.map[x][y].block:
					index = self.map[x][y].block_index
					try:
						mesh = self.map[x][y].block+str(index)
						tile = logic.getCurrentScene().addObject(mesh,self.sys.own)
						self.map[x][y].block = tile
					except ValueError:
						raise Exception("**********\nStairs at {} {} are reested! \nCorrect block for index {} not found!\n**********".format(x,y,index))
						logic.endGame()
		
				#draw props
				if self.map[x][y].prop:
					p = self.map[x][y].prop
					self.sys.own.worldPosition = [(x*S)+rand(-1,1),(y*S)+rand(-1,1), 2]
					if p == 'LifePotion':
						self.sys.own.worldPosition.z = 0
					prop = logic.getCurrentScene().addObject(p, self.sys.own)
					ori = prop.worldOrientation.to_euler()
					ori.z = rand(0,628)*0.01
					prop.worldOrientation = ori
					if p == 'Zombie':
						self.monsters.append(prop)
					elif p == 'LifePotion':
						self.items.append(prop)
示例#17
0
文件: api.py 项目: VladJamir/cmsc135
    def __init__(self, dst=NullAddress, src=NullAddress):
        """
        Base class for all packets.

        If src is None, it is filled in with the sending Entity.
        If dst is None, nothing special happens, but when it gets
        to the next hop, the receiver probably won't know what to do with it!

        You can subclass this to add your own packet fields, but they should all
        be either simple primitive types, or plain ol' containers (lists,
        tuples, dicts) containing primitive types or more plain ol' containers
        (containing primitive types or more plain 'ol containers containing...).

        """
        self.src = src
        self.dst = dst
        # Decremented for each entity we go through.
        self.ttl = self.DEFAULT_TTL
        # List of entities we've been sent through.  For debugging.
        self.trace = []

        # When using NetVis, packets are visible, and you can set the color.
        # color is a list of red, green, blue, and (optionally) alpha values.
        # Each value is between 0 and 1.  alpha of 0 is transparent.  1 is
        # opaque.
        self.outer_color = hsv_to_rgb(rand(), rand() * .8 + .2,
                                      rand() * .5 + .5, .75)
        self.inner_color = [0, 0, 0, 0]  # transparent
示例#18
0
def random_on_plane(r, n, co):
    """
    generates a random point on the plane ax + by + cz = d
    """
    n = list(n)
    co = list(co)
    d = dotp(n, co)
    xorz = [1, 0, 0] if (n[0] == 0) else [0, 0, 1]
    w = crossp(n, xorz)

    theta = rand(0, 1) * 2 * M_PI
    k = normalize(n)
    w = add(scale(w, cos(theta)), 
            scale(crossp(k, w), sin(theta)))

    if r == 0:
        w = scale(w, r/norm(w))
    else:
        rand_r = rand(0, 1) * r
        w = scale(w, rand_r/norm(w))

    if d != 0:
        t = scale(n, d / norm2(n))  # vec3
        w = add(w, t)

    return w
示例#19
0
 def update(self):
     users = self.users
     fr = rand(1,5)
     to = rand(1,5)
     return (fr, to,
         users.update(users.c.projid==fr).execute(
         projid=to).rowcount)
示例#20
0
  def update(self):
    if self.dest != self.real_dest: # we're going in a random direction.
      self.pause += 1
      if self.pause >= self.delay:
        self.pause = 0
        self.dest = self.real_dest[:]

    # Randomly decide if we want to go toward our dest, or in a random dir.
    if rand(1, 100) == 1 and not self.at_dest and self.pause == 0:
      # random direction!
      self.dest = [rand(0, self.size[0]), rand(0, 380)]
    elif self.pause == 0:
      self.dest = self.real_dest[:]

    vec = [self.dest[0] - self.rect.centerx, self.dest[1] - self.rect.centery]
    mag = sqrt(vec[0]**2 + vec[1]**2)
    if mag <= 10 and self.pause == 0: # here
      self.real_dest = self.rect.center
      self.at_dest = 1
      return
    elif mag <= 10 and self.pause != 0: # at rand dest
      return

    vec[0] /= mag
    vec[1] /= mag
    self.rect = self.rect.move(self.speed * vec[0], self.speed * vec[1])
示例#21
0
文件: dicebot.py 项目: wlonk/Quinoa
def allflesh(skill):
    die = rand(1, 10)
    more = die
    rol = []
    if die == 10:
        while die == 10:
            nextroll = rand(1, 10)
            rol.append(nextroll)
            additional = max(0, nextroll - 5)
            die = nextroll
            more += additional
    if die == 1:
        while die == 1:
            nextroll = rand(1, 10)
            rol.append(nextroll)
            additional = min(nextroll - 5, 0)
            if additional < 0 and more == die:
                more -= 1
            if nextroll == 1:
                additional -= 1
            die = nextroll
            more += additional
    rollage = skill + more
    if rollage <= 8:
        ret = 0
    elif 9 <= rollage <= 16:
        ret = int(ceiling((rollage - 8) / 2.))
    elif 17 <= rollage <= 20:
        ret = 5
    elif 21 <= rollage:
        ret = int(ceiling((rollage - 20) / 3.)) + 5
    if rol:
        return "%s (Total: %s, role of luck %s)" % \
                (ret, rollage, ', '.join(str(x) for x in rol))
    return "%s (Total: %s)" % (ret, rollage)
示例#22
0
文件: dicebot.py 项目: wlonk/Quinoa
def hande(heaven, earth, passing_grade=1):
    pool = [rand(1, 10) for i in range(heaven)]
    num_rerolls_used = 0
    if earth < 0:
        earth = -earth
    while num_rerolls_used < earth:
        for i, v in enumerate(pool):
            if v < 7:
                pool[i] = rand(1, 10)
                num_rerolls_used += 1
                break
        if not sum(v < 7 for v in pool):
            break
    hits = sum(x >= 7 for x in pool) + pool.count(10)
    if hits == passing_grade:
        ret = "Pass (%s)" % (', '.join(str(x) for x in pool))
    if hits > passing_grade:
        ret = "Pass +%d (%s)" % \
                (hits - passing_grade, ', '.join(str(x) for x in pool))
    if hits < passing_grade:
        ret = "Fail -%d (%s)" % \
                (passing_grade - hits, ', '.join(str(x) for x in pool))
    if num_rerolls_used < abs(earth):
        val = abs(earth) - num_rerolls_used
        ret += " (%d reroll" % val
        if val != 1:
            ret += "s"
        ret += " left)"
    return ret
def randStr(L=10):
	r=""
	for j in range(L):
		if int(rand()*10)<5:
			r+=chr(int(rand()*26)+ord('A'))
		else:
			r+=chr(int(rand()*26)+ord('a'))
	return r
示例#24
0
 def update(self):
     fr = rand(1,5)
     to = rand(1,5)
     i = -1
     for i, user in enumerate(self.users.find({'projid': fr})):
         self.users.update(user,
             {'$set': {'projid': to}})
     return fr, to, i+1
 def update(self):
     fr = rand(1,5)
     to = rand(1,5)
     i = -1
     users = Users.selectBy(projid=fr)
     for i, user in enumerate(users):
         user.projid = to
     return fr, to, i+1
示例#26
0
    def __init__(self, w, h, title='Pyglet App'):
        super(Window, self).__init__(w, h, title)

        # Grayish background
        glClearColor(*self.fLowLight)
             
        # Cull backs of polygons
        glCullFace(GL_BACK);
        glFrontFace(GL_CCW);
        glEnable(GL_CULL_FACE);
        glEnable(GL_DEPTH_TEST);
        
        # Setup light parameters
        glLightModelfv(GL_LIGHT_MODEL_AMBIENT, self.fNoLight);
        glLightfv(GL_LIGHT0, GL_AMBIENT, self.fLowLight);
        glLightfv(GL_LIGHT0, GL_DIFFUSE, self.fBrightLight);
        glLightfv(GL_LIGHT0, GL_SPECULAR, self.fBrightLight);
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);

        # Calculate shadow matrix
        vPoints = [
            [0.0, -0.4, 0.0],
            [10.0, -0.4, 0.0],
            [5.0, -0.4, -5.0],
        ]
        
        # Get the plane equation from three points on the ground
        vPlaneEquation = M3DVector4f()
        m3dGetPlaneEquation(vPlaneEquation, vPoints[0], vPoints[1], vPoints[2]);

        # Calculate projection matrix to draw shadow on the ground
        m3dMakePlanarShadowMatrix(self.mShadowMatrix, vPlaneEquation, self.fLightPos)
        self.mShadowMatrix = gl_vec(GLfloat, self.mShadowMatrix)

        # Mostly use material tracking
        glEnable(GL_COLOR_MATERIAL);
        glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
        glMateriali(GL_FRONT, GL_SHININESS, 128);
            
        # Randomly place the sphere inhabitants
        for iSphere in range(self.NUM_SPHERES):
            # Pick a random location between -20 and 20 at .1 increments
            s = GLFrame()
            x = rand() * 40 - 20
            z = rand() * 40 - 20
            s.SetOrigin(x, 0.0, z)
            self.spheres[iSphere] = s

        glEnable(GL_MULTISAMPLE)  # This is actually on by default

        self._make_display_list('small sphere', self._draw_small_sphere)
        self._make_display_list('big sphere', self._draw_big_sphere)
        self._make_display_list('torus', self._draw_torus)
        self._make_display_list('ground', self._draw_ground)

        pyglet.clock.schedule_interval(self._update, 1.0/60.0)
        pyglet.clock.schedule_interval(self.fps, 2.0)
def spawnEnemies():
    global spawnTimer, spawnrate, score
    if spawnrate<.6:
        spawnrate = .6
    enhealth = score/1000
    enhealth = (enhealth + difficulty) * 10
    if timeit.default_timer()-spawnTimer>0:
        enemies.insert(0,enemy(rand(60, width-60),-50, enemyimgs[rand(0,len(enemyimgs)-1)], enhealth))
        spawnTimer=timeit.default_timer()+spawnrate
示例#28
0
 def Plot(self,color=[]):
     """
     Add polygon to the canvas.
     """
     if not color:
         poly = patches.Polygon(self.pukeVertices(),fc=(rand(),rand(),rand()))
     else: 
         poly = patches.Polygon(self.pukeVertices(),fc='r')
     self.subplot.add_patch(poly)
示例#29
0
def insert(cur, db):
    if db == 'sqlite':
        cur.executemany("INSERT INTO users VALUES(?, ?, ?)",
        [(who, uid, rand(1,5)) for who, uid in randName()])
    elif db == 'gadfly':
        for who, uid in randName():
            cur.execute("INSERT INTO users VALUES(?, ?, ?)",(who, uid, rand(1,5)))
    elif db == 'mysql':
        cur.executemany("INSERT INTO users VALUES(%s, %s, %s)", [(who, uid, rand(1,5)) for who, uid in randName()])
示例#30
0
def test_iand_big():
    temp_vals = list((val, rand(100)) for val in range(100))
    that_vals = list((val, rand(100)) for val in range(100))
    temp = PriorityDict(temp_vals)
    that = PriorityDict(that_vals)
    temp &= that
    assert all(temp[pos] == min(temp_vals[pos][1], that_vals[pos][1])
               for pos in range(100))
    temp._check()
示例#31
0
 def scramble_pos(self, k):
     self.pos = ((rand() - 0.5) * k, (rand() - 0.5) * k, (rand() - 0.5) * k)
示例#32
0
        for i, line in enumerate(f.readlines()):
            if len(line.replace("\n", "")) == 0:
                continue
            d = [float(e) for e in line.replace("\n", "").split(",")]
            data.append({
                "id": i,
                "code": geo_hash(d[0], d[1]),
                "lat": d[0],
                "lng": d[1],
                "value": d[2]
            })

        groups = group(data, rate)

        sampled = [g[int(len(g) * rand())] for g in groups]

        m.fit(sampled)

        transform = [m.type_idx(i) for i in range(len(sampled))]

        with open(output_name, mode='w', encoding='utf8') as f:
            res = []
            for i in range(len(sampled)):
                neighbors = m.neighbors[i]
                res.append({
                    "type": transform[i],
                    "id": sampled[i]["id"],
                    "lng": sampled[i]["lng"],
                    "lat": sampled[i]["lat"],
                    "value": sampled[i]["value"],
示例#33
0
import numpy as np
from random import uniform as rand
from math import sqrt

n = 10
A = np.zeros((n, n))
for i in range(n):
    for j in range(i, n):
        A[i][j] = round(rand(1, 10), 2)
        A[j][i] = A[i][j]
print('Эрмитова матрица: \n', A)

eigen_values, eigen_vectors = np.linalg.eig(A)
for i in range(n):
    eigen_values[i] = round(eigen_values[i], 2)
    for j in range(n):
        eigen_vectors[i][j] = round(eigen_vectors[i][j], 2)
print('Собственные векторы: \n', eigen_vectors)
print('Собственные значения: \n', eigen_values)

eigen_values_1, eigen_vectors_1 = np.linalg.eigh(A)
for i in range(n):
    eigen_values_1[i] = round(eigen_values_1[i], 2)
    for j in range(n):
        eigen_vectors_1[i][j] = round(eigen_vectors_1[i][j], 2)
print('Собственные векторы: \n', eigen_vectors_1)
print('Собственные значения: \n', eigen_values_1)

v = np.zeros(n)
for i in range(n):
    v[i] = round(rand(1, 10), 2)
示例#34
0
●	случайное целое число,
●	случайное вещественное число,
●	случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f',
то вводятся эти символы. Программа должна вывести на экран любой
символ алфавита от 'a' до 'f' включительно.
"""
from random import randint as rand
#Генерация случайного целого числа
print(
    "Для генерации случайного целого числа от вас понадобится ввод значений..."
)
start = int(input("Введите начало границы: "))
end = int(input("Введите конец границы: "))
print("Ваше случайное целое число:", str(rand(start, end)))
#Генерация случайного вещественного числа
print(
    "Для генерации случайного вещественного числа от вас понадобится ввод значений..."
)
start = int(input("Введите начало границы: "))
end = int(input("Введите конец границы: "))
count = int(input("Введите количество цифр после запятой: "))
full = rand(start, end)
after = rand(1, 10000)
all = str(full) + "." + str(after)
all = round(float(all), count)
print("Ваше случайное целое число:", all)
#Генерируем случайный символ
alpha = "abcdefghijklmnopqrstuvwxyz"
print(
示例#35
0
    def __call__(self, instance):
        tokens_a, tokens_b = instance[:2]
        tokens_pos_a = instance[-1]
        tokens_pos_b = [0] * len(tokens_b)
        # print("instance", len(instance))
        try:
            assert len(tokens_a) == len(tokens_pos_a)
        except Exception as e:
            print("instance", len(instance))
            print("tokens_a", len(tokens_a))
            print("tokens_pos_a", len(tokens_pos_a))
            print(instance)

        if self.pos_shift:
            tokens_b = ['[S2S_SOS]'] + tokens_b

        # -3  for special tokens [CLS], [SEP], [SEP]
        num_truncated_a, _ = truncate_tokens_pair(tokens_a, tokens_b, tokens_pos_a, tokens_pos_b, self.max_len - 3, max_len_a=self.max_len_a,
                                                  max_len_b=self.max_len_b, trunc_seg=self.trunc_seg, always_truncate_tail=self.always_truncate_tail)

        # Add Special Tokens
        if self.s2s_special_token:
            tokens = ['[S2S_CLS]'] + tokens_a + \
                ['[S2S_SEP]'] + tokens_b + ['[SEP]']
        else:
            tokens = ['[CLS]'] + tokens_a + ['[SEP]'] + tokens_b + ['[SEP]']
        
        tokens_pos = [0] + tokens_pos_a + [0] + tokens_pos_b + [0]

        if self.new_segment_ids:
            if self.mode == "s2s":
                if self.s2s_add_segment:
                    if self.s2s_share_segment:
                        segment_ids = [0] + [1] * \
                            (len(tokens_a)+1) + [5]*(len(tokens_b)+1)
                    else:
                        segment_ids = [4] + [6] * \
                            (len(tokens_a)+1) + [5]*(len(tokens_b)+1)
                else:
                    segment_ids = [4] * (len(tokens_a)+2) + \
                        [5]*(len(tokens_b)+1)
            else:
                segment_ids = [2] * (len(tokens))
        else:
            segment_ids = [0]*(len(tokens_a)+2) + [1]*(len(tokens_b)+1)

        if self.pos_shift:
            n_pred = min(self.max_pred, len(tokens_b))
            masked_pos = [len(tokens_a)+2+i for i in range(len(tokens_b))]
            masked_weights = [1]*n_pred
            masked_ids = self.indexer(tokens_b[1:]+['[SEP]'])
        else:
            # For masked Language Models
            # the number of prediction is sometimes less than max_pred when sequence is short
            effective_length = len(tokens_b)
            if self.mask_source_words:
                effective_length += len(tokens_a)
            n_pred = min(self.max_pred, max(
                1, int(round(effective_length*self.mask_prob))))
            # candidate positions of masked tokens
            cand_pos = []
            special_pos = set()
            for i, tk in enumerate(tokens):
                # only mask tokens_b (target sequence)
                # we will mask [SEP] as an ending symbol
                if (i >= len(tokens_a)+2) and (tk != '[CLS]'):
                    cand_pos.append(i)
                elif self.mask_source_words and (i < len(tokens_a)+2) and (tk != '[CLS]') and (not tk.startswith('[SEP')):
                    cand_pos.append(i)
                else:
                    special_pos.add(i)
            shuffle(cand_pos)

            masked_pos = set()
            max_cand_pos = max(cand_pos)
            for pos in cand_pos:
                if len(masked_pos) >= n_pred:
                    break
                if pos in masked_pos:
                    continue

                def _expand_whole_word(st, end):
                    new_st, new_end = st, end
                    while (new_st >= 0) and tokens[new_st].startswith('##'):
                        new_st -= 1
                    while (new_end < len(tokens)) and tokens[new_end].startswith('##'):
                        new_end += 1
                    return new_st, new_end

                if (self.skipgram_prb > 0) and (self.skipgram_size >= 2) and (rand() < self.skipgram_prb):
                    # ngram
                    cur_skipgram_size = randint(2, self.skipgram_size)
                    if self.mask_whole_word:
                        st_pos, end_pos = _expand_whole_word(
                            pos, pos + cur_skipgram_size)
                    else:
                        st_pos, end_pos = pos, pos + cur_skipgram_size
                else:
                    # directly mask
                    if self.mask_whole_word:
                        st_pos, end_pos = _expand_whole_word(pos, pos + 1)
                    else:
                        st_pos, end_pos = pos, pos + 1

                for mp in range(st_pos, end_pos):
                    if (0 < mp <= max_cand_pos) and (mp not in special_pos):
                        masked_pos.add(mp)
                    else:
                        break

            masked_pos = list(masked_pos)
            if len(masked_pos) > n_pred:
                shuffle(masked_pos)
                masked_pos = masked_pos[:n_pred]

            masked_tokens = [tokens[pos] for pos in masked_pos]
            for pos in masked_pos:
                if rand() < 0.8:  # 80%
                    tokens[pos] = '[MASK]'
                elif rand() < 0.5:  # 10%
                    tokens[pos] = get_random_word(self.vocab_words)
            # when n_pred < max_pred, we only calculate loss within n_pred
            masked_weights = [1]*len(masked_tokens)

            # Token Indexing
            masked_ids = self.indexer(masked_tokens)
        # Token Indexing
        input_ids = self.indexer(tokens)

        # Zero Padding
        n_pad = self.max_len - len(input_ids)
        input_ids.extend([0]*n_pad)
        segment_ids.extend([0] * n_pad)
        tokens_pos.extend([0] * n_pad)

        if self.num_qkv > 1:
            mask_qkv = [0]*(len(tokens_a)+2) + [1] * (len(tokens_b)+1)
            mask_qkv.extend([0]*n_pad)
        else:
            mask_qkv = None

        input_mask = torch.zeros(self.max_len, self.max_len, dtype=torch.long)
        if self.mode == "s2s":
            input_mask[:, :len(tokens_a)+2].fill_(1)
            second_st, second_end = len(
                tokens_a)+2, len(tokens_a)+len(tokens_b)+3
            input_mask[second_st:second_end, second_st:second_end].copy_(
                self._tril_matrix[:second_end-second_st, :second_end-second_st])
        else:
            st, end = 0, len(tokens_a) + len(tokens_b) + 3
            input_mask[st:end, st:end].copy_(self._tril_matrix[:end, :end])

        # Zero Padding for masked target
        if self.max_pred > n_pred:
            n_pad = self.max_pred - n_pred
            if masked_ids is not None:
                masked_ids.extend([0]*n_pad)
            if masked_pos is not None:
                masked_pos.extend([0]*n_pad)
            if masked_weights is not None:
                masked_weights.extend([0]*n_pad)

        oracle_pos = None
        oracle_weights = None
        oracle_labels = None
        if self.has_oracle:
            s_st, labls = instance[2:]
            oracle_pos = []
            oracle_labels = []
            for st, lb in zip(s_st, labls):
                st = st - num_truncated_a[0]
                if st > 0 and st < len(tokens_a):
                    oracle_pos.append(st)
                    oracle_labels.append(lb)
            oracle_pos = oracle_pos[:20]
            oracle_labels = oracle_labels[:20]
            oracle_weights = [1] * len(oracle_pos)
            if len(oracle_pos) < 20:
                x_pad = 20 - len(oracle_pos)
                oracle_pos.extend([0] * x_pad)
                oracle_labels.extend([0] * x_pad)
                oracle_weights.extend([0] * x_pad)

            return (input_ids, segment_ids, input_mask, mask_qkv, masked_ids,
                    masked_pos, masked_weights, -1, self.task_idx,
                    oracle_pos, oracle_weights, oracle_labels)
        
        try:
            assert len(input_ids) == len(tokens_pos)
        except Exception as e:
            print("input_ids", len(input_ids))
            print("tokens_pos", len(tokens_pos))

        return (input_ids, segment_ids, input_mask, mask_qkv, masked_ids, masked_pos, masked_weights, -1, self.task_idx, tokens_pos)
示例#36
0
def draw_circle(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img, (x, y), rand(50, 120),
                   (rand(0, 255), rand(0, 255), rand(0, 255)), -1)
示例#37
0
Hs = 4.5  #m

#define frequency domain
wo = 0.01  #rd/s - starting range of angular frequency
wf = 3.5  #rd/s - ending range of angular frequency
dw = 0.001  #rd/s - angular frequency step
n = int(1 + (wf - wo) / dw)  #number of frequency components

#define time domain
to = 0.0  #s - initial time for wave train
tf = 2000.0  #s - final time
dt = 0.1  #s - time step

#initial phases
#phi=[1.5,0.9,3.8,2.6,5.2,0.2,3.9,6.2,0.9,4.2,2.9,0.6,5.3,6.1,1.1]
phi = [rand() * 2 * Pi for i in range(n)]

### CALCULATIONS ###
print "Calculating wave spectrum"
#calculate domain of angular frequencies
w = [wo + i * dw for i in range(n)]

#calculate parameters of spectrum, as per Isherwood
if 2 * Pi * Hs / g / Tz**2 >= 0.037:
    gamma = 10.54 - 1.34 / sqrt(2 * Pi * Hs / g / Tz**2) - exp(
        -19 + 3.775 / sqrt(2 * Pi * Hs / g / Tz**2))
else:
    gamma = 0.9 + exp(18.86 - 3.67 / sqrt(2 * Pi * Hs / g / Tz**2))
Tp = Tz / (0.6063 + 0.1164 * sqrt(gamma) - 0.01224 * gamma)  #s
wp = 2 * Pi / Tp  #rd/s
alpha = (2.964 + 0.4788 * sqrt(gamma) - 0.343 * gamma +
示例#38
0
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from random import randint as rand

webdriver = webdriver.Chrome(executable_path='C:/Users/Ishwar/Downloads/chromedriver_win32/chromedriver.exe')#Choose your chromedriver path

webdriver.get('https://www.instagram.com/accounts/login/?source=auth_switcher')
sleep(rand(8,12))

username = webdriver.find_element_by_name('username')
username.send_keys('enter_your_username')
password = webdriver.find_element_by_name('password')
password.send_keys('enter_your_password')

#the css_selector may differ in your case 
button_login = webdriver.find_element_by_css_selector('#react-root > section > main > div > article > div > div:nth-child(1) > div > form > div:nth-child(4) > button > div')
button_login.click()
sleep(rand(8,12))

#comment below line, if you don't get a pop up asking about notifications
webdriver.find_element_by_css_selector('body > div.RnEpo.Yx5HN > div > div > div.mt3GC > button.aOOlW.HoLwm').click() 

hashtag_list = ['animation', '3d', 'design', 'blender']

follow_list = []
followed = 0
like = 0
comment = 0

for hashtag in hashtag_list:
示例#39
0
def create_plancher(self, context):
    bpy.context.user_preferences.edit.use_global_undo = False
    obj_mode = bpy.context.active_object.mode
    bpy.ops.object.mode_set(mode='OBJECT')
    bpy.context.scene.unit_settings.system = 'METRIC'
    cobj = context.object
    verts, faces = parquet(
        cobj.switch,
        cobj.nbrboards,
        cobj.height,
        cobj.randheight,
        cobj.width,
        cobj.randwith,
        cobj.gapx,
        cobj.lengthboard,
        cobj.gapy,
        cobj.shifty,
        cobj.nbrshift,
        cobj.tilt,
        cobj.herringbone,
        cobj.randoshifty,
        cobj.lengthparquet,
        cobj.trans,
        cobj.gaptrans,
        cobj.randgaptrans,
        cobj.glue,
        cobj.borders,
        cobj.lengthtrans,
        cobj.locktrans,
        cobj.nbrtrans,
    )

    # Code from Michel Anders script Floor Generator
    # Create mesh & link object to scene
    emesh = cobj.data

    mesh = bpy.data.meshes.new("Plancher_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update(calc_edges=True)

    for i in bpy.data.objects:
        if i.data == emesh:
            i.data = mesh

    name = emesh.name
    emesh.user_clear()
    bpy.data.meshes.remove(emesh)
    mesh.name = name

    #---------------------------------------------------------------------COLOR & UV
    if obj_mode == 'EDIT':  # If we are in 'EDIT MODE'
        seed(cobj.colseed)  # New random distribution
        mesh.uv_textures.new("Txt_Plancher")  # New UV map
        vertex_colors = mesh.vertex_colors.new().data  # New vertex color
        rgb = []

        if cobj.colrand > 0:  # If random color
            for i in range(cobj.colrand):
                color = [
                    round(rand(), 1),
                    round(rand(), 1),
                    round(rand(), 1)
                ]  # Create as many random color as in the colrand variable
                rgb.append(color)  # Keep all the colors in the RGB variable

        elif cobj.colphase > 0:  # If phase color
            for n in range(cobj.colphase):
                color = [
                    round(rand(), 1),
                    round(rand(), 1),
                    round(rand(), 1)
                ]  # Create as many random color as in the colphase variable
                rgb.append(color)  # Keep all the colors in the RGB variable

    #---------------------------------------------------------------------VERTEX GROUP
        bpy.context.object.vertex_groups.clear()  # Clear vertex group if exist
        if cobj.colrand == 0 and cobj.colphase == 0:  # Create the first Vertex Group
            bpy.context.object.vertex_groups.new()
        elif cobj.colrand > 0:  # Create as many VG as random color
            for v in range(cobj.colrand):
                bpy.context.object.vertex_groups.new()
        elif cobj.colphase > 0:  # Create as many VG as phase color
            for v in range(cobj.colphase):
                bpy.context.object.vertex_groups.new()

    #---------------------------------------------------------------------VERTEX COLOR
        phase = cobj.colphase
        color = {}
        for poly in mesh.polygons:  # For each polygon of the mesh

            if cobj.colrand == 0 and cobj.colphase == 0:  # If no color
                color = [rand(), rand(),
                         rand()]  # Create at least one random color

            elif cobj.colrand > 0:  # If random color

                if cobj.allrandom:  # If all random choose
                    nbpoly = len(mesh.polygons.items())  # Number of boards
                    randvg = randint(0, cobj.colrand)  # Random vertex group
                    for i in range(nbpoly):
                        color = [
                            round(rand(), 1),
                            round(rand(), 1),
                            round(rand(), 1)
                        ]  # Create as many random color as in the colrand variable
                        rgb.append(
                            color)  # Keep all the colors in the RGB variable

                else:
                    color = rgb[randint(
                        0, cobj.colrand -
                        1)]  # Take one color ramdomly from the RGB list

                for loop_index in poly.loop_indices:  # For each vertice from this polygon
                    vertex_colors[
                        loop_index].color = color  # Assign the same color
                    if cobj.allrandom:  # If all random choose
                        vg = bpy.context.object.vertex_groups[
                            randvg - 1]  # Assign a random vertex group
                    else:
                        vg = bpy.context.object.vertex_groups[rgb.index(
                            color
                        )]  # Else assign a vertex group by color index
                    vg.add([loop_index], 1, "ADD")  # index, weight, operation

            elif cobj.colphase > 0:  # If phase color
                color = rgb[phase - 1]  # Take the last color from the RGB list
                phase -= 1  # Substract 1 from the phase number
                if phase == 0:
                    phase = cobj.colphase  # When phase = 0, start again from the beginning to loop in the rgb list

                for loop_index in poly.loop_indices:  # For each vertice from this polygon
                    vertex_colors[
                        loop_index].color = color  # Assign the same color
                    vg = bpy.context.object.vertex_groups[rgb.index(color)]
                    vg.add([loop_index], 1, "ADD")  # index, weight, operation
        color.clear()  # Clear the color list

        #-----------------------------------------------------------------UV UNWRAP
        ob = bpy.context.object
        ob.select = True
        bpy.ops.object.mode_set(mode='EDIT')
        bpy.ops.uv.unwrap(method='ANGLE_BASED', correct_aspect=True)
        #-----------------------------------------------------------------UV LAYER
        me = ob.data
        bm = bmesh.from_edit_mesh(me)
        uv_lay = bm.loops.layers.uv.verify()

        #-----------------------------------------------------------------GROUP UV
        # Group all the UV points at the origin point
        # Need more work, it's not working everytimes, don't know why...
        v = 0
        tpuvx = {}
        tpuvy = {}
        for face in bm.faces:  # For each polygon
            for loop in face.loops:  # For each loop
                luv = loop[uv_lay]
                v += 1
                uv = loop[uv_lay].uv  # Keep the coordinate of the uv point
                tpuvx[
                    uv.x] = loop.index  # Keep the X coordinate of the uv point
                tpuvy[
                    uv.y] = loop.index  # Keep the Y coordinate of the uv point

                if v > 3:  # When the last uv point of this polygon is reached
                    minx = min(
                        tpuvx.keys()
                    )  # Keep the smallest value on the X axis from the 4 uv point
                    miny = min(
                        tpuvy.keys()
                    )  # Keep the smallest value on the Y axis from the 4 uv point
                    for loop in face.loops:  # A new loop in the loop ... really need more work
                        loop[uv_lay].uv[
                            0] -= minx  # For each UV point, substract the value of the smallest X
                        loop[uv_lay].uv[
                            1] -= miny  # For each UV point, substract the value of the smallest Y
                    v = 0  # Initialize counter
            tpuvx.clear()  # Clear the list
            tpuvy.clear()  # Clear the list

        bmesh.update_edit_mesh(me)  # Update the mesh

    else:
        bpy.ops.object.mode_set(
            mode='OBJECT')  # We are in 'OBJECT MODE' here, nothing to do

#---------------------------------------------------------------------MODIFIERS
    obj = context.active_object
    nbop = len(obj.modifiers)

    if nbop == 0:
        obj.modifiers.new('Solidify', 'SOLIDIFY')
        obj.modifiers.new('Bevel', 'BEVEL')
    obj.modifiers['Solidify'].show_expanded = False
    obj.modifiers['Solidify'].thickness = self.height
    obj.modifiers['Bevel'].show_expanded = False
    obj.modifiers['Bevel'].width = 0.001
    obj.modifiers['Bevel'].use_clamp_overlap

    bpy.context.user_preferences.edit.use_global_undo = True
示例#40
0
文件: gen.py 项目: dennissoftman/KhPI
#!/usr/bin/python3
from random import randint as rand

f = open('test.bin', 'wb')
for i in range(0, 10):
    num = rand(0, 2**31)
    print(num)
    f.write(num.to_bytes(4, byteorder='little'))
f.close()
示例#41
0
import json
from random import randint as rand
outMsg['message'] = 'земля ему пухом'
if user_get(user_id) == 1:
    if rand(0, 100) < 40:
        outMsg["attachment"] = vk_upload("py/357_shot1.wav", outMsg["peer_id"],
                                         "audio_message")
        vk_send('messages.send', outMsg, 1)
        outMsg = {}
        vk_send('messages.removeChatUser', {
            'chat_id': str(chat_id),
            'user_id': str(user_id)
        }, 1)
    else:
        outMsg["attachment"] = vk_upload("py/357_shot1.wav", outMsg["peer_id"],
                                         "audio_message")
        vk_send('messages.send', outMsg, 1)
        outMsg["attachment"] = vk_upload("py/357_reload1.wav",
                                         outMsg["peer_id"], "audio_message")
        outMsg['message'] = 'живучий попался'
        vk_send('messages.send', outMsg, 1)
        outMsg = {}
else:
    try:
        id = ''
        try:
            id = str(
                json.loads(
                    vk_send('messages.getById', {'message_ids': str(msg_id)},
                            1))['response']['items'][0]['fwd_messages'][0]
                ['user_id'])
示例#42
0
#!/usr/bin/python
from os import popen
from os import mkdir
from sys import argv
from random import random as rand
N = int(argv[1])

key = "\xef\xbe\xff\xde"

for t in range(N):
    mkdir('team%d' % t)
    sec = ""
    L = 32
    for i in range(L):
        sec += chr(ord('a') + int(rand() * 26))
    sec = sec.upper()
    file('team%d/flag.txt' % t, 'w+').write(sec)
    popen(
        "echo 'INSERT INTO `flags` (`teamID`, `taskID`, `flag`) VALUES (%d, 15, '\"'\"%s\"'\"');\' >> rev500.sql"
        % ((t + 1), sec))
    sec = list(sec)
    for i in range(len(sec)):
        sec[i] = chr(ord(sec[i]) ^ ord(key[i % 4]))
    sec = "\\\\x".join(['{:02x}'.format(ord(c)) for c in sec])
    rep = "cat rev500.c | sed 's/bupass/\\\\x%s/'" % (sec)
    source = popen(rep).read()

    f = file('team%d/rev500.c' % t, 'w+')
    f.write(source)
示例#43
0
def delete(cur):
    rm = rand(1,5)
    cur.execute('DELETE FROM users WHERE projid=%d' % rm)
    return rm, getRC(cur)
示例#44
0
# Create an empty maze.
initMaze(mazeXSize, mazeYSize)

# Loop until we have no more starting points (2's in the empty maze)
while filter(lambda x: 2 in x, maze):
    # Get the X and Y values of the first point in our randomized list.
    rx = spl[0][0]
    ry = spl[0][1]
    # Pop the first entry in the list, this deletes it and the rest move down.
    spl.pop(0)
    # Check to see if our chosen point is still a valid starting point.
    ud = False
    if maze[rx][ry] == 2:
        ud = True
        # Pick a random wall length up to the maximum.
        rc = rand(0, maxWallLen)
        # Pick a random direction.
        rd = randDir()
        fc = rd
        loop = True
        while loop:
            # Look in each direction, if the current wall being built is stuck inside itself start again.
            if maze[rx][ry - 2] == 3 and maze[rx][ry + 2] == 3 and maze[
                    rx - 2][ry] == 3 and maze[rx + 2][ry] == 3:
                #
                # Code to clear maze area required
                #
                initMaze(mazeXSize, mazeYSize)
                break
            # Look ahead to see if we're okay to go in this direction.....
            cx = rx + (rd[0] * 2)
示例#45
0
 def __init__(self):
     self.verts = ((-10, -3, 20), (10, -3, 20), (-10, -3, -300), (10, -3,
                                                                  -300))
     self.color = (rand(), rand(), rand())
示例#46
0
def Game(Team1,Team2):
        timer = 0
        MatchTeam1=MatchTeam(Team1)
        MatchTeam2=MatchTeam(Team2)
        activeteam=MatchTeam1
        notactiveteam=MatchTeam2
        additionaltime=90
        attackpointer=0
        while timer<=180:
                time=int(timer/2)
                activeteam.addProssession()
                if time == 45 or time == 90:
                        additionaltime = rand(0, 5)
                chance = rand(0,100)
                if chance <=20:
                        player = rand(1, 10)
                        activeplayer = notactiveteam.Team.StartPlayers[player]
                        while activeplayer.RedCard==1:
                                player=rand(1, 10)
                                activeplayer = notactiveteam.Team.StartPlayers[player]
                        if rand(0,150)==75:
                                notactiveteam.addRed(player)
                        elif rand(0,100)<=10:
                                notactiveteam.addYellow(player)
                        if rand(0,200)<=2:
                                activeplayer=activeteam.Team.StartPlayers[rand(1,10)]
                                for Player in activeteam.Team.ReservePlayers:
                                        if Player.Position==activeplayer.Position and Player.IsSubstitution==0:
                                                Player.IsSubstitution=1
                                                Player,activeplayer=activeplayer,Player
                                                activeteam.Substitution-=1
                                                break
                if ((time>=60 and rand(0,100)<=5) or rand(0,200<=4)) and activeteam.Substitution==0:
                        activeplayer = activeteam.Team.StartPlayers[rand(1, 10)]
                        for Player in activeteam.Team.ReservePlayers:
                                if Player.Position == activeplayer.Position:
                                        Player.IsSubstitution = 1
                                        Player, activeplayer = activeplayer, Player
                                        activeteam.Substitution -= 1
                                        break
                if attackpointer<4:
                        chance = rand(0,100)
                        activeplayer = activeteam.Team.StartPlayers[rand(activeteam.Team.Defenders,10)]
                        while activeplayer.RedCard == 1:
                                activeplayer = activeteam.Team.StartPlayers[rand(activeteam.Team.Defenders, 10)]
                        if chance<activeplayer.Rating:
                                attackpointer+=1
                                activeteam.addSecsessfulPass()
                        else:
                                attackpointer=0
                                activeteam.addPass()
                                activeteam, notactiveteam = notactiveteam, activeteam
                else:
                        chance = rand(0,100)
                        if chance<=50:
                                chance = rand(0, 100)
                                activeplayer = activeteam.Team.StartPlayers[rand(activeteam.Team.Defenders, 10)]
                                while activeplayer.RedCard == 1:
                                        activeplayer = activeteam.Team.StartPlayers[rand(activeteam.Team.Defenders, 10)]
                                if chance < activeplayer.Rating:
                                        attackpointer += 1
                                        activeteam.addSecsessfulPass()
                                else:
                                        attackpointer=0
                                        activeteam.addPass()
                                        activeteam, notactiveteam = notactiveteam, activeteam
                        else:
                                chance = rand(0,100)
                                if chance <30:
                                        activeplayer = activeteam.Team.StartPlayers[rand(activeteam.Team.Defenders,10-activeteam.Team.Strikers)]
                                        while activeplayer.RedCard == 1:
                                                activeplayer = activeteam.Team.StartPlayers[rand(activeteam.Team.Defenders, 10 - activeteam.Team.Strikers)]
                                else:
                                        activeplayer = activeteam.Team.StartPlayers[rand(10 - activeteam.Team.Strikers,10)]
                                        while activeplayer.RedCard == 1:
                                                activeplayer = activeteam.Team.StartPlayers[rand(activeteam.Team.Defenders, 10 - activeteam.Team.Strikers)]
                                chance=rand(0,100)
                                if chance<=activeplayer.Rating/2:
                                        activeteam.addShoot()
                                        activeteam, notactiveteam = notactiveteam, activeteam
                                        attackpointer=0
                                elif rand(0,activeplayer.Shoot)>notactiveteam.Team.StartPlayers[0].Rating/2:
                                        activeteam.addGoal()
                                        activeteam, notactiveteam = notactiveteam, activeteam
                                        attackpointer=0

                                else:
                                        activeteam.addSecsessfilShoot()
                                        notactiveteam.addSave()
                                        activeteam, notactiveteam = notactiveteam, activeteam
                                        attackpointer=0
                timer+=1
                sleep(0)
                if time==additionaltime+45 or time==additionaltime+90:
                        timer-=additionaltime*2
                        additionaltime=90
                        if time==45:
                                pass
                        timer+=1
        activeteam.Prossession=int(activeteam.Prossession/(activeteam.Prossession+notactiveteam.Prossession)*100)
        notactiveteam.Prossession=100-activeteam.Prossession
        activeteam.AllPass*=2
        activeteam.SecsessfulPass*=2
        notactiveteam.AllPass*=2
        notactiveteam.SecsessfulPass*=2
        if activeteam.Goals>notactiveteam.Goals:
                activeteam.Team.Points+=3
                activeteam.Team.WinGames+=1
                notactiveteam.Team.LoseGames+=1
        elif notactiveteam.Goals>activeteam.Goals:
                notactiveteam.Team.Points+=3
                activeteam.Team.LoseGames+=1
                notactiveteam.Team.WinGames+=1
        else:
                activeteam.Team.Points+=1
                activeteam.Team.DrawGames+=1
                notactiveteam.Team.DrawGames+=1
                notactiveteam.Team.Points+=1
        activeteam.Team.Games+=1
        notactiveteam.Team.Games += 1
    dir = os.path.join(cwd, "model_" + str(i))
    if not os.path.exists(dir):
        os.mkdir(dir)
    #model = os.path.join(dir,'model1.tam')
    model = os.path.join(cwd, 'model1.tam')
    copyfile(pattern, model)

    # записываем случайные параметры в файл
    f = open(model, 'r')  # pass an appropriate path of the required file
    lines = f.readlines()
    n = 46
    # dn, dt generation from Bakulin Grechka Tsvankin article "Estimation of fracture parameters from reflection seismic data -- Part I"
    Vs = 2750
    Vp = 5000
    g = (Vs**2) / (Vp**2)
    e = 0.1 * rand()

    # dry
    dn = 4 * e / (3 * g * (1 - g))
    dt = 16 * e / (3 * (3 - 2 * g))
    eps = -2 * g * (1 - g) * dn / (1 - dn * (1 - 2 * g)**2)
    delta = -2 * g * ((1 - 2 * g) * dn + dt) * (1 - (1 - 2 * g) * dn) / (
        (1 - dn * (1 - 2 * g)**2) * (1 + (g * dt - dn * (1 - 2 * g)**2) /
                                     (1 - g)))
    gamma = -1 * dt / 2

    alpha = 5.0
    lines[n - 1] = anisotropic_parameters(
        eps, delta, gamma, alpha
    )  # n is the line number you want to edit; subtract 1 as indexing of list starts from 0
    f.close(
    def getRandomSystem():
        def getVarPart(
            lvl, n
        ):  # lvl: level of imbricated parenthesis / n: current variable name used / isFirst
            while True:
                coef = LOW_COEF // 3 + rand(RNG_COEF // 3)
                if not lvl or coef:
                    break  # zero coefficient is not allowed at other levels than the first one

            if not coef: return ""  # may return blank only at first level

            varPart = "{}".format(
                lstVars[n] if rand(100) >= BRACKETS_PROBA -
                DECREASE_PROBA * lvl else "({})".format(" + ".join(
                    getVarPart(lvl + 1, rand(1, nVars))
                    for _ in range(rand(2, 4))).replace("+ -", "- ")))
            return "{}{}".format(coef, varPart)

        nVars = MIN_VARS + rand(
            ADD_VARS + 1)  # number of variables names (all different)

        varSet = set()
        while len(varSet) < nVars:
            varSet.add(chr([65, 97][rand(2)] + rand(26))
                       )  # generate names (1 letter only, lower and uppercase)

        lstVars = list(varSet)
        """ Generate the coefficients for all the variables in the examples:
              - First line left blank (will be the formula)
              - diagonal terms always 0: never find the current variable in its own definition
              - generate a triangular matrix, so that there are good odds that one can find a solution to the simplification
              - first variable will NEVER have a 0 coefficient
        """
        coefM = [
            [
                0 if x == 0 or y >= x
                else  # first line blank ; upper triangle blank
                (1 + rand(RNG_COEF // 2)) * (-1)**rand(2) if y == 0
                else  # first column: always != 0, positive or negative
                (LOW_COEF + rand(RNG_COEF)) * (
                    rand(100) >= ZERO_PROBA
                )  # other: any number in [LOW_COEF, LOW_COEF + RNG_COEF] or 0 with a probability of ZERO_PROBA
                for y in range(nVars)
            ] for x in range(nVars)
        ]

        def genEq(x):
            eq = " + ".join("{}{}".format(coefM[x][y], lstVars[y])
                            for y in range(nVars) if coefM[x][y]).replace(
                                "+ -", "- ") + " = " + lstVars[x]
            return re.sub(r'\b1(?=\w)', '', eq)

        """ Convert to examples equations """
        eqSyst = [[""] if x == 0 else genEq(x) for x in range(nVars)]
        """Generate the formula: does not contain the first variable """
        formula, x = '', 0
        while not formula:
            x += 1
            if x == 100:
                print(
                    "problem in the random tests: cannot generate a valid formula. Please raise an issue in the discourse with the info below:"
                )
                print('vars:', lstVars, 'nVars=', nVars, '\n')
                print('coefM:')
                print('\n'.join(map(str, coefM)))
                print('système:')
                print(eqSyst)
                raise Exception('nope')

            formula = " + ".join(
                part for part in [getVarPart(0, n) for n in range(1, nVars)]
                if part).replace("+ -", "- ")
        eqSyst[0] = formula

        if DEBUG_RAND:
            print("------------")
            print('\n'.join(str(eq) for eq in eqSyst))

        return eqSyst
示例#49
0
def lsl_dummy_stream():
    # first create a new stream info (here we set the name to BioSemi,
    # the content-type to EEG, 8 channels, 100 Hz, and float-valued data) The
    # last value would be the serial number of the device or some other more or
    # less locally unique identifier for the stream as far as available (you
    # could also omit it but interrupted connections wouldn't auto-recover)
    info = StreamInfo('DummyStream' + str(freqHz) + 'Hz', 'EEG', 15, freqHz, 'float32', 'myuid342345')

    # next make an outlet
    outlet = StreamOutlet(info)

    print("now sending data...")
    try:
        print("Press Ctrl+C to terminate")
        while True:
            # make a new random 15-channel sample; this is converted into a
            # pylsl.vectorf (the data type that is expected by push_sample)
            mysample = [rand(), rand(), rand(), rand(), rand(), rand(), rand(), rand(), rand(), rand(), rand(), rand(),
                        rand(), rand(), rand()]
            # now send it and wait for a bit
            outlet.push_sample(mysample)
            time.sleep(1.0/freqHz)
    except KeyboardInterrupt:
        del outlet
        print("Loop terminated, shutting stream down")
        time.sleep(0.5)
    return    
示例#50
0
from random import randint as rand

cases = int(input("Gerar quantos casos? -> "))

for number in range(1, cases+1):
    file = open('../input/' + str(number), 'w')
    S, D = [rand(1,10), rand(1,10000)]
    file.write(str(S) + ' ' + str(D) + '\n')
    for i in range(S):
        file.write(str(rand(1, 100)) + ' ')
    file.close()
示例#51
0
    def update(self):
        self.x = self.next_x
        self.y = self.next_y
        self.status = self.next_status


BETA = 0.20
GAMMA = 0.01
MOVE = 0.75
SIZE = 80
I0 = 0.1
I_RADIUS = 2
NAGENTS = 200
AGENTS = [
    Patient(int(rand() * SIZE), int(rand() * SIZE), int(rand() < I0))
    for _ in range(NAGENTS)
]

N_S = len([a for a in AGENTS if a.status == 0])
N_I = len([a for a in AGENTS if a.status == 1])
IN = [N_S, N_I]

MAX_TIME = 200
for TIME in range(MAX_TIME):

    showPlot(TIME >= MAX_TIME - 1)

    for a in AGENTS:
        a.do_actions()
示例#52
0
def mcrn_syslogger():
   #############################################################################
   ### DRIVE DIAGNOSTIC CYCLE REPORT:
   when = dt.utcnow()
   choices = ['nom'] * 80 + ['chk'] * 15 + ['err!'] * 5
   reactor = choose(choices)
   thrust = rand(6013579, 6370000)
   Isp = rand(1768971, 1927000)
   Ve1 = rand(4, 6); Ve2 = rand(1, 8)
   mfr1 = rand(1, 2); mfr2 = rand(1, 9)
   thP1 = rand(57, 60); thP2 = rand(1, 9)
   tpo1 = rand(93,96); tpo2 = rand(1, 79)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="drive diagnostic cycle" report="' + when.strftime('%H:%M:%S') + ': r:' + reactor + ' | t:' + str(thrust) + 'N | Isp:' + str(Isp) + 's | Ve:' + str(Ve1) + '.' + str(Ve2) + '%ls | mfr:' + str(mfr1) + '.' + str(mfr2) + 'kg/s | thP:' + str(thP1) + '.' + str(thP2) + 'tw | tpo:' + str(tpo1) + '.' + str(tpo2) + 'tw"' )
   #############################################################################
   ### PRIMARY LOCK SYSTEMS:
   when = dt.utcnow()
   if when.strftime('%M')[1] in [ '0', '2', '4', '6', '8' ] and when.strftime('%S')[0] in [ '3' ]:
      values_status = [ 'LOCKED' ] * 60 + ['UNLOCKED'] * 40
      values_method = [ 'PIN', 'MANUAL' ]
      values_byWhom = [ 'CHRISSIE', 'BURTONA', 'GUNNY', 'HOLDENJ', 'KAMALA', 'NAGATAN', 'PEACHES', 'PRAXTHEMENG' ]
      ########### LOCK CPS-01:
      status = choose( values_status )
      if status == 'UNLOCKED':
         method = choose( values_method )
         if method == 'PIN':
            byWhom = choose( values_byWhom )
         else:
            byWhom = 'N/A'
      else:
         method = 'N/A'; byWhom = 'N/A'
      print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="lock status" lock="CPS-01" status="' + status + '" unlock_method="' + method + '" unlocked_by="' + byWhom + '"' )
      ########### LOCK CPS-02:
      status = choose( values_status )
      if status == 'UNLOCKED':
         method = choose( values_method )
         if method == 'PIN':
            byWhom = choose( values_byWhom )
         else:
            byWhom = 'N/A'
      else:
         method = 'N/A'; byWhom = 'N/A'
      print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="lock status" lock="CPS-02" status="' + status + '" unlock_method="' + method + '" unlocked_by="' + byWhom + '"' )
      ########### LOCK CPS-03:
      status = choose( values_status )
      if status == 'UNLOCKED':
         method = choose( values_method )
         if method == 'PIN':
            byWhom = choose( values_byWhom )
         else:
            byWhom = 'N/A'
      else:
         method = 'N/A'; byWhom = 'N/A'
      print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="lock status" lock="CPS-03" status="' + status + '" unlock_method="' + method + '" unlocked_by="' + byWhom + '"' )
      ########### LOCK CPS-04:
      status = choose( values_status )
      if status == 'UNLOCKED':
         method = choose( values_method )
         if method == 'PIN':
            byWhom = choose( values_byWhom )
         else:
            byWhom = 'N/A'
      else:
         method = 'N/A'; byWhom = 'N/A'
      print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="lock status" lock="CPS-04" status="' + status + '" unlock_method="' + method + '" unlocked_by="' + byWhom + '"' )
      ########### LOCK CPS-05:
      status = choose( values_status )
      if status == 'UNLOCKED':
         method = choose( values_method )
         if method == 'PIN':
            byWhom = choose( values_byWhom )
         else:
            byWhom = 'N/A'
      else:
         method = 'N/A'; byWhom = 'N/A'
      print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="lock status" lock="CPS-05" status="' + status + '" unlock_method="' + method + '" unlocked_by="' + byWhom + '"' )
   #############################################################################
   ### SUB-SYSTEM STATUS:
   when = dt.utcnow()
   if when.strftime('%M')[1] in [ '1', '3', '5', '7', '9' ]:
      choices = ['N'] * 60 + ['C'] * 30 + ['E!'] * 10
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="ASTRO_GEO" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="AUTOPILOT" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="DOCK_CLAMP" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="FILTER_A" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="FILTER_W" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="GALL_COFFEE" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="GALL_COOK" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="GALL_FRIDGE" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="HOLD_CRANE" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="CLIMATE" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="COMMS_INT" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="CPIT_CTRL" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="LIGHTING" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="1" system="LOCKS_INT" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="MED_AUTODOC" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="MED_MONITOR" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="RAIL_TARG" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="REACT_INIT" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="REACT_CONTAIN" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="REACT_CHILLOUT" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="PDC_ACQ" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="PDC_TARG" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="PDC_TRACK" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="THRUST_CTRL" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="TORP_ACQ" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="TORP_TARG" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="TORP_TRACK" status="' + status[0] + '"' )
      status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="sub-system status" column="2" system="WASTE_MGMT" status="' + status[0] + '"' )
   #############################################################################
   ### SELECTED INVENTORY ITEM:
   when = dt.utcnow()
   if when.strftime('%M')[1] in [ '0', '2', '6', '8' ]:
      power = rand(11, 89); efficiency = rand(39, 99); error_rate = rand(3, 59); cleanup = rand(69, 99)
      print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="inventory" serial="1_LFEIPB4UJ" item="40mm Secondary Display System" class="III" state="OK" status="Online" power="' + str(power) + '" efficiency="' + str(efficiency) + '" error_rate="' + str(error_rate) + '" cleanup="' + str(cleanup) + '" log="{[\'date\':\'2020-03-23\',\'work\':\'created rollback point and patched firmware to newest version\',\'modification\':\'mod1\',\'by\':\'BURTONA\'],[\'date\':\'2020-03-25\',\'work\':\'rolled firmware to restore point due to screen tearing issue\',\'modification\':\'mod2\',\'by\':\'PEACHES\']}"' )
   #############################################################################
   ### DOOR SYSTEM INTEGRITY:
   when = dt.utcnow()
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="A01" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="A02" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="BA1" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="BA2" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="BA3" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="BA4" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="C11" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="D23" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="E01" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="E02" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="H01" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="M1A" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="M16" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="N77" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="P29" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="P76" integrity="' + str(integrity) + '"' )
   integrity = rand(71, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="system integrity" system="P77" integrity="' + str(integrity) + '"' )
   #############################################################################
   ### PRESSURE VALVE 2:
   when = dt.utcnow()
   seal = rand(81, 100); inlet = rand(81, 100); housing = rand(81, 100); pressure = rand(81, 100);
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure control valve" pressure_valve="V02" seal_strength="' + str(seal) + '" inlet_strength="' + str(inlet) + '" housing_integrity="' + str(housing) + '" pressure="' + str(pressure) + '"' )
   #############################################################################
   ### TORPEDO FUEL DORSAL
   when = dt.utcnow()
   value = rand(89,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo fuel" tube="dorsal" fuel="' + str(value) + '"' )
   #############################################################################
   ### DRIVE PLUME WASTE 1:
   when = dt.utcnow()
   waste = rand(11, 39)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="drive plume waste" sensor="01" waste="' + str(waste) + '"' )
   #############################################################################
   ### FORE THRUSTER PERFORMANCE:
   when = dt.utcnow()
   performance = rand(79, 99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="thruster performance" thruster="fore" performance="' + str(performance) + '"' )
   #############################################################################
   ### REACTOR CONTAINMENT FIELD PERFORMANCE:
   when = dt.utcnow()
   performance = rand(89, 99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="reactor performance" metric="containment field integrity" performance="' + str(performance) + '"' )
   #############################################################################
   ### POWER MAIN ALFA:
   when = dt.utcnow()
   power =  rand(11, 97)
   kw = rand(19, 25)
   dtr=kw*27
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="power main" main="01" power="' + str(power) + '" max_throughput="' + str(kw) + '" days_til_repair="' + str(dtr) + '"' )
   #############################################################################
   ### PRESSURE VALVE 5:
   time = dt.utcnow()
   seal = rand(81, 100); inlet = rand(81, 100); housing = rand(81, 100); pressure = rand(81, 100);
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure control valve" pressure_valve="V05" seal_strength="' + str(seal) + '" inlet_strength="' + str(inlet) + '" housing_integrity="' + str(housing) + '" pressure="' + str(pressure) + '"' )
   #############################################################################
   ###  TORPEDO PROJECTIONS VENTRAL:
   when = dt.utcnow()
   value = rand(79,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo metrics" tube="ventral" metric="projected specific impulse" metric_abbrev="pIsp" value="' + str(value) + '"' )
   value = rand(79,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo metrics" tube="ventral" metric="projected impulse" metric_abbrev="pI" value="' + str(value) + '"' )
   value = rand(79,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo metrics" tube="ventral" metric="projected thrust" metric_abbrev="pTh" value="' + str(value) + '"' )
   value = rand(79,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo metrics" tube="ventral" metric="projected mass ratio" metric_abbrev="pMR" value="' + str(value) + '"' )
   #############################################################################
   ### REACTOR INJECTOR ANTIMATTER:
   when = dt.utcnow()
   performance = rand(79, 99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="reactor performance" metric="injector integrity - antimatter" performance="' + str(performance) + '"' )
   #############################################################################
   ### DRIVE PLUME WASTE 3:
   when = dt.utcnow()
   waste = rand(29, 79)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="drive plume waste" sensor="03" waste="' + str(waste) + '"' )
   #############################################################################
   ### INTERNAL PRESSURE:
   when = dt.utcnow()
   metric = rand(3, 25); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure bars Internal Pressure" metric="' + str(metric) + '"' )
   #############################################################################
   ### POWER MAIN DELTA:
   when = dt.utcnow()
   power =  rand(11, 97)
   kw = rand(19, 25)
   dtr=kw*27
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="power main" main="04" power="' + str(power) + '" max_throughput="' + str(kw) + '" days_til_repair="' + str(dtr) + '"' )
   #############################################################################
   ### PRESSURE SENSOR STATUS:
   when = dt.utcnow()
   choices = ['Nominal'] * 60 + ['Check'] * 30 + ['Error!'] * 10
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="CREW01" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="CREW02" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="MED01" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="MED02" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="OPS01" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="OPS02" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="OPS03" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="HOLD01" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="HOLD02" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="HOLD03" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="HOLD04" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="ENG01" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="ENG02" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="ENG03" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="GALL01" sensor_status="' + status + '"' )
   status = choose(choices); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure sensor" sensor_id="SHOP01" sensor_status="' + status + '"' )
   #############################################################################
   ### PRESSURE VALVE 3:
   time = dt.utcnow()
   seal = rand(81, 100); inlet = rand(81, 100); housing = rand(81, 100); pressure = rand(81, 100);
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure control valve" pressure_valve="V03" seal_strength="' + str(seal) + '" inlet_strength="' + str(inlet) + '" housing_integrity="' + str(housing) + '" pressure="' + str(pressure) + '"' )
   #############################################################################
   ### REACTOR OVERALL EFFICIENCY:
   when = dt.utcnow()
   performance = rand(79, 99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="reactor performance" metric="overall efficiency" performance="' + str(performance) + '"' )
   #############################################################################
   ### OXYGEN / C02:
   time = dt.utcnow()
   metric = rand(89, 99); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure bars Oxygen/C02" metric="' + str(metric) + '"' )
   #############################################################################
   ### TORPEDO FUEL VENTRAL:
   time = dt.utcnow()
   value = rand(89,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo fuel" tube="ventral" fuel="' + str(value) + '"' )
   #############################################################################
   ### DRIVE PLUME WASTE 5:
   when = dt.utcnow()
   waste = rand(49, 99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="drive plume waste" sensor="05" waste="' + str(waste) + '"' )
   #############################################################################
   ### COMMS STATUS BARS:
   when = dt.utcnow()
   value = rand(69, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="console selected system" metric="throughput" value="' + str(value) + '"' )
   value = rand(69, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="console selected system" metric="resolution" value="' + str(value) + '"' )
   value = rand(69, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="console selected system" metric="cleanup" value="' + str(value) + '"' )
   value = rand(69, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="console selected system" metric="receiver" value="' + str(value) + '"' )
   value = rand(69, 100); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="console selected system" metric="transmitter" value="' + str(value) + '"' )
   #############################################################################
   ### POWER MAIN BRAVO:
   when = dt.utcnow()
   power =  rand(11, 97)
   kw = rand(19, 25)
   dtr=kw*27
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="power main" main="02" power="' + str(power) + '" max_throughput="' + str(kw) + '" days_til_repair="' + str(dtr) + '"' )
   #############################################################################
   ### TORPEDO PROJECTIONS DORSAL:
   when = dt.utcnow()
   value = rand(79,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo metrics" tube="dorsal" metric="projected specific impulse" metric_abbrev="pIsp" value="' + str(value) + '"' )
   value = rand(79,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo metrics" tube="dorsal" metric="projected impulse" metric_abbrev="pI" value="' + str(value) + '"' )
   value = rand(79,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo metrics" tube="dorsal" metric="projected thrust" metric_abbrev="pTh" value="' + str(value) + '"' )
   value = rand(79,99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="torpedo metrics" tube="dorsal" metric="projected mass ratio" metric_abbrev="pMR" value="' + str(value) + '"' )
   #############################################################################
   ### PRESSURE VALVE 4:
   time = dt.utcnow()
   seal = rand(81, 100); inlet = rand(81, 100); housing = rand(81, 100); pressure = rand(81, 100);
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure control valve" pressure_valve="V04" seal_strength="' + str(seal) + '" inlet_strength="' + str(inlet) + '" housing_integrity="' + str(housing) + '" pressure="' + str(pressure) + '"' )
   #############################################################################
   ### EXTERNAL PRESSURE:
   when = dt.utcnow()
   metric = rand(3, 25); print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure bars External Pressure" metric="' + str(metric) + '"' )
   #############################################################################
   ### DRIVE PLUME WASTE 2:
   when = dt.utcnow()
   waste = rand(19, 59)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="drive plume waste" sensor="02" waste="' + str(waste) + '"' )
   #############################################################################
   ### REACTOR INJECTOR DEUTERIUM:
   when = dt.utcnow()
   performance = rand(79, 99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="reactor performance" metric="injector integrity - deuterium" performance="' + str(performance) + '"' )
   #############################################################################
   ### AFT THRUSTER PERFORMANCE:
   when = dt.utcnow()
   performance = rand(79, 99)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="thruster performance" thruster="aft" performance="' + str(performance) + '"' )
   #############################################################################
   ### PRESSURE VALVE 1:
   time = dt.utcnow()
   seal = rand(81, 100); inlet = rand(81, 100); housing = rand(81, 100); pressure = rand(81, 100);
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="pressure control valve" pressure_valve="V01" seal_strength="' + str(seal) + '" inlet_strength="' + str(inlet) + '" housing_integrity="' + str(housing) + '" pressure="' + str(pressure) + '"' )
   #############################################################################
   ### POWER MAIN CAIN IS FOR CHARLIE AND DELTA IS FOR CAIN:
   when = dt.utcnow()
   power =  rand(11, 97)
   kw = rand(19, 25)
   dtr=kw*27
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="power main" main="03" power="' + str(power) + '" max_throughput="' + str(kw) + '" days_til_repair="' + str(dtr) + '"' )
   #############################################################################
   ### DRIVE PLUME WASTE 4:
   when = dt.utcnow()
   waste = rand(39, 89)
   print( 'timestamp="' + when.strftime('%Y-%m-%dT%H:%M:%SZ') + '" type="drive plume waste" sensor="04" waste="' + str(waste) + '"' )
示例#53
0
def randomNumberGenerator():

    print(random.rand(1, 10))
示例#54
0
from random import randrange as rand


def sum(arr):
    if len(arr) == 1:
        return arr[0]
    else:
        return arr.pop(0) + sum(arr)


arr = [rand(10) for i in range(rand(10))]

print(f'For array {arr} sum is {sum(arr)}')
示例#55
0
    def __call__(self, instance):
        img_path, tokens_b = instance[:2]
        tokens_a = ['[UNK]'] * self.len_vis_input

        num_truncated_a, _ = truncate_tokens_pair(
            tokens_a,
            tokens_b,
            self.max_len - 3,
            max_len_a=self.max_len_a,
            max_len_b=self.max_len_b,
            trunc_seg=self.trunc_seg,
            always_truncate_tail=self.always_truncate_tail)

        # Add Special Tokens
        tokens = ['[CLS]'] + tokens_a + ['[SEP]'] + tokens_b + ['[SEP]']

        if self.new_segment_ids:
            if self.mode == 's2s':
                segment_ids = [4] * (len(tokens_a) +
                                     2) + [5] * (len(tokens_b) + 1)
            elif self.mode == 'bi':
                segment_ids = [0] * (len(tokens_a) +
                                     2) + [1] * (len(tokens_b) + 1)
            elif self.mode == 'l2r':
                segment_ids = [2] * (len(tokens))
        else:
            segment_ids = [0] * (len(tokens_a) + 2) + [1] * (len(tokens_b) + 1)

        # For masked Language Models
        # the number of prediction is sometimes less than max_pred when sequence is short
        effective_length = len(tokens_b)
        n_pred = min(self.max_pred,
                     max(1, int(round(effective_length * self.mask_prob))))
        # candidate positions of masked tokens
        cand_pos = []
        special_pos = set()
        for i, tk in enumerate(tokens):
            # only mask tokens_b (target sequence)
            # we will mask [SEP] as an ending symbol
            if (i >= len(tokens_a) + 2) and (tk != '[CLS]'):
                cand_pos.append(i)
            else:
                special_pos.add(i)
        shuffle(cand_pos)

        masked_pos = cand_pos[:n_pred]

        if self.mask_image_regions:
            vis_masked_pos = np.random.choice(
                self.len_vis_input,
                int(self.len_vis_input * self.vis_mask_prob),
                replace=False
            ) + 1  # +1 for [CLS], always of the same length, no need to pad
        else:
            vis_masked_pos = []

        masked_tokens = [tokens[pos] for pos in masked_pos]
        for pos in masked_pos:
            if rand() < 0.8:  # 80%
                tokens[pos] = '[MASK]'
            elif rand() < 0.5:  # 10%
                tokens[pos] = get_random_word(self.vocab_words)
        # when n_pred < max_pred, we only calculate loss within n_pred
        masked_weights = [1] * len(masked_tokens)

        # Token Indexing
        input_ids = self.indexer(tokens)
        masked_ids = self.indexer(masked_tokens)

        # Zero Padding
        n_pad = self.max_len - len(input_ids)
        input_ids.extend([0] * n_pad)
        segment_ids.extend([0] * n_pad)

        # self-attention mask
        input_mask = torch.zeros(self.max_len, self.max_len, dtype=torch.long)
        second_st, second_end = len(tokens_a) + 2, len(tokens_a) + len(
            tokens_b) + 3

        if self.mode == "s2s":
            input_mask[:, :len(tokens_a) + 2].fill_(1)
            input_mask[second_st:second_end, second_st:second_end].copy_(
                self._tril_matrix[:second_end - second_st, :second_end -
                                  second_st])
        elif self.mode == 'bi':
            input_mask = torch.tensor([1]*len(tokens)+[0]*n_pad, dtype=torch.long) \
                .unsqueeze(0).expand(self.max_len, self.max_len).clone()
        elif self.mode == 'l2r':
            st, end = 0, len(tokens_a) + len(tokens_b) + 3
            input_mask[st:end, st:end].copy_(self._tril_matrix[:end, :end])

        if self.mask_image_regions:
            input_mask[:, vis_masked_pos].fill_(
                0)  # block the masked visual feature

        # Zero Padding for masked target
        if self.max_pred > n_pred:
            n_pad = self.max_pred - n_pred
            masked_ids.extend([0] * n_pad)
            masked_pos.extend([0] * n_pad)
            masked_weights.extend([0] * n_pad)

        if not self.enable_butd:
            # loading images
            img = Image.open(img_path).convert('RGB')
            img = self.Resize(img)
            img = self.RandomCrop(img)
            img = self.ToTensor(img)
            img = self.res_Normalize(img)
        else:
            # loading pre-processed features
            img_id = img_path.split('/')[-1].split('.')[0]
            if self.region_det_file_prefix != '':
                # read data from h5 files
                with h5py.File(self.region_det_file_prefix+'_feat'+img_id[-3:] +'.h5', 'r') as region_feat_f, \
                        h5py.File(self.region_det_file_prefix+'_cls'+img_id[-3:] +'.h5', 'r') as region_cls_f, \
                        h5py.File(self.region_bbox_file, 'r') as region_bbox_f:
                    img = torch.from_numpy(region_feat_f[img_id][:]).float()
                    cls_label = torch.from_numpy(
                        region_cls_f[img_id][:]).float()
                    vis_pe = torch.from_numpy(region_bbox_f[img_id][:])
            else:
                # legacy, for some datasets, read data from numpy files
                img = torch.from_numpy(np.load(img_path))
                cls_label = torch.from_numpy(
                    np.load(img_path.replace('.npy', '_cls_prob.npy')))
                with h5py.File(self.region_bbox_file, 'r') as region_bbox_f:
                    vis_pe = torch.from_numpy(region_bbox_f[img_id][:])

            # lazy normalization of the coordinates...
            w_est = torch.max(vis_pe[:, [0, 2]]) * 1. + 1e-5
            h_est = torch.max(vis_pe[:, [1, 3]]) * 1. + 1e-5
            vis_pe[:, [0, 2]] /= w_est
            vis_pe[:, [1, 3]] /= h_est
            assert h_est > 0, 'should greater than 0! {}'.format(h_est)
            assert w_est > 0, 'should greater than 0! {}'.format(w_est)
            rel_area = (vis_pe[:, 3] - vis_pe[:, 1]) * (vis_pe[:, 2] -
                                                        vis_pe[:, 0])
            rel_area.clamp_(0)

            vis_pe = torch.cat(
                (vis_pe[:, :4], rel_area.view(-1, 1), vis_pe[:, 5:]),
                -1)  # confident score
            normalized_coord = F.normalize(vis_pe.data[:, :5] - 0.5, dim=-1)
            vis_pe = torch.cat((F.layer_norm(vis_pe, [6]), \
                F.layer_norm(cls_label, [1601])), dim=-1) # 1601 hard coded...

            # process answer
            if self.ans_proc:
                ans_tk = self.ans_proc(instance[2])['answers_scores']
            else:
                ans_tk = img.new(1)

        return (input_ids, segment_ids, input_mask, masked_ids, masked_pos,
                masked_weights, -1, self.task_idx, img, vis_masked_pos, vis_pe,
                ans_tk)
示例#56
0
    def Pattern(self):

        Inhibition = input('Inhibition Network? Yes=Y, No=N: ')

        print()
        print()
        print('The kernel we are using is:')
        rvalues = list(arange(-100, 100, 0.01))
        print(len(rvalues))
        KernelMap = map(self.Kernel, rvalues)
        KernelList = list(KernelMap)

        #Plot Kernel
        plt.plot(rvalues, KernelList, 'r', lw=1)
        plt.ylabel('Kernel', fontsize=30)
        plt.xlabel('x (cm)', fontsize=30)
        plt.show()

        MatrixKernel = self.Gamma(self.Mdist)

        print()
        print('The distance between two consecutive place fields is',
              self.PFspacing, 'cm. We have in total', len(self.PFpositions),
              'place fields.')
        print()
        print('And the respective Kernel in the matrix form will be:')

        #Plot Kernel Matrix
        plt.figure(figsize=(6, 6))
        plt.imshow(MatrixKernel, cmap='jet')  # viridis, inferno, magma
        plt.tick_params(labelsize=23)
        cb = plt.colorbar()
        cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=23)
        plt.title('$\Gamma_{matrix}$', fontsize=30)
        plt.show()
        #Further details on the Kernel Matrix

        print()
        print('We plot the Symmetric part of the Matrix as well:')
        plt.imshow((MatrixKernel + MatrixKernel.T) / 2, cmap='jet')
        plt.tick_params(labelsize=23)
        cb = plt.colorbar()
        cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=23)
        plt.title('Symm. Part', fontsize=25)
        plt.show()

        print()
        print('Also we plot the Antisymmetric part of the Matrix as well:')
        plt.imshow((MatrixKernel - MatrixKernel.T) / 2, cmap='jet')
        plt.tick_params(labelsize=23)
        cb = plt.colorbar()
        cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=23)
        plt.title('Anti. Part', fontsize=25)
        plt.show()

        # Now we write the time evolution of the weights

        if Inhibition == 'N':

            Average = input('Average weights over time? Yes=Y, No=N: ')

            print()
            print()
            print('We generate random initial weights:')

            J0 = 1 + 0.1 * random.rand(
                len(self.PFpositions
                    ))  # We generate a vector J of random synaptic weights
            #J0 = J0/sqrt(sum(J0**2))                                           # We normalize them

            plt.figure(figsize=(20, 5))
            plt.scatter(self.PFpositions, J0)
            plt.plot(self.PFpositions, J0)
            plt.tick_params(labelsize=30)
            plt.xlim(0, +self.Length)
            plt.ylim(0)
            plt.xlabel('Place Cells (blue dots) over Linear Track (cm)',
                       fontsize=30)
            plt.ylabel('Initial Synaptic Weight', fontsize=30)
            plt.show()

            t = 0
            dt = 0.001
            J = J0
            Jvec = [J0]

            #String of weights
            X = [J[0]]
            Y = [J[25]]
            Z = [J[50]]

            # String of averaged weights
            A = []
            B = []
            C = []

            if Average == 'N':  #No Average
                while t < self.Time:
                    t = dt + t
                    J = J + dt * (dot(MatrixKernel, J) - J**2
                                  )  #   - dot(J,J) )
                    J[J < 0] = 0  # Positivity constrain
                    #J[J>1]=1

                    X.append(
                        J[0]
                    )  # The intention is to plot this X against time, and see if the weights are stable on time
                    Y.append(J[25])
                    Z.append(
                        J[50]
                    )  # The intention is to plot this X against time, and see if the weights are stable on time

                print('After learning, the pattern looks like this:')

                plt.figure(figsize=(20, 5))
                plt.scatter(self.PFpositions, J)
                plt.plot(self.PFpositions, J)
                plt.tick_params(labelsize=30)
                plt.xlim(0, +self.Length)
                #plt.ylim(0)
                plt.xlabel('Place Cells (blue dots) over Linear Track (cm)',
                           fontsize=30)
                plt.ylabel('Final Synaptic Weight', fontsize=30)
                plt.show()

                print()
                print()
                print(
                    'We want to see the time evolution of several individual cell weights along the path. We selected 2 of them:'
                )

                lx = int(len(X) / 8)
                ly = int(len(Y) / 8)
                lz = int(len(Z) / 8)
                X = X[2 * lx:3 * lx]
                Y = Y[2 * ly:3 * ly]
                Z = Z[2 * lz:3 * lz]
                timex = arange(
                    2 * lx * dt, 3 * lx * dt,
                    dt)  #Appropiate spacing for the x-axis to be Time

                # timex = arange(0,len(X)*dt,dt)

                #Temporal Evolution
                plt.figure(figsize=(20, 5))
                #Neuron no. 0
                plt.plot(timex, X, label='Cell x=0', lw=2, color='darkgreen')
                #Neuron no. 25
                plt.plot(timex, Y, label='Cell x=50', lw=2, color='darkred')
                #Neuron no. 50
                plt.plot(timex,
                         Z,
                         label='Cell x=100',
                         lw=2,
                         color='darkorange')
                plt.tick_params(labelsize=30)
                plt.xlabel('Time (s)', fontsize=30)
                plt.ylabel('Synaptic Weight', fontsize=30)
                plt.legend(frameon=True, prop={'size': 30})
                plt.show()

            if Average == 'Y':  #Averaged
                while t < self.Time:

                    step = self.step

                    t = t + dt

                    J = J + dt * (dot(MatrixKernel, J) - J**2)
                    Jvec.append(J)
                    J[J < 0] = 0  # Positivity constrain

                    X.append(J[0])
                    Y.append(J[25])
                    Z.append(J[50])

                    if t % step <= dt:  # Loop to store J after a certain number of steps - CELL 0

                        Javg = np.average(np.array(Jvec), axis=0)

                        A.append(
                            Javg[0]
                        )  # The intention is to plot this X against time, and see if the weights are stable on time
                        B.append(
                            Javg[25]
                        )  # The intention is to plot this X against time, and see if the weights are stable on time
                        C.append(Javg[50])

                        J = Javg
                        Jvec = []

                print('After learning, the pattern looks like this:')

                plt.figure(figsize=(20, 5))
                plt.scatter(self.PFpositions, J)
                plt.plot(self.PFpositions, J)
                plt.tick_params(labelsize=30)
                plt.xlim(0, +self.Length)
                #plt.ylim(0)
                plt.xlabel('Place Cells (blue dots) over Linear Track (cm)',
                           fontsize=30)
                plt.ylabel('Averaged Synaptic Weights', fontsize=30)
                plt.show()

                print()
                print()
                print(
                    'We want to see the time evolution of several individual cell weights along the path. We selected 2 of them:'
                )

                la = int(len(A) / 8)
                lb = int(len(B) / 8)
                lc = int(len(C) / 8)
                A = A[2 * la:3 * la]
                B = B[2 * la:3 * lb]
                C = C[2 * la:3 * lc]

                stepx = arange(
                    2 * la * step, 3 * la * step,
                    step)  #Appropiate spacing for the x-axis to be Time

                #Temporal Evolution
                plt.figure(figsize=(20, 5))
                plt.plot(stepx,
                         A,
                         label='Cell x=0 avg',
                         lw=3,
                         color='darkgreen')
                plt.tick_params(labelsize=30)
                plt.xlabel('Time (s)', fontsize=30)
                plt.ylabel('Synaptic Weights', fontsize=30)
                plt.plot(stepx,
                         B,
                         label='Cell x=50 avg',
                         lw=3,
                         color='darkred')
                plt.plot(stepx,
                         C,
                         label='Cell x=100 avg',
                         lw=3,
                         color='darkorange')
                plt.legend(frameon=True, prop={'size': 30})
                plt.show()

        elif Inhibition == 'Y':

            dP = len(self.PFpositions)  # Number of Place Cells
            dG = 100  # Number of Grid Cells that will inhibit each other

            J = 1 / dP * (
                np.ones((dG, dP)) + 0.1 * np.random.randn(dG, dP)
            )  # Initial Random Weight Matrix - From Place Cells to Grid Cell
            #M=-1/dG*( np.ones((dG,dG)) + 0.1*np.random.randn(dG,dG) )          # Inhibition Matrix - No Sparsed

            M0 = scipy.sparse.random(
                dG, dG, .1)  # Inhibition Matrix - Sparsed (all 3 lines)
            M0 = M0 != 0
            M = -10 * (M0 + 0.1 * np.random.randn(dG, dG))

            plt.figure(figsize=(20, 5))
            plt.scatter(self.PFpositions, J[0])
            plt.plot(self.PFpositions, J[0])
            plt.xlim(0, +self.Length)
            plt.ylim(0)
            plt.title('Initial Weight Distribution (Randomized)')
            plt.xlabel('Place Cells (blue dots) over Linear Track (cm)')
            plt.ylabel('Synaptic Weight')
            plt.show()

            J = np.matrix(J)
            M = np.matrix(M)

            MI = (np.matrix(np.identity(dG)) - M)
            MI = MI.I

            print('')
            print('Now we plot the matrix MI:')
            plt.imshow(MI, cmap='viridis')  # viridis, inferno, magma
            plt.colorbar()
            plt.show()

            t = 0
            dt = 0.001

            X = [J[0, 0]]
            Y = [J[0, 50]]

            #if Average=='N':
            while t < self.Time:

                t = dt + t
                J = J + dt * (
                    MI * J * MatrixKernel - np.matrix((J.A)**2)
                )  # .A is just transforming matrix into array, to be able to perform **2

                #J=np.matrix((J.A)*(J.A>0))
                J[J < 0] = 0  # Positivity constrain
                #J[J>1]=0

                X.append(
                    J[0, 0]
                )  # The intention is to plot this X against time, and see if the weights are stable on time
                Y.append(
                    J[0, 50]
                )  # The intention is to plot this X against time, and see if the weights are stable on time

            J = array(J)

            plt.figure(figsize=(20, 5))
            plt.scatter(self.PFpositions, J[0])
            plt.plot(self.PFpositions, J[0])
            plt.xlim(0, +self.Length)
            plt.tick_params(labelsize=30)
            #plt.ylim(0)
            plt.xlabel('Place Cells (blue dots) over Linear Track (cm)',
                       fontsize=30)
            plt.ylabel('Final Synaptic Weight', fontsize=30)
            plt.show()

            plt.figure(figsize=(20, 5))
            plt.scatter(self.PFpositions, J[23])
            plt.plot(self.PFpositions, J[23])
            plt.xlim(0, +self.Length)
            plt.tick_params(labelsize=30)
            #plt.ylim(0)
            plt.xlabel('Place Cells (blue dots) over Linear Track (cm)',
                       fontsize=30)
            plt.ylabel('Final Synaptic Weight', fontsize=30)
            plt.show()

            plt.figure(figsize=(20, 5))
            plt.scatter(self.PFpositions, J[57])
            plt.plot(self.PFpositions, J[57])
            plt.xlim(0, +self.Length)
            plt.tick_params(labelsize=30)
            #plt.ylim(0)
            plt.xlabel('Place Cells (blue dots) over Linear Track (cm)',
                       fontsize=30)
            plt.ylabel('Final Synaptic Weight', fontsize=30)
            plt.show()

            plt.figure(figsize=(20, 5))
            plt.scatter(self.PFpositions, J[81])
            plt.plot(self.PFpositions, J[81])
            plt.xlim(0, +self.Length)
            plt.tick_params(labelsize=30)
            #plt.ylim(0)
            plt.xlabel('Place Cells (blue dots) over Linear Track (cm)',
                       fontsize=30)
            plt.ylabel('Final Synaptic Weight', fontsize=30)
            plt.show()

            timex = arange(0,
                           len(X) * dt,
                           dt)  #Appropiate spacing for the x-axis to be Time

            #Neuron 0
            plt.figure(figsize=(20, 5))
            plt.plot(timex, X, label='Cell 0 - Avg')
            plt.title('Temporal Evolution of the Synaptic Weights of Cells 0')
            #plt.ylim(0)
            plt.xlabel('Time (s)')
            plt.ylabel('Synaptic Weight')
            plt.legend(frameon=True)
            plt.show()

            #Neuron 50
            plt.figure(figsize=(20, 5))
            plt.plot(timex, Y, label='Cell 50 - Avg')
            plt.title('Temporal Evolution of the Synaptic Weights of Cells 50')
            #plt.ylim(0)
            plt.xlabel('Time (s)')
            plt.ylabel('Synaptic Weight')
            plt.legend(frameon=True)
            plt.show()

#==============================================================================
#             Y.append(J[13,50])
#
#             plt.figure(figsize=(20,5))
#             plt.scatter(self.PFpositions,J[13])
#             plt.plot(self.PFpositions,J[13])
#             plt.xlim(0,+self.Length)
#             #plt.ylim(0)
#             plt.title('Final Pattern')
#             plt.xlabel('Place Cells over Linear Path (Blue Dots)')
#             plt.ylabel
#
#             #Neuron 50
#             plt.figure(figsize=(20,5))
#             plt.plot(timex,Y,label='Cell 50 - Avg')
#             plt.title('Temporal Evolution of the Synaptic Weights of Cells 50')
#             #plt.ylim(0)
#             plt.xlabel('Time (s)')
#             plt.ylabel('Synaptic Weight')
#             plt.legend(frameon=True)
#             plt.show()
#
#             Y.append(J[24,50])
#
#             plt.figure(figsize=(20,5))
#             plt.scatter(self.PFpositions,J[24])
#             plt.plot(self.PFpositions,J[24])
#             plt.xlim(0,+self.Length)
#             #plt.ylim(0)
#             plt.title('Final Pattern')
#             plt.xlabel('Place Cells over Linear Path (Blue Dots)')
#             plt.ylabel
#
#             #Neuron 50
#             plt.figure(figsize=(20,5))
#             plt.plot(timex,Y,label='Cell 50 - Avg')
#             plt.title('Temporal Evolution of the Synaptic Weights of Cells 50')
#             #plt.ylim(0)
#             plt.xlabel('Time (s)')
#             plt.ylabel('Synaptic Weight')
#             plt.legend(frameon=True)
#             plt.show()
#
#             Y.append(J[67,50])
#
#             plt.figure(figsize=(20,5))
#             plt.scatter(self.PFpositions,J[67])
#             plt.plot(self.PFpositions,J[67])
#             plt.xlim(0,+self.Length)
#             #plt.ylim(0)
#             plt.title('Final Pattern')
#             plt.xlabel('Place Cells over Linear Path (Blue Dots)')
#             plt.ylabel
#
#             #Neuron 50
#             plt.figure(figsize=(20,5))
#             plt.plot(timex,Y,label='Cell 50 - Avg')
#             plt.title('Temporal Evolution of the Synaptic Weights of Cells 50')
#             #plt.ylim(0)
#             plt.xlabel('Time (s)')
#             plt.ylabel('Synaptic Weight')
#             plt.legend(frameon=True)
#             plt.show()
#==============================================================================

        else:
            print('In the input, please insert only Y or N')
示例#57
0
def update(cur):
    fr = rand(1,5)
    to = rand(1,5)
    cur.execute(
        "UPDATE users SET projid=%d WHERE projid=%d" % (to, fr))
    return fr, to, getRC(cur)
示例#58
0
def gen_passwd():
    p = ""
    for _ in range(rand(6, 10)):
        p += choice(string.ascii_lowercase + string.digits)
    return p
示例#59
0
 def _getNextPiece(self):
     stop = len(tetris_shapes) if self._doEvil else 7
     return tetris_shapes[rand(0, stop)]
示例#60
0
 def insert(self):
     self.ses.add_all(
         Users(login=who, userid=userid, projid=rand(1, 5))
         for who, userid in randName())
     self.ses.commit()