Python random.random() Examples

The following are code examples for showing how to use random.random(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: RunescapeBots   Author: lukegarbutt   File: GeMercher.py    (license) View Source Project 11 votes vote down vote up
def wait_for(image, runescape_window):
	# adding a possible failsafe in here
	time_entered = time.time()
	# could add a failsafe in here incase we misclick or something, this
	# should be something to come back to
	failsafe_count = 0
	while(True):
		found = pyautogui.locateOnScreen(image, region=(runescape_window.top_left_corner[0], runescape_window.top_left_corner[1], runescape_window.bottom_right_corner[
										 0] - runescape_window.top_left_corner[0], runescape_window.bottom_right_corner[1] - runescape_window.top_left_corner[1]))
		if found != None:
			break
		elif failsafe_count > 10:
			print("We can't seem to fix the problem so the script is now aborting")
			quit()
		elif time.time()-time_entered > 5 :
			failsafe_count += 1
			print('We appear to be stuck so attempting to move the mouse and see if this fixes it')
			#print('For debug:')
			#print(runescape_window.bottom_right_corner[0], runescape_window.top_left_corner[0])
			#print(runescape_window.bottom_right_corner[1], runescape_window.top_left_corner[1])
			realmouse.move_mouse_to(random.randint(runescape_window.top_left_corner[0], runescape_window.bottom_right_corner[0]), random.randint(runescape_window.top_left_corner[1], runescape_window.bottom_right_corner[1]))
			#pyautogui.click()
			time_entered = time.time() 
Example 2
Project: django-performance-testing   Author: PaesslerAG   File: queries.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def get_sample_results(cls):
        read = """QUERY - 'SELECT "auth_user"."id" FROM "auth_group"'""" \
            """- PARAMS = ()"""
        write = """QUERY - 'UPDATE "auth_group" SET "name" = %s'""" \
            """- PARAMS = ('bar',)"""
        other = """QUERY - 'BEGIN TRANSACTION' - PARAMS = ()"""

        def to_query(sql):
            return {'sql': sql, 'time': '%.3f' % random.random()}

        def to_single_result(*sqls):
            qc = cls()
            qc.queries = [to_query(sql) for sql in sqls]
            return qc.get_results_to_send()

        return [
            to_single_result(*sqls)
            for sqls in [
                [read], [read, write], [read, read], [write, write],
                [other, other], [read, write, other]
            ]
        ] 
Example 3
Project: tree-gen   Author: friggog   File: quaking_aspen.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def system():
    """initialize and iterate the system as appropriate"""
    axiom = []
    con = int(__base_length__ / 0.1)
    s = random() * 0.2 + 0.9
    for ind in range(con):
        axiom.append(LSymbol("!", {"w": s * (__base_width__ + ((con - ind) / con) ** 6 * 0.2)}))
        axiom.append(LSymbol("F", {"l": s * 0.1}))
    axiom.append(LSymbol("Q", {"w": s * __base_width__, "l": s * 0.1}))
    l_sys = LSystem(axiom=axiom,
                    rules={"Q": q_prod, "A": a_prod},
                    tropism=Vector([0, 0, 0.2]),
                    thickness=0.5,
                    bendiness=0,
                    leaf_shape=3,
                    leaf_scale=0.17,
                    leaf_bend=0.2)
    l_sys.iterate_n(12)
    return l_sys 
Example 4
Project: tree-gen   Author: friggog   File: lombardy_poplar.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def q_prod(sym):
    """Production rule for Q"""
    ret = []
    prev_ang = 0
    for _ in range(int(random() * 2 + 3)):
        ang = random() * 10 + 30
        ret.extend([LSymbol("/", {"a": prev_ang + 75 + random() * 10}),
                    LSymbol("&", {"a": ang}),
                    LSymbol("!", {"w": sym.parameters["w"] * 0.2}),
                    LSymbol("["),
                    LSymbol("A", {"w": sym.parameters["w"] * 0.3,
                                  "l": 1.5 * sqrt(sym.parameters["w"]) * (random() * 0.2 + 0.9)}),
                    LSymbol("]"),
                    LSymbol("!", {"w": sym.parameters["w"]}),
                    LSymbol("^", {"a": ang}),
                    LSymbol("F", {"l": sym.parameters["l"]})])
    ret.append(LSymbol("Q", {"w": max(0, sym.parameters["w"] - __base_width__ / 14),
                             "l": sym.parameters["l"]}))
    return ret 
Example 5
Project: variational-text-tensorflow   Author: carpedm20   File: toy_generator.py    (MIT License) View Source Project 6 votes vote down vote up
def get_neighbors(words, word, window_size=2):
  if type(word) == str:
    idx = words.index(word)
  elif type(word) == int:
    idx = word
  else:
    raise Exception(" [!] Invalid type for word: %s" % type(word))

  if idx < window_size:
    ans = words[-(window_size - idx):] + words[:idx + window_size + 1]
  elif idx >= len(words) - window_size:
    ans = words[idx-window_size:] + words[:window_size + idx - len(words) + 1]
  else:
    ans = words[idx-window_size:idx+window_size+1]

  for _ in xrange(15):
    if random.random() < 0.1:
      ans.append(random.choice(ans))

  random.shuffle(ans)
  return ans 
Example 6
Project: Modeling_Preparation   Author: Yangruipis   File: genetic_algorithm.py    (license) View Source Project 6 votes vote down vote up
def begin(self):
        for i in range(1000):
            index1 = self.choose_gene(random.random())
            index2 = self.choose_gene(random.random())
            while index1 == index2:
                index2 = self.choose_gene(random.random())

            if random.random() < self.mutation_prob:
                self.genes[index1].mutation()
                self.genes[index2].mutation()

            if random.random() < self.cross_prob:
                Gene.cross(self.genes[index1], self.genes[index2])

            self.get_fit_value()
            # self.gene_pop()

            result = self.get_best_gene()
            print len(self.genes), result[0].bin2dec(), result[1] 
Example 7
Project: Modeling_Preparation   Author: Yangruipis   File: simulated_annealing.py    (license) View Source Project 6 votes vote down vote up
def begin(self):
        x = random.randint(self.x_range[0], self.x_range[1])
        f = self.func(x)
        T = self.T0
        while T > self.T_min:
            for i in range(self.K):
                new_x = self.gen_new_x(x, T)
                f_x = self.func(new_x)
                delta_E = f_x - f
                #
                if delta_E < 0:
                    f = f_x
                    x = new_x
                    break
                else:
                    #p_k = 1.0 / (1 + np.exp(- delta_E / self.func(T)))
                    p_k = np.exp(- delta_E / T)
                    if random.random() < p_k:
                        f = f_x
                        x = new_x
                        break
            T *= self.delta

        return x 
Example 8
Project: IotCenter   Author: panjanek   File: display.py    (MIT License) View Source Project 6 votes vote down vote up
def repeat(self):
        while True:
            try:
                self.displayTime()
                if (datetime.datetime.now() - self.sensor1ts).total_seconds() > self.expirationSeconds:
                    self.canvas.itemconfigure(self.txtSensor1, text="")
                    self.canvas.itemconfigure(self.txtSensor1BigIcon, text="")
                if (datetime.datetime.now() - self.sensor2ts).total_seconds() > self.expirationSeconds:
                    self.canvas.itemconfigure(self.txtSensor2, text="")      
                    self.canvas.itemconfigure(self.txtSensor2BigIcon, text="")                    
                
                #t = random.random()*60-20
                #self.displaySensor1(t, "test")
            except Exception as e:    
                self.logger.exception(e)
            except:
                pass
            time.sleep(1) 
Example 9
Project: pytorch-semseg   Author: meetshah1995   File: augmentations.py    (MIT License) View Source Project 6 votes vote down vote up
def __call__(self, img, mask):
        if self.padding > 0:
            img = ImageOps.expand(img, border=self.padding, fill=0)
            mask = ImageOps.expand(mask, border=self.padding, fill=0)

        assert img.size == mask.size
        w, h = img.size
        th, tw = self.size
        if w == tw and h == th:
            return img, mask
        if w < tw or h < th:
            return img.resize((tw, th), Image.BILINEAR), mask.resize((tw, th), Image.NEAREST)

        x1 = random.randint(0, w - tw)
        y1 = random.randint(0, h - th)
        return img.crop((x1, y1, x1 + tw, y1 + th)), mask.crop((x1, y1, x1 + tw, y1 + th)) 
Example 10
Project: RunescapeBots   Author: lukegarbutt   File: GeMercher.py    (license) View Source Project 6 votes vote down vote up
def cancel_offer(top_left_corner, bottom_right_corner, runescape_window):
	loc_of_ge_point = pointfrombox.random_point(top_left_corner, bottom_right_corner)
	realmouse.move_mouse_to(loc_of_ge_point[0], loc_of_ge_point[1])
	pyautogui.click()
	# print('now waiting and then trying to locate x button')
	# wait_for('Tools/screenshots/abort_x_button.png', runescape_window)
	time.sleep(3+random.random())
	fail_count = 0
	# print('We are about to cancel an offer that we believe to be in the window with coords {}, we are at line 497'.format(runescape_window.bottom_right_corner))
	while True:
		cancel_loc = pyautogui.locateOnScreen('Tools/screenshots/abort_x_button.png', region=(runescape_window.top_left_corner[0], runescape_window.top_left_corner[1], runescape_window.bottom_right_corner[0]-runescape_window.top_left_corner[0], runescape_window.bottom_right_corner[1]-runescape_window.top_left_corner[1]))
		if fail_count > 3:
			print('failed 3 times so trying to locate the abort button from the inventory collect button')
			to_inv_loc = pyautogui.locateOnScreen('Tools/screenshots/to_inv_button.png', region=(runescape_window.top_left_corner[0], runescape_window.top_left_corner[1], runescape_window.bottom_right_corner[0]-runescape_window.top_left_corner[0], runescape_window.bottom_right_corner[1]-runescape_window.top_left_corner[1]))
			cancel_loc = tuple(numpy.subtract(to_inv_loc, (163, 107, 163, 8)))
		if cancel_loc == None:
			print('Failed to locate the abort button {} times, trying again in 5 seconds'.format(fail_count))
			time.sleep(5)
			fail_count += 1
		else:
			break
	# print('we have saved the location of the x button ready to click')
	# print(cancel_loc)
	point_of_cancel_button = pointfrombox.random_point((cancel_loc[0], cancel_loc[1]), (cancel_loc[0]+cancel_loc[2], cancel_loc[1]+cancel_loc[3]))
	realmouse.move_mouse_to(point_of_cancel_button[0], point_of_cancel_button[1])
	pyautogui.click() 
Example 11
Project: RunescapeBots   Author: lukegarbutt   File: GeMercher.py    (license) View Source Project 6 votes vote down vote up
def prevent_logout(top_left_corner, bottom_right_corner, runescape_window):
	seed = random.random()
	x, y = pyautogui.size()
	if seed > 0.5:  # opens up the sale history tab for 5 seconds then returns to ge tab
		while(True):
			realmouse.move_mouse_to(random.randint(0,x), random.randint(0,y))
			if len(list(pyautogui.locateAllOnScreen('Tools/screenshots/sale_history_button.png', region=(top_left_corner[0], top_left_corner[1], bottom_right_corner[0]-top_left_corner[0], bottom_right_corner[1]-top_left_corner[1]))))>0:
				move_mouse_to_box('Tools/screenshots/sale_history_button.png', top_left_corner, bottom_right_corner)
				pyautogui.click()
				time.sleep(9*random.random()+1)
				move_mouse_to_box('Tools/screenshots/grand_exchange_button.png', top_left_corner, bottom_right_corner)
				pyautogui.click()
				break
	else:  # examines the money pouch
		examine_money(bottom_right_corner)

# pass in an image and a search region 
Example 12
Project: RunescapeBots   Author: lukegarbutt   File: realmouse.py    (license) View Source Project 6 votes vote down vote up
def move_mouse_to(x, y):
	"""Function to simulate realistic mouse movements in python. The objective of this
	 will be to take in coordinates x,y and move them in a realistic manner. We
	 will be passing in an x,y,  that is already 'random' so this function will
	 move to the exact x,y"""
	# takes current mouse location and stores it
	while(True):
		try:
			curr_x, curr_y = pyautogui.position()
			# calculates the distance from current position to target position
			distance = int(((x - curr_x)**2 + (y - curr_y)**2)**0.5)
			# calculates a random time to make the move take based on the distance
			duration_of_move = (distance * random.random() / 2000) + 0.5
			# move the mouse to our position and takes the time of our duration just
			# calculated
			pyautogui.moveTo(x, y, duration_of_move, pyautogui.easeInOutQuad)
			#pyautogui.moveTo(x, y, duration_of_move, pyautogui.easeOutElastic)
			break
		except:
			print('paused for 10 seconds')
			time.sleep(10) 
Example 13
Project: distributional_perspective_on_RL   Author: Kiwoo   File: replay_buffer.py    (license) View Source Project 6 votes vote down vote up
def sample(self, batch_size):
        """Sample a batch of experiences.

        Parameters
        ----------
        batch_size: int
            How many transitions to sample.

        Returns
        -------
        obs_batch: np.array
            batch of observations
        act_batch: np.array
            batch of actions executed given obs_batch
        rew_batch: np.array
            rewards received as results of executing act_batch
        next_obs_batch: np.array
            next set of observations seen after executing act_batch
        done_mask: np.array
            done_mask[i] = 1 if executing act_batch[i] resulted in
            the end of an episode and 0 otherwise.
        """
        idxes = [random.randint(0, len(self._storage) - 1) for _ in range(batch_size)]
        return self._encode_sample(idxes) 
Example 14
Project: npstreams   Author: LaurentRDC   File: test_stats.py    (license) View Source Project 6 votes vote down vote up
def test_against_numpy_nanstd(self):
        source = [np.random.random((16, 12, 5)) for _ in range(10)]
        for arr in source:
            arr[randint(0, 15), randint(0, 11), randint(0, 4)] = np.nan
        stack = np.stack(source, axis = -1)

        for axis in (0, 1, 2, None):
            for ddof in range(4):
                with self.subTest('axis = {}, ddof = {}'.format(axis, ddof)):
                    from_numpy = np.nanstd(stack, axis = axis, ddof = ddof)
                    from_ivar = last(istd(source, axis = axis, ddof = ddof, ignore_nan = True))
                    self.assertSequenceEqual(from_numpy.shape, from_ivar.shape)
                    self.assertTrue(np.allclose(from_ivar, from_numpy)) 
Example 15
Project: cellranger   Author: 10XGenomics   File: bam.py    (license) View Source Project 6 votes vote down vote up
def downsample_bam(in_name, out_name, downsample_rate, restrict_chrom=None):
	""" Downsamples a bam.  Optionally also restricts the output to a single chromosome.
	"""
	f = create_bam_infile(in_name)
	g, tids = create_bam_outfile(out_name, None, None, template=f)

	if restrict_chrom is None:
		bam_iter = f
	else:
		bam_iter = f.fetch(restrict_chrom)

	should_write = {}
	for r in bam_iter:
		if should_write.has_key(r.qname):
			if should_write[r.qname]:
				g.write(r)
		else:
			if random.random() < downsample_rate:
				should_write[r.qname] = True
				g.write(r)
			else:
				should_write[r.qname] = False
	g.close() 
Example 16
Project: scikit-dataaccess   Author: MITHaystack   File: param_class.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, val_init, val_min, val_max, decimals=0, extreme=0):
        ''' 
        Construct AutoParamMinMax object

        @param val_init: Initial value for parameter
        @param val_min: Minimum value for param
        @param val_max: Maximum value for parameter
        @param decimals: Number of decimals to include in the random number
        @param extreme: Either the maximum or minimum is chosen every
                        extreme number of iterations. Using a value of
                        one will be an extreme value every time.
                        Using a value of zero will always choose a
                        random value.
        
        '''
        self.val        = val_init
        self.val_init   = val_init        
        self.val_min    = val_min
        self.val_max    = val_max
        self.n = 0
        self.n_max = extreme
        self.decimals = decimals 
