def save(self):
# Use long filename as first preference
filename = self.longFilename
# Otherwise use the short filename
if filename is None:
filename = self.shortFilename
# Otherwise just make something up!
if filename is None:
import random
import string
filename = 'UnknownFilename ' + \
''.join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(5)) + ".bin"
#f = open("/tmp/" + filename, 'wb')
# if self.data is None:
#f.write(("Pas de PJ"))
# f.close()
# else:
# f.write((self.data))
# f.close()
# return filename
python类choice()的实例源码
def render(self,PolygonList):
a = self.get_neighbours(PolygonList)
land = [i.terrain for i in a if i.terrain >= 0]
salt = [i for i in self.get_neighbours(PolygonList) if i.terrain < 0]
if len([i for i in self.vertices if i.river == True])/len(self.vertices) > 0.88:
if not salt:
self.terrain = 0
self.color = color_palettes.shallows[2]
if self.terrain < 0 and land:
self.terrain = -1
#self.color = color_palettes.shallows[0]
elif self.terrain > 0 and len(land) != len(a):
#coast = [i for i in self.vertices if i.coast]
#if len(coast) > 1:
# render_coast(coast)
if self.terrain > 2:
self.color = random.choice(color_palettes.cliff)
else:
self.terrain = 1
#self.color = random.choice(color_palettes.sand)
def move():
hits_robot = []
hits_non_robot = []
for move in MOVES:
target = shooting(move)
if target and target[TYPE] == ROBOT:
hits_robot.append(move)
elif target:
hits_non_robot.append(move)
if LASER in hits_robot:
return LASER
elif hits_robot:
return random.choice(hits_robot)
elif hits_non_robot:
return random.choice(hits_non_robot)
else:
return FORWARD # Find something to shoot!
def reorder_bpr_loss(re_x, his_x, dynamic_user, item_embedding, config):
'''
loss function for reorder prediction
re_x padded reorder baskets
his_x padded history bought items
'''
nll = 0
ub_seqs = []
for u, h, du in zip(re_x, his_x, dynamic_user):
du_p_product = torch.mm(du, item_embedding.t()) # shape: max_len, num_item
nll_u = [] # nll for user
for t, basket_t in enumerate(u):
if basket_t[0] != 0:
pos_idx = torch.cuda.LongTensor(basket_t) if config.cuda else torch.LongTensor(basket_t)
# Sample negative products
neg = [random.choice(h[t]) for _ in range(len(basket_t))] # replacement
# neg = random.sample(range(1, config.num_product), len(basket_t)) # without replacement
neg_idx = torch.cuda.LongTensor(neg) if config.cuda else torch.LongTensor(neg)
# Score p(u, t, v > v')
score = du_p_product[t - 1][pos_idx] - du_p_product[t - 1][neg_idx]
# Average Negative log likelihood for basket_t
nll_u.append(- torch.mean(torch.nn.LogSigmoid()(score)))
nll += torch.mean(torch.cat(nll_u))
return nll
def slack(text: hug.types.text):
"""Returns JSON containing an attachment with an image url for the Slack integration"""
title = text
if text == 'top250':
top250_res = requests.get(IMDB_URL + '/chart/toptv', headers={'Accept-Language': 'en'})
top250_page = html.fromstring(top250_res.text)
candidates = top250_page.xpath('//*[@data-caller-name="chart-top250tv"]//tr/td[2]/a')
title = random.choice(candidates).text
return dict(
response_type='in_channel',
attachments=[
dict(image_url=GRAPH_URL + f'/graph?title={quote(title)}&uuid={uuid.uuid4()}')
]
)
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 test_one_sample_one_line(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
do_line = random.choice(x_series_device.do_lines).name
with nidaqmx.Task() as task:
task.do_channels.add_do_chan(
do_line, line_grouping=LineGrouping.CHAN_PER_LINE)
writer = DigitalSingleChannelWriter(task.out_stream)
reader = DigitalSingleChannelReader(task.in_stream)
# Generate random values to test.
values_to_test = [bool(random.getrandbits(1)) for _ in range(10)]
values_read = []
for value_to_test in values_to_test:
writer.write_one_sample_one_line(value_to_test)
time.sleep(0.001)
values_read.append(reader.read_one_sample_one_line())
numpy.testing.assert_array_equal(values_read, values_to_test)
def test_one_sample_port_byte(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
do_port = random.choice(
[d for d in x_series_device.do_ports if d.do_port_width <= 8])
with nidaqmx.Task() as task:
task.do_channels.add_do_chan(
do_port.name, line_grouping=LineGrouping.CHAN_FOR_ALL_LINES)
# Generate random values to test.
values_to_test = [int(random.getrandbits(do_port.do_port_width))
for _ in range(10)]
writer = DigitalSingleChannelWriter(task.out_stream)
reader = DigitalSingleChannelReader(task.in_stream)
values_read = []
for value_to_test in values_to_test:
writer.write_one_sample_port_byte(value_to_test)
time.sleep(0.001)
values_read.append(reader.read_one_sample_port_byte())
numpy.testing.assert_array_equal(values_read, values_to_test)
def test_one_sample_port_uint16(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
do_port = random.choice(
[do for do in x_series_device.do_ports if do.do_port_width <= 16])
with nidaqmx.Task() as task:
task.do_channels.add_do_chan(
do_port.name, line_grouping=LineGrouping.CHAN_FOR_ALL_LINES)
# Generate random values to test.
values_to_test = [int(random.getrandbits(do_port.do_port_width))
for _ in range(10)]
writer = DigitalSingleChannelWriter(task.out_stream)
reader = DigitalSingleChannelReader(task.in_stream)
values_read = []
for value_to_test in values_to_test:
writer.write_one_sample_port_uint16(value_to_test)
time.sleep(0.001)
values_read.append(reader.read_one_sample_port_uint16())
numpy.testing.assert_array_equal(values_read, values_to_test)
def test_create_ai_voltage_chan(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
ai_phys_chan = random.choice(x_series_device.ai_physical_chans).name
with nidaqmx.Task() as task:
ai_channel = task.ai_channels.add_ai_voltage_chan(
ai_phys_chan, name_to_assign_to_channel="VoltageChannel",
terminal_config=TerminalConfiguration.NRSE, min_val=-20.0,
max_val=20.0, units=VoltageUnits.FROM_CUSTOM_SCALE,
custom_scale_name="double_gain_scale")
assert ai_channel.physical_channel.name == ai_phys_chan
assert ai_channel.name == "VoltageChannel"
assert ai_channel.ai_term_cfg == TerminalConfiguration.NRSE
assert ai_channel.ai_min == -20.0
assert ai_channel.ai_max == 20.0
assert (ai_channel.ai_voltage_units ==
VoltageUnits.FROM_CUSTOM_SCALE)
assert (ai_channel.ai_custom_scale.name ==
"double_gain_scale")
def test_create_ai_resistance_chan(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
ai_phys_chan = random.choice(x_series_device.ai_physical_chans).name
with nidaqmx.Task() as task:
ai_channel = task.ai_channels.add_ai_resistance_chan(
ai_phys_chan, name_to_assign_to_channel="ResistanceChannel",
min_val=-1000.0, max_val=1000.0, units=ResistanceUnits.OHMS,
resistance_config=ResistanceConfiguration.TWO_WIRE,
current_excit_source=ExcitationSource.EXTERNAL,
current_excit_val=0.002, custom_scale_name="")
assert ai_channel.physical_channel.name == ai_phys_chan
assert ai_channel.name == "ResistanceChannel"
assert numpy.isclose(ai_channel.ai_min, -1000.0, atol=1)
assert numpy.isclose(ai_channel.ai_max, 1000.0, atol=1)
assert ai_channel.ai_resistance_units == ResistanceUnits.OHMS
assert (ai_channel.ai_resistance_cfg ==
ResistanceConfiguration.TWO_WIRE)
assert ai_channel.ai_excit_src == ExcitationSource.EXTERNAL
assert ai_channel.ai_excit_val == 0.002
def test_watchdog_expir_state(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
do_line = random.choice(x_series_device.do_lines)
with nidaqmx.system.WatchdogTask(
x_series_device.name, timeout=0.1) as task:
expir_states = [DOExpirationState(
physical_channel=do_line.name,
expiration_state=Level.TRISTATE)]
task.cfg_watchdog_do_expir_states(expir_states)
expir_state_obj = task.expiration_states[do_line.name]
assert expir_state_obj.expir_states_do_state == Level.TRISTATE
expir_state_obj.expir_states_do_state = Level.LOW
assert expir_state_obj.expir_states_do_state == Level.LOW
def test_arm_start_trigger(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
counter = random.choice(self._get_device_counters(x_series_device))
with nidaqmx.Task() as task:
task.co_channels.add_co_pulse_chan_freq(counter)
task.triggers.arm_start_trigger.trig_type = (
TriggerType.DIGITAL_EDGE)
assert (task.triggers.arm_start_trigger.trig_type ==
TriggerType.DIGITAL_EDGE)
task.triggers.arm_start_trigger.trig_type = (
TriggerType.NONE)
assert (task.triggers.arm_start_trigger.trig_type ==
TriggerType.NONE)
def test_pause_trigger(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
counter = random.choice(self._get_device_counters(x_series_device))
with nidaqmx.Task() as task:
task.co_channels.add_co_pulse_chan_freq(counter)
task.timing.cfg_implicit_timing(
sample_mode=AcquisitionType.CONTINUOUS)
task.triggers.pause_trigger.trig_type = (
TriggerType.DIGITAL_LEVEL)
assert (task.triggers.pause_trigger.trig_type ==
TriggerType.DIGITAL_LEVEL)
task.triggers.pause_trigger.trig_type = (
TriggerType.NONE)
assert (task.triggers.pause_trigger.trig_type ==
TriggerType.NONE)
def generate_random_forecast(use_celcius=True):
""" Generate a random weather forecast.
:param use_celcius: If true, phrase should use degrees celcius,
otherwise use Fahrenheit.
:return: A phrase describing a random weather forecast.
"""
degrees = random.choice([12, 15, 18, 21, 23])
conditions = random.choice([_("cloudy"), _("rainy"), _(
"thunder storms"), _("windy"), _("clear sky"), _("light wind")])
if use_celcius:
degrees_sentence = _("{} degrees celcius").format(degrees)
else:
degrees = int(degrees * 9 / 5 + 32)
degrees_sentence = _("{} degrees Fahrenheit").format(degrees)
return _("{}, {}").format(conditions, degrees_sentence)
def test_map_juke(self):
if len(self.instance.map_manager.maps) <= 1:
raise Exception('Test server should contain more than 1 map!')
while True:
next_map = random.choice(list(self.instance.map_manager.maps))
if next_map.uid != self.instance.map_manager.current_map.uid:
break
# Set next map
await self.instance.map_manager.set_next_map(next_map)
assert self.instance.map_manager.next_map == next_map
map_info = await self.instance.gbx.execute('GetNextMapInfo')
assert map_info['UId'] == next_map.uid
#
# async def test_map_jump(self):
# if len(self.instance.map_manager.maps) <= 1:
# raise Exception('Test server should contain more than 1 map!')
# while True:
# jump_map = random.choice(self.instance.map_manager.maps)
# if jump_map.uid != self.instance.map_manager.current_map.uid:
# break
#
# # Skip to next map.
# await self.instance.map_manager.set_current_map(jump_map)
# assert self.instance.map_manager.next_map == jump_map
def minutes_for_days():
"""
500 randomly selected days.
This is used to make sure our test coverage is unbaised towards any rules.
We use a random sample because testing on all the trading days took
around 180 seconds on my laptop, which is far too much for normal unit
testing.
We manually set the seed so that this will be deterministic.
Results of multiple runs were compared to make sure that this is actually
true.
This returns a generator of tuples each wrapping a single generator.
Iterating over this yeilds a single day, iterating over the day yields
the minutes for that day.
"""
env = TradingEnvironment()
random.seed('deterministic')
return ((env.market_minutes_for_day(random.choice(env.trading_days)),)
for _ in range(500))
def add_if_below_threshold(cls, player, asteroid_list, at_least_x_existing):
if len(asteroid_list) < at_least_x_existing:
plus_or_minus_x = random.choice([1, -1])
new_asteroid_x = player.sprite.rect.top - (cls.SPAWN_DISTANCE_FROM_PLAYER * plus_or_minus_x)
if new_asteroid_x > player.sprite.rect.left:
x_speed = -1
else:
x_speed = 1
plus_or_minus_y = random.choice([1, -1])
new_asteroid_y = player.sprite.rect.left - (cls.SPAWN_DISTANCE_FROM_PLAYER * plus_or_minus_y)
if new_asteroid_y > player.sprite.rect.top:
y_speed = -1
else:
y_speed = 1
another_asteroid = Asteroid((new_asteroid_x, new_asteroid_y), 10, x_speed, y_speed)
asteroid_list.add(another_asteroid)
def generate_bot_move(self):
"""Returns the computer selected row, col
"""
selections = defaultdict(list)
if self.bot_level == 1: # Easy - Pick any one from valid_choices list
selected_item = random.choice(self.game_choices)
elif self.bot_level == 2: # Hard - Try to block the player from winning
for win_set in self.winning_combos:
rem_items = list(win_set - self.player_a_choices - self.player_b_choices)
selections[len(rem_items)].append(rem_items)
if selections.get(1):
selected_item = random.choice(random.choice(selections[1]))
elif selections.get(2):
selected_item = random.choice(random.choice(selections[2]))
else:
selected_item = random.choice(random.choice(selections[3]))
return selected_item
def gen_pass(dump, key):
"""Generate password for a user account."""
if key is None:
print("no key available")
exit(1)
rands = ''.join(random.choice(CHARS) for _ in range(64))
encoded = wrapper.encrypt(rands, key)
raw = wrapper.decrypt(encoded, key)
if rands != raw:
print("encrypt/decrypt problem")
exit(1)
if dump:
print("password:")
print(raw)
print("config file encoded")
print(encoded)
else:
return (raw, encoded)
def _send_http_post(self, pause=10):
global stop_now
self.socks.send("POST / HTTP/1.1\r\n"
"Host: %s\r\n"
"User-Agent: %s\r\n"
"Connection: keep-alive\r\n"
"Keep-Alive: 900\r\n"
"Content-Length: 10000\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" %
(self.host, random.choice(useragents)))
for i in range(0, 9999):
if stop_now:
self.running = False
break
p = random.choice(string.letters+string.digits)
print term.BOL+term.UP+term.CLEAR_EOL+"Posting: %s" % p+term.NORMAL
self.socks.send(p)
time.sleep(random.uniform(0.1, 3))
self.socks.close()
def randomagent():
BR_VERS = [
['%s.0' % i for i in xrange(18, 50)],
['37.0.2062.103', '37.0.2062.120', '37.0.2062.124', '38.0.2125.101', '38.0.2125.104', '38.0.2125.111', '39.0.2171.71', '39.0.2171.95', '39.0.2171.99',
'40.0.2214.93', '40.0.2214.111',
'40.0.2214.115', '42.0.2311.90', '42.0.2311.135', '42.0.2311.152', '43.0.2357.81', '43.0.2357.124', '44.0.2403.155', '44.0.2403.157', '45.0.2454.101',
'45.0.2454.85', '46.0.2490.71',
'46.0.2490.80', '46.0.2490.86', '47.0.2526.73', '47.0.2526.80', '48.0.2564.116', '49.0.2623.112', '50.0.2661.86', '51.0.2704.103', '52.0.2743.116',
'53.0.2785.143', '54.0.2840.71'],
['11.0'],
['8.0', '9.0', '10.0', '10.6']]
WIN_VERS = ['Windows NT 10.0', 'Windows NT 7.0', 'Windows NT 6.3', 'Windows NT 6.2', 'Windows NT 6.1', 'Windows NT 6.0', 'Windows NT 5.1', 'Windows NT 5.0']
FEATURES = ['; WOW64', '; Win64; IA64', '; Win64; x64', '']
RAND_UAS = ['Mozilla/5.0 ({win_ver}{feature}; rv:{br_ver}) Gecko/20100101 Firefox/{br_ver}',
'Mozilla/5.0 ({win_ver}{feature}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{br_ver} Safari/537.36',
'Mozilla/5.0 ({win_ver}{feature}; Trident/7.0; rv:{br_ver}) like Gecko',
'Mozilla/5.0 (compatible; MSIE {br_ver}; {win_ver}{feature}; Trident/6.0)']
index = random.randrange(len(RAND_UAS))
return RAND_UAS[index].format(win_ver=random.choice(WIN_VERS), feature=random.choice(FEATURES), br_ver=random.choice(BR_VERS[index]))
def get_seq(self, seq_len):
"""
Gets a single pair of sequences (input, target) from a random song.
@param seq_len: The number of words in a sequence.
@return: A tuple of sequences, (input, target) offset from each other by one word.
"""
# Pick a random song. Must be longer than seq_len
for i in xrange(1000): # cap at 1000 tries
song = random.choice(self.lyric_indices)
if len(song) > seq_len: break
# Take a sequence of (seq_len) from the song lyrics
i = random.randint(0, len(song) - (seq_len + 1))
inp= np.array(song[i:i+seq_len], dtype=int)
target = np.array(song[i+1:i+seq_len+1], dtype=int)
return inp, target
def epsilon_greedy_q_policy(self, state):
'''
Args:
state (State)
Returns:
(str): action.
'''
# Policy: Epsilon of the time explore, otherwise, greedyQ.
if numpy.random.random() > self.epsilon:
# Exploit.
action = self.get_max_q_action(state)
else:
# Explore
action = numpy.random.choice(self.actions)
return action
def _compute_max_qval_action_pair(self, state):
'''
Args:
state (State)
Returns:
(tuple) --> (float, str): where the float is the Qval, str is the action.
'''
# Grab random initial action in case all equal
best_action = random.choice(self.actions)
max_q_val = float("-inf")
shuffled_action_list = self.actions[:]
random.shuffle(shuffled_action_list)
# Find best action (action w/ current max predicted Q value)
for action in shuffled_action_list:
q_s_a = self.get_q_value(state, action)
if q_s_a > max_q_val:
max_q_val = q_s_a
best_action = action
return max_q_val, best_action
def _compute_max_qval_action_pair(self, state, q_func_id=None):
'''
Args:
state (State)
q_func_id (str): either "A", "B", or None. If None, computes avg of A and B.
Returns:
(tuple) --> (float, str): where the float is the Qval, str is the action.
'''
# Grab random initial action in case all equal
best_action = random.choice(self.actions)
max_q_val = float("-inf")
shuffled_action_list = self.actions[:]
random.shuffle(shuffled_action_list)
# Find best action (action w/ current max predicted Q value)
for action in shuffled_action_list:
q_s_a = self.get_q_value(state, action, q_func_id)
if q_s_a > max_q_val:
max_q_val = q_s_a
best_action = action
return max_q_val, best_action
def _compute_max_qval_action_pair(self, state, horizon=None):
'''
Args:
state (State)
horizon (int): Indicates the level of recursion depth for computing Q.
Returns:
(tuple) --> (float, str): where the float is the Qval, str is the action.
'''
# If this is the first call, use the default horizon.
if horizon is None:
horizon = self.horizon
# Grab random initial action in case all equal
best_action = random.choice(self.actions)
max_q_val = self.get_q_value(state, best_action, horizon)
# Find best action (action w/ current max predicted Q value)
for action in self.actions:
q_s_a = self.get_q_value(state, action, horizon)
if q_s_a > max_q_val:
max_q_val = q_s_a
best_action = action
return max_q_val, best_action
def _transition_func(self, state, action):
'''
Args:
state (State)
action (str)
Returns
(State)
'''
if self.num_states == 1:
return state
if (state, action) not in self._transitions:
# Chooses @self.num_rand_trans from range(self.num_states)
self._transitions[state][action] = np.random.choice(self.num_states, self.num_rand_trans, replace=False)
state_id = np.random.choice(self._transitions[state][action])
return RandomState(state_id)
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s" % (random.getstate(), time.time())).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
def randompdf (path) :
numpdf = (randint(1500,2000))
for i in range(10):
name = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"
numwords = (randint(200,1000))
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
words =[]
for i in range(numwords):
randomword = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))])
words.append(randomword)
wordsinstring = ''.join(words)
pdf.cell(200, 10, txt=wordsinstring, align="C")
pdf.output(name)
for i in range(numpdf):
dupli = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"
copyfile(name, dupli)