def attack(opponent):
rand_damage = random.randint(8,32)
opponent['HP'] -= rand_damage
## if opponent['HP'] <= 0:
## opponent['HP'] = 0
## return opponent
##print(opponent['HP'])
## else:
return opponent
python类randint()的实例源码
def client(host, port, n, task=None):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = pycos.AsyncSocket(sock)
yield sock.connect((host, port))
print('%s connected' % n)
# send arbitrary length of data
msg = '%d: ' % n + '-' * random.randint(100,300) + '/'
msg = msg.encode()
yield sock.sendall(msg)
sock.close()
# pycos.logger.setLevel(pycos.Logger.DEBUG)
# run 10 client tasks
def get_item(player):
item_list = ["MRE", "First Aid Kit", "Meth-derived stim-pack"]
print("You find a ", item_list[random.randint(0,2)],
"your health increased by ", (abs(player['HP'] - 100)), "HP")
return player['HP'] += abs(player['HP'] - 100)
def test_add_another_offset(self):
topic_1 = uuidutils.generate_uuid()
partition_1 = random.randint(0, 1024)
until_offset_1 = random.randint(0, sys.maxsize)
from_offset_1 = random.randint(0, sys.maxsize)
app_name_1 = uuidutils.generate_uuid()
offset_key_1 = "%s_%s_%s" % (app_name_1, topic_1, partition_1)
my_batch_time = self.get_dummy_batch_time()
used_values = {}
self.kafka_offset_specs.add(topic=topic_1, partition=partition_1,
app_name=app_name_1,
from_offset=from_offset_1,
until_offset=until_offset_1,
batch_time_info=my_batch_time)
used_values[offset_key_1] = {
"topic": topic_1, "partition": partition_1, "app_name": app_name_1,
"from_offset": from_offset_1, "until_offset": until_offset_1
}
kafka_offset_specs = self.kafka_offset_specs.get_kafka_offsets(
app_name_1)
offset_value_1 = kafka_offset_specs.get(offset_key_1)
self.assertions_on_offset(used_value=used_values.get(offset_key_1),
offset_value=offset_value_1)
self.assertEqual(1,
len(self.kafka_offset_specs.get_kafka_offsets(
app_name_1)))
def test_int_property(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
with nidaqmx.Task() as task:
task.ci_channels.add_ci_count_edges_chan(
x_series_device.ci_physical_chans[0].name)
# Test property default value.
assert task.in_stream.offset == 0
# Test property setter and getter.
value_to_test = random.randint(0, 100)
task.in_stream.offset = value_to_test
assert task.in_stream.offset == value_to_test
value_to_test = random.randint(-100, 0)
task.in_stream.offset = value_to_test
assert task.in_stream.offset == value_to_test
# Test property deleter.
del task.in_stream.offset
assert task.in_stream.offset == 0
def test_uint_property(self, x_series_device, seed):
# Reset the pseudorandom number generator with seed.
random.seed(seed)
with nidaqmx.Task() as task:
task.ai_channels.add_ai_voltage_chan(
x_series_device.ai_physical_chans[0].name)
task.timing.cfg_samp_clk_timing(1000)
# Test property initial value.
assert task.timing.samp_clk_timebase_div == 100000
# Test property setter and getter.
value_to_test = random.randint(500, 10000)
task.timing.samp_clk_timebase_div = value_to_test
assert task.timing.samp_clk_timebase_div == value_to_test
# Test property deleter.
del task.timing.samp_clk_timebase_div
assert task.timing.samp_clk_timebase_div == 100000
def _process_event(self, event):
'Processes an event sent to the bot.'
unknown_reactions = [
'I don\'t think I understand you correctly.\nCould you rephrase what you meant?',
'I\'m not sure I know what you mean by that.',
'Could you elaborate on this?',
'I couldn\'t catch what you meant.\nCould you say it differently?',
]
is_understandable = False
self._send_typing(event['channel'])
for keyword in self._keywords:
if keyword in event['text']:
is_understandable = True
if is_understandable:
self._send_typing(event['channel'])
self._send_menus(event)
elif not is_understandable:
self._send_message(
event['channel'],
unknown_reactions[random.randint(0, len(unknown_reactions) - 1)])
return
def augment_data(self, v_img_):
# TODO: create a separate class for augmentation
imsize = self.imsize
for img in v_img_:
#randomly flip
if randint(0,65535)>32767:
img[:,:,:] = img[:,:,::-1]
#adjust gamma
gamma = np.random.uniform(0.77,1.3, size=(imsize[0],1,1))
img **= gamma
#randomly crop image
coinflip = lambda:randint(0,1)
if coinflip():
idx = lambda x:slice(None,x)
else:
idx = lambda x:slice(-x,None)
if coinflip():
n = randint(0,imsize[1]/4)
idx = (slice(None), idx(n), slice(None))
else:
n = randint(0,imsize[2]/4)
idx = (slice(None), slice(None), idx(n))
img[idx] = 0.
return v_img_
def roll(text, limit=1000):
groups = dice_pattern.findall(text)
if len(groups) > limit:
return []
result = []
for group in groups:
sub_result = []
if group[0]:
if group[0].startswith('-'):
sign = -1
else:
sign = 1
for _ in range(int(group[1])):
n = int(group[2])
if n > limit:
return []
sub_result.append(sign * random.randint(1, n))
elif group[3]:
sub_result.append(int(group[3]))
result.append(sub_result)
return result
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 __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 downloadFilesSave(links, fileFormat): # main function
if (links == 'EMPTY'): # if links list is empty
return ' NO LINKS FOUND !'
for link in links:
name = random.randint(0, 10000001)
if (name in os.listdir(os.getcwd())): # random name to files
name = random.randint(0, 10000001)
if (format not in ['zip', 'png', 'jpg', 'jpeg', 'tiff', 'bmp', 'svg', 'gif']):
try:
saveFile=open(str(name)+'.' + fileFormat, 'w')
saveFile.write(urllib2.urlopen(link).read())
saveFile.close()
except urllib2.URLError:
pass
else:
try:
saveFile=open(str(name)+'.' + fileFormat, 'wb')
saveFile.write(urllib2.urlopen(link).read())
saveFile.close()
except urllib2.URLError:
pass
return ' {} DOWNLOADS SUCCESSFULL YET !'.format(len(os.listdir(os.getcwd())))
def genkey(n=0):
n = n or random.randint(0, P)
n &= ~7
n &= ~(128 << 8 * 31)
n |= 64 << 8 * 31
return n
# def str2int(s):
# return int(hexlify(s), 16)
# # return sum(ord(s[i]) << (8 * i) for i in range(32))
#
# def int2str(n):
# return unhexlify("%x" % n)
# # return ''.join([chr((n >> (8 * i)) & 255) for i in range(32)])
#################################################
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 generate_example(seq_length, min_val, max_val):
"""
Creates a list of (a,b) tuples where a is random[min_val,max_val] and b is 1 in only
two tuples, 0 for the rest. The ground truth is the addition of a values for tuples with b=1.
:param seq_length: length of the sequence to be generated
:param min_val: minimum value for a
:param max_val: maximum value for a
:return x: list of (a,b) tuples
:return y: ground truth
"""
# Select b values: one in first X% of the sequence, the other in the second Y%
b1 = random.randint(0, int(seq_length * FIRST_MARKER / 100.) - 1)
b2 = random.randint(int(seq_length * SECOND_MARKER / 100.), seq_length - 1)
b = [0.] * seq_length
b[b1] = 1.
b[b2] = 1.
# Generate list of tuples
x = [(random.uniform(min_val, max_val), marker) for marker in b]
y = x[b1][0] + x[b2][0]
return x, y
def sample_hparams():
hparams = {}
for k, sample_range in ranges.items():
if isinstance(sample_range, (LogRange, LinearRange)):
if isinstance(sample_range[0], int):
# LogRange not valid for ints
hparams[k] = random.randint(sample_range[0], sample_range[1])
elif isinstance(sample_range[0], float):
start, end = sample_range
if isinstance(sample_range, LogRange):
start, end = np.log10(start), np.log10(end)
choice = np.random.uniform(start, end)
if isinstance(sample_range, LogRange):
choice = np.exp(choice)
hparams[k] = choice
return hparams
def sample_hparams():
hparams = {}
for k, sample_range in ranges.items():
if isinstance(sample_range, (LogRange, LinearRange)):
if isinstance(sample_range[0], int):
# LogRange not valid for ints
hparams[k] = random.randint(sample_range[0], sample_range[1])
elif isinstance(sample_range[0], float):
start, end = sample_range
if isinstance(sample_range, LogRange):
start, end = np.log10(start), np.log10(end)
choice = np.random.uniform(start, end)
if isinstance(sample_range, LogRange):
choice = np.exp(choice)
hparams[k] = choice
return hparams
def sample_hparams():
hparams = {}
for k, sample_range in ranges.items():
if isinstance(sample_range, (LogRange, LinearRange)):
if isinstance(sample_range[0], int):
# LogRange not valid for ints
hparams[k] = random.randint(sample_range[0], sample_range[1])
elif isinstance(sample_range[0], float):
start, end = sample_range
if isinstance(sample_range, LogRange):
start, end = np.log10(start), np.log10(end)
choice = np.random.uniform(start, end)
if isinstance(sample_range, LogRange):
choice = np.exp(choice)
hparams[k] = choice
return hparams
def sample_hparams():
hparams = {}
for k, sample_range in ranges.items():
if isinstance(sample_range, (LogRange, LinearRange)):
if isinstance(sample_range[0], int):
# LogRange not valid for ints
hparams[k] = random.randint(sample_range[0], sample_range[1])
elif isinstance(sample_range[0], float):
start, end = sample_range
if isinstance(sample_range, LogRange):
start, end = np.log10(start), np.log10(end)
choice = np.random.uniform(start, end)
if isinstance(sample_range, LogRange):
choice = np.exp(choice)
hparams[k] = choice
return hparams
def sample_hparams():
hparams = {}
for k, sample_range in ranges.items():
if isinstance(sample_range, (LogRange, LinearRange)):
if isinstance(sample_range[0], int):
# LogRange not valid for ints
hparams[k] = random.randint(sample_range[0], sample_range[1])
elif isinstance(sample_range[0], float):
start, end = sample_range
if isinstance(sample_range, LogRange):
start, end = np.log10(start), np.log10(end)
choice = np.random.uniform(start, end)
if isinstance(sample_range, LogRange):
choice = np.exp(choice)
hparams[k] = choice
return hparams
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 encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + '.crypt'
iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
encryptor = AES.new(key, AES.MODE_CBC, iv)
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(struct.pack('<Q', filesize))
outfile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' ' * (16 - len(chunk) % 16)
outfile.write(encryptor.encrypt(chunk))
def rotate_slaves(self):
"Round-robin slave balancer"
slaves = self.sentinel_manager.discover_slaves(self.service_name)
if slaves:
if self.slave_rr_counter is None:
self.slave_rr_counter = random.randint(0, len(slaves) - 1)
for _ in xrange(len(slaves)):
self.slave_rr_counter = (
self.slave_rr_counter + 1) % len(slaves)
slave = slaves[self.slave_rr_counter]
yield slave
# Fallback to the master connection
try:
yield self.get_master_address()
except MasterNotFoundError:
pass
raise SlaveNotFoundError('No slave found for %r' % (self.service_name))
def choose_boundary():
global _prefix
if _prefix is None:
hostid = socket.gethostbyname(socket.gethostname())
try:
uid = `os.getuid()`
except:
uid = '1'
try:
pid = `os.getpid()`
except:
pid = '1'
_prefix = hostid + '.' + uid + '.' + pid
timestamp = '%.3f' % time.time()
seed = `random.randint(0, 32767)`
return _prefix + '.' + timestamp + '.' + seed
def getRandomPixePositionl():
"""
Returns the position of a random pixel in the image
"""
# Get image size
width, height = getSize()
# Get random pixel
a, b = random.randint(0, width - 1), random.randint(0, height - 1)
# Debug
if args.debug:
print('...debug -> random pixel: %d , %d' % (a, b))
return a, b
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 encode(image, number):
'''Encodes the key into the image. Note: number is the str of a bin!'''
width, height = image.size
# Make sure that the image is large enough
if width < len(number):
return False
line = randint(0,height)
column = width - len(number) -1
px = image.load()
for i, char in enumerate(number):
i += column
color = ((px[i, line][2] // 10) * 10) + int(char)
px[i, line]= (px[i,line][0], px[i,line][1], color)
image.save('encoded.png', 'PNG', quality=100)
return True
def unique_books(user, books, result_count):
"""
Return unique random books from given list of books.
:param django.contrib.auth.models.User user: The request user.
:param django.db.models.query.QuerySet[.models.Book] books: The given list of books.
:param int result_count: The count of unique books.
:return set[.models.Book]: The unique books.
"""
books = Book.exclude_private_books(user, books)
unique = set()
if len(books) > START_RECOMMEND:
while len(unique) < result_count:
unique.add(books[random.randint(0, len(books) - 1)])
return unique