Example 17
Project: scikit-dataaccess   Author: MITHaystack   File: param_class.py    (MIT License) View Source Project 6 votes vote down vote up
def perturb(self):
        ''' 
        Peturb the paramter by choosing a random value between val_min and val_max. 

        Will choose a random number with precision specified by decimals. Will optionally
        pick the min or the max value after a specified number of perturb calls
        '''

        if self.n == self.n_max - 1:
            # Choose and extreme value
            self.val = random.sample([self.val_min, self.val_max], 1)[0]
            self.n = 0

        else:
            if self.decimals == 0:
                self.val = random.randint(self.val_min,self.val_max)
            else:
                self.val = random.random() * (self.val_max - self.val_min + 10**-self.decimals) + (self.val_min - 0.5 * 10**-self.decimals)
                self.val = round(self.val, ndigits=self.decimals)

            if self.n_max > 0:
                self.n += 1 
Example 18
Project: kinect-2-libras   Author: inessadl   File: threading.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __bootstrap(self):
        # Wrapper around the real bootstrap code that ignores
        # exceptions during interpreter cleanup.  Those typically
        # happen when a daemon thread wakes up at an unfortunate
        # moment, finds the world around it destroyed, and raises some
        # random exception *** while trying to report the exception in
        # __bootstrap_inner() below ***.  Those random exceptions
        # don't help anybody, and they confuse users, so we suppress
        # them.  We suppress them only when it appears that the world
        # indeed has already been destroyed, so that exceptions in
        # __bootstrap_inner() during normal business hours are properly
        # reported.  Also, we only suppress them for daemonic threads;
        # if a non-daemonic encounters this, something else is wrong.
        try:
            self.__bootstrap_inner()
        except:
            if self.__daemonic and _sys is None:
                return
            raise 
