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]
]
]
python类random()的实例源码
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
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
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
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]
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
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)
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))
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()
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
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)
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)
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))
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()
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
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
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
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
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
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]
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'))
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'
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
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
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
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
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
def __init__(self,location = None):
random.seed()
self.name = generate_name()
self.location = location
self.cities = []
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
def random_sleep(mean=0.3, tolerance=0.15):
sleep_time = mean - tolerance + 2 * tolerance * random()
sleep(sleep_time)