Example 19
Project: plugin.video.exodus   Author: lastship   File: proxy.py    (license) View Source Project 6 votes vote down vote up
def request(url, check, close=True, redirect=True, error=False, proxy=None, post=None, headers=None, mobile=False, XHR=False, limit=None, referer=None, cookie=None, timeout='30'):
    try:

        r = client.request(url, close=close, redirect=redirect, proxy=proxy, post=post, headers=headers, mobile=mobile, XHR=XHR, limit=limit, referer=referer, cookie=cookie, timeout=timeout)
        if r == None and error == False: return r
        if check in str(r) or str(r) == '': return r


        proxies = sorted(get(), key=lambda x: random.random())
        proxies = sorted(proxies, key=lambda x: random.random())
        proxies = proxies[:3]

        for p in proxies:
            p += urllib.quote_plus(url)
            if not post == None: p += urllib.quote_plus('?%s' % post)
            r = client.request(p, close=close, redirect=redirect, proxy=proxy, headers=headers, mobile=mobile, XHR=XHR, limit=limit, referer=referer, cookie=cookie, timeout='20')
            if check in str(r) or str(r) == '': return r

    except:
        pass 
Example 20
Project: plugin.video.exodus   Author: lastship   File: proxy.py    (license) View Source Project 6 votes vote down vote up
def geturl(url):
    try:
        r = client.request(url, output='geturl')
        if r == None: return r

        host1 = re.findall('([\w]+)[.][\w]+$', urlparse.urlparse(url.strip().lower()).netloc)[0]
        host2 = re.findall('([\w]+)[.][\w]+$', urlparse.urlparse(r.strip().lower()).netloc)[0]
        if host1 == host2: return r

        proxies = sorted(get(), key=lambda x: random.random())
        proxies = sorted(proxies, key=lambda x: random.random())
        proxies = proxies[:3]

        for p in proxies:
            p += urllib.quote_plus(url)
            r = client.request(p, output='geturl')
            if not r == None: return parse(r)

    except:
        pass 
Example 21
Project: GraphTime   Author: GlooperLabs   File: simulate.py    (license) View Source Project 6 votes vote down vote up
def generate_graphs(self, n_edges_list, use_seed=True):
        """For each number of edges (n_edges) in n_edges_list create
        an Erdos Renyi Precision Graph that allows us to sample
        from later.

        Parameters
        ----------
        n_edges : list[int] or int
            list of number of edges for each graph or scalar
            if only one graph is wanted
        use_seed : bool
            indicates if seed shall be reset
        """
        if use_seed and self.seed is not None:
            random.seed(self.seed)

        n_edges = n_edges_list if type(n_edges_list) is list \
            else [n_edges_list]

        self.graphs = [ErdosRenyiPrecisionGraph(self.n_vertices, n_es)
                       for n_es in n_edges] 
Example 22
Project: encore.ai   Author: dyelax   File: get_song_lyrics.py    (MIT License) View Source Project 6 votes vote down vote up
def download_lyrics(artist, url):
  print url
  time.sleep(random() + 2)
  page = urllib2.urlopen(url).read()
  soup = BeautifulSoup(page, 'html.parser')

  # Get the song title
  song_title = soup.find('title').get_text().split(' - ')[1].lower().replace('/', ' ').replace(' ', '_')

  # Get the lyrics div
  lyrics = soup.findAll('div', {'class': ''})

  for i in lyrics:
    lyrics = i.get_text().strip()
    if len(lyrics) > 10:
      with open('artists/' + artist + '/' + song_title + '.txt', 'wb') as w:
        cleaned_lyrics = lyrics.replace('\r\n', ' *BREAK* ').replace('\n', ' *BREAK* ').replace('  ', ' ')
        w.write(cleaned_lyrics.encode('utf-8')) 
Example 23
Project: encore.ai   Author: dyelax   File: get_all_songs.py    (MIT License) View Source Project 6 votes vote down vote up
def download_songs(url):
  time.sleep(random.random() * 0.5)
  try:
    page = urllib2.urlopen(url).read()
    soup = BeautifulSoup(page, 'html.parser')

    # Get the artist name
    artist_name = soup.findAll('h1')[0].get_text()[:-7].lower().replace(' ', '_')

    # Store all songs for a given artist
    with open('artist_data/'+artist_name+'.txt', 'wb') as w:
      for song in soup.findAll('a', {'target': '_blank'}):
        if 'lyrics/' in song['href']:
          song_url = song['href'][1:].strip()
          w.write(song_url + '\n')
  except urllib2.HTTPError:
    print '404 not found' 
Example 24
Project: pogom-linux   Author: PokeHunterProject   File: rpc_api.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, auth_provider, device_info=None):

        self.log = logging.getLogger(__name__)

        self._auth_provider = auth_provider

        # mystical unknown6 - resolved by PokemonGoDev
        self._signal_agglom_gen = False
        self._signature_lib = None

        if RpcApi.START_TIME == 0:
            RpcApi.START_TIME = get_time(ms=True)

        if RpcApi.RPC_ID == 0:
            RpcApi.RPC_ID = int(random.random() * 10 ** 18)
            self.log.debug('Generated new random RPC Request id: %s', RpcApi.RPC_ID)

        # data fields for unknown6
        self.session_hash = os.urandom(32)
        self.token2 = random.randint(1,59)
        self.course = random.uniform(0, 360)

        self.device_info = device_info 
Example 25
Project: oscars2016   Author: 0x0ece   File: http.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE):
    """Constructor.

    Args:
      fd: io.Base or file object, The stream in which to write the downloaded
        bytes.
      request: googleapiclient.http.HttpRequest, the media request to perform in
        chunks.
      chunksize: int, File will be downloaded in chunks of this many bytes.
    """
    self._fd = fd
    self._request = request
    self._uri = request.uri
    self._chunksize = chunksize
    self._progress = 0
    self._total_size = None
    self._done = False

    # Stubs for testing.
    self._sleep = time.sleep
    self._rand = random.random 
Example 26
Project: QUANTAXIS   Author: yutiansut   File: QABid.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, price=16, date='2015-01-05', datetime='2015-01-05 09:01:00', sending_time='2015-01-05 09:01:00', transact_time='', amount=10,
                 towards=1, code='000001', user='root', strategy='example01', btype='0x01', bid_model='strategy', amount_model='amount',
                 order_id=str(random.random()), trade_id='', status='100'):
        self.price = price
        self.date = date
        self.datetime = datetime
        self.sending_time = sending_time  # ????
        self.transact_time = transact_time
        self.amount = amount
        self.towards = towards  # side
        self.code = code
        self.user = user
        self.strategy = strategy
        self.type = btype  # see below
        self.bid_model = strategy
        self.amount_model = amount_model
        self.order_id = order_id
        self.trade_id = trade_id
        self.status = status 
Example 27
Project: Projects   Author: it2school   File: math_test.py    (license) View Source Project 6 votes vote down vote up
def setUp(self):
#        gc.collect()
        self.zeroVec = Vector2()
        self.e1 = Vector2(1, 0)
        self.e2 = Vector2(0, 1)
#        self.t1 = (random(), random())
        self.t1 = (1.2, 3.4)
        self.l1 = list(self.t1)
        self.v1 = Vector2(self.t1)
#        self.t2 = (random(), random())
        self.t2 = (5.6, 7.8)
        self.l2 = list(self.t2)
        self.v2 = Vector2(self.t2)
#        self.s1 = random()
#        self.s2 = random()
        self.s1 = 5.6
        self.s2 = 7.8 
Example 28
Project: attract-repel   Author: nmrksic   File: attract-repel.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def random_different_from(top_range, number_to_not_repeat):

    result = random.randint(0, top_range-1)
    while result == number_to_not_repeat:
        result = random.randint(0, top_range-1)

    return result 
Example 29
Project: Maps   Author: DarkPurple141   File: name_gen.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def __init__(self,location = None):
        random.seed()
        self.name = generate_name()
        self.location = location
        self.cities = [] 
Example 30
Project: Maps   Author: DarkPurple141   File: name_gen.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def generate_name():
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    wordlist = []

    with open ("words", 'r') as fo:
        for word in fo:
            if len(word) < 5:
                continue
            else:
                wordlist.append(word.strip())

    namelength = random.randrange(4)
    pref = random.choice(wordlist)[0:3]
    pref = pref[0].upper() + pref[1:3]

    if random.random() > 0.5:
        suff = random.choice(wordlist)[-3:]
    else:
        suff = random.choice(wordlist)[:3]

    for i in range(namelength):
        pref = pref + random.choice(alphabet)

    name = pref + suff

    return name 
Example 31
Project: uicourses_v2   Author: sumerinlan   File: crawler.py    (license) View Source Project 5 votes vote down vote up
def random_sleep(mean=0.3, tolerance=0.15):
    sleep_time = mean - tolerance + 2 * tolerance * random()
    sleep(sleep_time) 
Example 32
Project: RandTerrainPy   Author: jackromo   File: terraingen.py    (MIT License) View Source Project 5 votes vote down vote up
def _update_square(self, terrain, x, y, square_len):
        """Update the midpoint of a square.

        Midpoint becomes average of square corners plus a random offset determined by noise.

        Args:
            terrain (Terrain): Terrain to update.
            x (int): X coordinate of center of square.
            y (int): Y coordinate of center of square.
            square_len (int): Length of one side of square.

        Returns:
            Terrain: New terrain with updated square center.

        """
        half_len = square_len / 2
        # Impossible to attempt to access neighbours out of terrain bounds
        mean_height = sum([terrain[x - half_len, y - half_len],
                           terrain[x - half_len, y + half_len],
                           terrain[x + half_len, y - half_len],
                           terrain[x + half_len, y + half_len]]) / 4.0
        frequency = terrain.length / square_len
        offset = (random.random() - 0.5) * self.amp_from_freq(frequency)
        if not 0 <= mean_height + offset <= 1:
            if mean_height + offset > 1:
                terrain[x, y] = 1
            else:
                terrain[x, y] = 0
        else:
            terrain[x, y] = mean_height + offset
        return terrain 
Example 33
Project: RandTerrainPy   Author: jackromo   File: terraingen.py    (MIT License) View Source Project 5 votes vote down vote up
def _update_diamond(self, terrain, x, y, diamond_len):
        """Update the midpoint of a diamond.

        Midpoint becomes average of diamond corners plus a random offset determined by noise.

        Args:
            terrain (Terrain): Terrain to update.
            x (int): X coordinate of center of diamond.
            y (int): Y coordinate of center of diamond.
            diamond_len (int): Length of one corner of diamond to other.

        Returns:
            Terrain: New terrain with updated square center.

        """
        half_len = diamond_len / 2
        # If on edge of terrain, only access 3 neighbours to avoid leaving terrain bounds
        neighbours = []
        if x != 0:
            neighbours.append(terrain[x - half_len, y])
        if y != 0:
            neighbours.append(terrain[x, y - half_len])
        if x != terrain.width - 1:
            neighbours.append(terrain[x + half_len, y])
        if y != terrain.length - 1:
            neighbours.append(terrain[x, y + half_len])
        mean_height = sum(neighbours) / float(len(neighbours))
        frequency = terrain.length / diamond_len
        offset = (random.random() - 0.5) * self.amp_from_freq(frequency)
        if not 0 <= mean_height + offset <= 1:
            if mean_height + offset > 1:
                terrain[x, y] = 1
            else:
                terrain[x, y] = 0
        else:
            terrain[x, y] = mean_height + offset
        return terrain 
Example 34
Project: RandTerrainPy   Author: jackromo   File: terraingen.py    (MIT License) View Source Project 5 votes vote down vote up
def _init_gradients(self, vec_magnitude):
        """Initialize all gradient vectors to be in random directions with the same magnitude.

        Args:
            vec_magnitude (float): Magnitude of all gradient vectors.

        """
        self._grad_vecs = [[(0, 0) for _ in range(self._width_in_squares+1)] for _ in range(self._length_in_squares+1)]
        """list[list[tuple(float, float)]]: Grid of gradient vectors."""
        for x in range(self._width_in_squares+1):
            for y in range(self._length_in_squares+1):
                x_val = (random.random() - 0.5) * 2 * vec_magnitude
                y_val = math.sqrt(vec_magnitude**2 - x_val**2) * random.choice([1, -1])
                self._grad_vecs[y][x] = (x_val, y_val) 
Example 35
Project: RandTerrainPy   Author: jackromo   File: terraingen.py    (MIT License) View Source Project 5 votes vote down vote up
def _get_noise_at(self, x, y):
        """Get perlin noise at a point in terrain.

        Does this by choosing a random gradient vector for each grid corner (done at initialization)
        and taking their dot products with the displacement vectors to each point in the grid.
        The generated values are then interpolated between based on distance to each corner from the desired point.

        Args:
            x (int): X coordinate of requested point.
            y (int): Y coordinate of requested point.

        Returns:
            float: Height of point on terrain, between 0 and 1 inclusive.

        """
        grid_x = x / float(self._square_len)    # X value within grid of gradient vectors
        grid_y = y / float(self._square_len)    # Y value within grid of gradient vectors
        left_x, right_x, upper_y, lower_y = self._get_corners(grid_x, grid_y)
        x_weight = grid_x - left_x
        y_weight = grid_y - upper_y
        # ul = upper left, lr = lower right, etc.
        ul_influence_val = self._get_influence_val(left_x, upper_y, grid_x, grid_y)
        ur_influence_val = self._get_influence_val(right_x, upper_y, grid_x, grid_y)
        ll_influence_val = self._get_influence_val(left_x, lower_y, grid_x, grid_y)
        lr_influence_val = self._get_influence_val(right_x, lower_y, grid_x, grid_y)
        # Interpolate between top two and bottom two influence vals, then interpolate between them using y_weight
        upper_influence_val = self._interpolate_between(ul_influence_val, ur_influence_val, x_weight)
        lower_influence_val = self._interpolate_between(ll_influence_val, lr_influence_val, x_weight)
        interpolated_val = self._interpolate_between(upper_influence_val, lower_influence_val, y_weight)
        # Normalize interpolated_val to be between 0 and 1, return as height
        # Can range from 0.5 to -0.5, add 0.5 to achieve proper result
        height = interpolated_val + 0.5
        # Some margin of error, ensure is still between 0 and 1
        return round(height) if not 0 <= height <= 1 else height 
Example 36
Project: cnn-graph-classification   Author: giannisnik   File: utils.py    (license) View Source Project 5 votes vote down vote up
def generate_synthetic():
	import random
	max_nodes=200
	min_nodes=100
	community_num_nodes=10
	graphs=[]
	labels=[]
	com_1= nx.caveman_graph(1, community_num_nodes)
	com_2= nx.star_graph(community_num_nodes)

	for i in range(500):
		num_nodes= random.randint(min_nodes, max_nodes)
		graph= nx.fast_gnp_random_graph(num_nodes, 0.1)
		graph = nx.disjoint_union(graph,com_1)
		for i in range(num_nodes,graph.number_of_nodes()):
			for j in range(num_nodes):
				if random.random() > 0.9:
					graph.add_edge(graph.nodes()[i], graph.nodes()[j])
		graphs.append(graph)
		labels.append(1)
		num_nodes = random.randint(min_nodes, max_nodes)
		graph = nx.fast_gnp_random_graph(num_nodes, 0.1)
		for i in range(num_nodes, graph.number_of_nodes()):
			for j in range(num_nodes):
				if random.random() > 0.9:
					graph.add_edge(graph.nodes[i], graph.nodes[j])
		graphs.append(graph)
		labels.append(0)

	return graphs,labels 
Example 37
Project: Zoom2Youtube   Author: Welltory   File: youtube.py    (MIT License) View Source Project 5 votes vote down vote up
def _real_upload_video(self, insert_request):
        response = None
        error = None
        retry = 0
        print('File upload in progress...', end='')
        while response is None:
            try:
                status, response = insert_request.next_chunk()
                print('.', end='')
                if 'id' in response:
                    print()
                    return response['id']
            except HttpError as err:
                if err.resp.status in RETRIABLE_STATUS_CODES:
                    error = True
                else:
                    raise
            except RETRIABLE_EXCEPTIONS:
                error = True

            if error:
                retry += 1
                if retry > MAX_RETRIES:
                    raise Exception('Maximum retry are fail')

                sleep_seconds = random.random() * 2 ** retry
                time.sleep(sleep_seconds) 
Example 38
Project: tree-gen   Author: friggog   File: chturtle.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def random():
        """Normalised vector containing random entries in all dimensions"""
        vec = Vector([random.random(), random.random(), random.random()])
        vec.normalize()
        return vec 
Example 39
Project: tree-gen   Author: friggog   File: gen.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def rand_for_param_var():
    """Generate random number between -1 and 1"""
    return random.choice([-1, 1]) * rand_in_range(0, 1) 
Example 40
Project: tree-gen   Author: friggog   File: gen.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def rand_in_range(lower, upper):
    """Generate random number between lower and upper"""
    return (random.random() * (upper - lower)) + lower 
Example 41
Project: tree-gen   Author: friggog   File: gen.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def points_for_floor_split(self):
        """Calculate Poissonly distributed points for stem start points"""
        array = []
        # calculate approx spacing radius for dummy stem
        self.tree_scale = self.param.g_scale + self.param.g_scale_v
        stem = Stem(0, None)
        stem.length = self.calc_stem_length(stem)
        rad = 2.5 * self.calc_stem_radius(stem)
        # generate points
        for _ in range(self.param.floor_splits + 1):
            point_ok = False
            while not point_ok:
                # distance from center proportional for number of splits, tree scale and stem radius
                dis = sqrt(rand_in_range(0, 1) * self.param.floor_splits / 2.5 * self.param.g_scale * self.param.ratio)
                # angle random in circle
                theta = rand_in_range(0, 2 * pi)
                pos = Vector([dis * cos(theta), dis * sin(theta), 0])
                # test point against those already in array to ensure it will not intersect
                point_m_ok = True
                for point in array:
                    if (point[0] - pos).magnitude < rad:
                        point_m_ok = False
                        break
                if point_m_ok:
                    point_ok = True
                    array.append((pos, theta))
        return array 
Example 42
Project: tree-gen   Author: friggog   File: gen.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def construct(params, seed=0, render=False, out_path=None):
    """Construct the tree"""
    if seed == 0:
        seed = int(random.random() * 9999999)
        # print('Seed: ', seed)
    random.seed(seed)
    Tree(TreeParam(params)).make()
    if render:
        bpy.data.scenes['Scene'].render.filepath = out_path
        bpy.ops.render.render(write_still=True)

#mod = __import__('ch_trees.parametric.tree_params.quaking_aspen', fromlist=[''])
#reload(mod)
#construct(mod.params) 
Example 43
Project: tree-gen   Author: friggog   File: quaking_aspen.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def q_prod(sym):
    """Production rule for Q"""
    ret = []
    prev_ang = 0
    n = int(random() * 2 + 7)
    for ind in range(8):
        offset = 1 - (__base_width__ - sym.parameters["w"]) / __base_width__
        offset += ind / 8 / 12
        dang = 30 + 85 * offset
        if offset <= 0.7:
            b_len = 0.4 + 0.6 * offset / 0.7
        else:
            b_len = 0.4 + 0.6 * (1.0 - offset) / 0.3
        ret.extend([LSymbol("/", {"a": prev_ang + 75 + random() * 10}),
                    LSymbol("&", {"a": dang}),
                    LSymbol("!", {"w": sym.parameters["w"] * 0.08 * b_len}),
                    LSymbol("["),
                    LSymbol("F", {"l": sym.parameters["w"] / 2}),
                    LSymbol("A", {"w": 0.08 * b_len,
                                  "l": 0.6 * b_len}),
                    LSymbol("]"),
                    LSymbol("!", {"w": sym.parameters["w"]}),
                    LSymbol("^", {"a": dang}),
                    LSymbol("F", {"l": sym.parameters["l"]})])
    ret.append(LSymbol("Q", {"w": max(0, sym.parameters["w"] - __base_width__ / 11),
                             "l": sym.parameters["l"]}))
    return ret 
Example 44
Project: tree-gen   Author: friggog   File: quaking_aspen.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def a_prod(sym):
    """Production rule for A"""
    ret = []
    w_d = sym.parameters["w"] / 14
    prev_rot = 0
    n = int(random() * 3 + 15.5)
    for ind in range(n):
        wid = sym.parameters["w"] - ind * w_d
        l_count = int((sqrt(n - ind) + 2) * 4 * sym.parameters["l"])
        ret.extend([LSymbol("!", {"w": wid}),
                    LSymbol("F", {"l": sym.parameters["l"] / 3}),
                    LSymbol("/", {"a": prev_rot + 140}),
                    LSymbol("&", {"a": 60}),
                    LSymbol("!", {"w": wid * 0.4}),
                    LSymbol("["),
                    LSymbol("F", {"l": sqrt(n - ind) * sym.parameters["l"] / 3,
                                  "leaves": l_count,
                                  "leaf_d_ang": 40,
                                  "leaf_r_ang": 140}),
                    LSymbol("^", {"a": random() * 30 + 30}),
                    LSymbol("F", {"l": sqrt(n - ind) * sym.parameters["l"] / 4,
                                  "leaves": l_count,
                                  "leaf_d_ang": 40,
                                  "leaf_r_ang": 140}),
                    LSymbol("%"),
                    LSymbol("]"),
                    LSymbol("!", {"w": wid}),
                    LSymbol("^", {"a": 60}),
                    LSymbol("\\", {"a": prev_rot + 140}),
                    LSymbol("+", {"a": -5 + random() * 10}),
                    LSymbol("^", {"a": -7.5 + random() * 15})])
        prev_rot += 140
    ret.append(LSymbol("F", {"l": sym.parameters["l"] / 2}))
    return ret 
Example 45
Project: tree-gen   Author: friggog   File: palm.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def q_prod(sym):
    """Production rule for Q"""
    prop_off = sym.parameters["t"] / __t_max__
    if prop_off < 1:
        res = [LSymbol("!", {"w": 0.85 + 0.15 * sin(sym.parameters["t"])}),
               LSymbol("^", {"a": random() - 0.65})]
        if prop_off > __p_max__:
            d_ang = 1 / (1 - __p_max__) * (1 - prop_off) * 110 + 15
            res.extend([LSymbol("!", {"w": 0.1})])
            for ind in range(int(random() * 2 + 5)):
                r_ang = sym.parameters["t"] * 10 + ind * (random() * 50 + 40)
                e_d_ang = d_ang * (random() * 0.4 + 0.8)
                res.extend([LSymbol("/", {"a": r_ang}),
                            LSymbol("&", {"a": e_d_ang}),
                            LSymbol("["),
                            LSymbol("A"),
                            LSymbol("]"),
                            LSymbol("^", {"a": e_d_ang}),
                            LSymbol("\\", {"a": r_ang})],)
            res.append(LSymbol("F", {"l": 0.05}))
        else:
            res.append(LSymbol("F", {"l": 0.15}))
        res.append(LSymbol("Q", {"t": sym.parameters["t"] + __d_t__}))
    else:
        res = [LSymbol("!", {"w": 0}),
               LSymbol("F", {"l": 0.15})]
    return res 
Example 46
Project: tree-gen   Author: friggog   File: palm.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def system():
    """initialize and iterate the system as appropriate"""
    l_sys = LSystem(axiom=[LSymbol("!", {"w": 0.2}),
                           LSymbol("/", {"a": random() * 360}),
                           LSymbol("Q", {"t": 0})],
                    rules={"Q": q_prod, "A": a_prod},
                    tropism=Vector([0, 0, -1]),
                    thickness=0.2,
                    bendiness=0,
                    leaf_shape=10,
                    leaf_scale=1,
                    leaf_scale_x=0.1,
                    leaf_bend=0)
    l_sys.iterate_n(100)
    return l_sys 
Example 47
Project: tree-gen   Author: friggog   File: lombardy_poplar.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def a_prod(sym):
    """Production rule for A"""
    ret = []
    n = int(random() * 5 + 22.5)
    w_d = sym.parameters["w"] / (n - 1)
    prev_rot = 0
    for ind in range(n):
        wid = sym.parameters["w"] - ind * w_d
        ang = random() * 10 + 25
        ret.extend([LSymbol("!", {"w": wid}),
                    LSymbol("F", {"l": sym.parameters["l"] / 3}),
                    LSymbol("/", {"a": prev_rot + 140}),
                    LSymbol("&", {"a": ang}),
                    LSymbol("!", {"w": wid * 0.3}),
                    LSymbol("["),
                    LSymbol("F", {"l": 0.75 * sqrt(n - ind) * sym.parameters["l"] / 3,
                                  "leaves": 25,
                                  "leaf_d_ang": 40,
                                  "leaf_r_ang": 140}),
                    LSymbol("^", {"a": 20}),
                    LSymbol("F", {"l": 0.75 * sqrt(n - ind) * sym.parameters["l"] / 3,
                                  "leaves": 25,
                                  "leaf_d_ang": 40,
                                  "leaf_r_ang": 140}),
                    LSymbol("%"),
                    LSymbol("]"),
                    LSymbol("!", {"w": wid}),
                    LSymbol("^", {"a": ang}),
                    LSymbol("\\", {"a": prev_rot + 140}),
                    LSymbol("^", {"a": 1.2})])
        prev_rot += 140
    return ret 
Example 48
Project: tree-gen   Author: friggog   File: acer.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def d1_ang():
    """return random first split angle"""
    return random() * 40 + 60 
Example 49
Project: tree-gen   Author: friggog   File: acer.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def d2_ang():
    """return random second split angle"""
    return random() * 40 + 100 
Example 50
Project: tree-gen   Author: friggog   File: small_pine.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def q_prod(sym):
    """Production rule for Q"""
    ret = [LSymbol("!", {"w": sym.parameters["w"]}),
           LSymbol("&", {"a": 90}),
           LSymbol("+", {"a": random() * 360}),
           LSymbol("!", {"w": sym.parameters["bw"]})]
    b_count = int(random() * 2) + 5
    for _ in range(b_count):
        rand = random() * 130 / b_count
        ret.extend([LSymbol("+", {"a": rand}),
                    LSymbol("["),
                    LSymbol("^", {"a": 5 / max(sym.parameters["bl"] * sym.parameters["bl"], 0.05
                                               ) - 30 * (random() * 0.2 + 0.9)}),
                    LSymbol("A", {"l": sym.parameters["bl"], "w": sym.parameters["bw"]}),
                    LSymbol("]"),
                    LSymbol("+", {"a": (360 / b_count) - rand})])
    ret.extend([LSymbol("!", {"w": sym.parameters["w"]}),
                LSymbol("$"),
                LSymbol("F", {"l": sym.parameters["l"],
                              "leaves": int(sym.parameters["l"] * __n_leaves__ / 3),
                              "leaf_d_ang": 20,
                              "leaf_r_ang": 140}),
                LSymbol("Q", {"w": sym.parameters["w"] - 0.2 / 15,
                              "l": sym.parameters["l"] * 0.95,
                              "bw": sym.parameters["bw"] * __width_r__,
                              "bl": sym.parameters["bl"] * __branch_length_r__}),
                LSymbol("%")])
    return ret