本文整理匯總了Python中random.choices方法的典型用法代碼示例。如果您正苦於以下問題:Python random.choices方法的具體用法?Python random.choices怎麽用?Python random.choices使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類random
的用法示例。
在下文中一共展示了random.choices方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: lambda_handler
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def lambda_handler(event,context):
# Grab data from environment
jobqueue = os.environ['JobQueue']
jobdef = os.environ['JobDefinition']
# Create unique name for the job (this does not need to be unique)
job1Name = 'job1' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
# Set up a batch client
session = boto3.session.Session()
client = session.client('batch')
# Submit the job
job1 = client.submit_job(
jobName=job1Name,
jobQueue=jobqueue,
jobDefinition=jobdef
)
print("Started Job: {}".format(job1['jobName']))
示例2: random_string
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def random_string(n):
if n == 0:
return ""
x = random.random()
if x > 0.5:
pad = " " * n
elif x > 0.3:
pad = "".join(random.choices(digits + " \t\n", k=n))
elif x > 0.2:
pad = "".join(random.choices(ascii_uppercase + " \t\n", k=n))
elif x > 0.1:
pad = "".join(random.choices(ascii_uppercase + digits + " \t\n", k=n))
else:
pad = "".join(
random.choices(ascii_uppercase + digits + punctuation + " \t\n", k=n)
)
return pad
示例3: login
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def login(request: web.Request) -> web.Response:
info, err = await read_client_auth_request(request)
if err is not None:
return err
api, _, username, password, _ = info
device_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
try:
return web.json_response(await api.request(Method.POST, Path.login, content={
"type": "m.login.password",
"identifier": {
"type": "m.id.user",
"user": username,
},
"password": password,
"device_id": f"maubot_{device_id}",
}))
except MatrixRequestError as e:
return web.json_response({
"errcode": e.errcode,
"error": e.message,
}, status=e.http_status)
示例4: add_normal_sar_edges
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def add_normal_sar_edges(self, ratio=1.0):
"""Add extra edges from normal accounts to SAR accounts to adjust transaction graph features
:param ratio: Ratio of the number of edges to be added from normal accounts to SAR accounts
compared to the number of total SAR accounts
"""
sar_flags = nx.get_node_attributes(self.g, IS_SAR_KEY)
orig_candidates = [n for n in self.hubs if not sar_flags.get(n, False)] # Normal
bene_candidates = [n for n, sar in sar_flags.items() if sar] # SAR
num = int(len(bene_candidates) * ratio)
if num <= 0:
return
num_origs = len(orig_candidates)
print("Number of orig/bene candidates: %d/%d" % (num_origs, len(bene_candidates)))
orig_list = random.choices(orig_candidates, k=num)
bene_list = random.choices(bene_candidates, k=num)
for i in range(num):
_orig = orig_list[i]
_bene = bene_list[i]
self.add_transaction(_orig, _bene)
logger.info("Added %d edges from normal accounts to sar accounts" % num)
示例5: chooseRangeValue
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def chooseRangeValue(thresholds, rangeList):
""" Generate a random value based on the probability weights (thresholds) and list of ranges passed
Args:
thresholds : list of probabilities for each choice
rangeList: a list of pair lists giving the lower and upper bounds to choose value from
"""
# pick a number 1..3 from weights
rangeVal = choices(Index3Population, thresholds)
# get the appropriate range given rangeVal
interval = rangeList[rangeVal[0]]
# construct a population list from the result
intervalPopulation = list(range(interval[0], interval[1]))
# construct a equally prob weights list
numElements = interval[1] - interval[0]
probVal = 1.0 / numElements
probList = [probVal] * numElements
# now choose the value from the population based on the weights
val = choices(intervalPopulation, probList)
return val[0]
示例6: get_snap
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def get_snap(self, timeout: int = 3) -> Image or None:
"""
Gets a "snap" of the current camera video data and returns a Pillow Image or None
:param timeout: Request timeout to camera in seconds
:return: Image or None
"""
randomstr = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
snap = self.url + "?cmd=Snap&channel=0&rs=" \
+ randomstr \
+ "&user=" + self.username \
+ "&password=" + self.password
try:
req = request.Request(snap)
req.set_proxy(Request.proxies, 'http')
reader = request.urlopen(req, timeout)
if reader.status == 200:
b = bytearray(reader.read())
return Image.open(io.BytesIO(b))
print("Could not retrieve data from camera successfully. Status:", reader.status)
return None
except Exception as e:
print("Could not get Image data\n", e)
raise
示例7: __init__
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def __init__(self, image_folder, max_images=False, image_size=(512, 512), add_random_masks=False):
super(ImageInpaintingData, self).__init__()
if isinstance(image_folder, str):
self.images = glob.glob(os.path.join(image_folder, "clean/*"))
else:
self.images = list(chain.from_iterable([glob.glob(os.path.join(i, "clean/*")) for i in image_folder]))
assert len(self.images) > 0
if max_images:
self.images = random.choices(self.images, k=max_images)
print(f"Find {len(self.images)} images.")
self.img_size = image_size
self.transformer = Compose([RandomGrayscale(p=0.4),
# ColorJitter(brightness=0.2, contrast=0.2, saturation=0, hue=0),
ToTensor(),
# Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
self.add_random_masks = add_random_masks
示例8: random_masks
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def random_masks(pil_img, size=512, offset=10):
draw = ImageDraw.Draw(pil_img)
# draw liens
# can't use np.random because its not forkable under PyTorch's dataloader with multiprocessing
reps = random.randint(1, 5)
for i in range(reps):
cords = np.array(random.choices(range(offset, size), k=4)).reshape(2, 2)
cords[1] = np.clip(cords[1], a_min=cords[0] - 75, a_max=cords[0] + 75)
width = random.randint(15, 20)
draw.line(cords.reshape(-1).tolist(), width=width, fill=255)
# # draw circles
reps = random.randint(1, 5)
for i in range(reps):
cords = np.array(random.choices(range(offset, size - offset), k=2))
cords.sort()
ex = np.array(random.choices(range(20, 70), k=2)) + cords
ex = np.clip(ex, a_min=offset, a_max=size - offset)
draw.ellipse(np.concatenate([cords, ex]).tolist(), fill=255)
return pil_img
示例9: test_subview
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def test_subview(benchmark):
corpus = resources.generate_corpus(
200,
(5, 10),
(1, 5),
(0, 6),
(1, 20),
random.Random(x=234)
)
random.seed(200)
filtered_utts = random.choices(list(corpus.utterances.keys()), k=20000)
filters = [
subset.MatchingUtteranceIdxFilter(filtered_utts)
]
benchmark(run, corpus, filters)
示例10: test_process_multiple_tag_query_params
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def test_process_multiple_tag_query_params(self):
"""Test that grouping by multiple tag keys returns a valid response."""
with tenant_context(self.tenant):
labels = (
OCPAWSCostLineItemDailySummary.objects.filter(usage_start__gte=self.ten_days_ago)
.values(*["tags"])
.first()
)
self.assertIsNotNone(labels)
tags = labels.get("tags")
qstr = "filter[limit]=2"
# pick a random subset of tags
kval = len(tags.keys())
if kval > 2:
kval = random.randint(2, len(tags.keys()))
selected_tags = random.choices(list(tags.keys()), k=kval)
for tag in selected_tags:
qstr += f"&group_by[tag:{tag}]=*"
url = reverse("reports-openshift-aws-costs") + "?" + qstr
client = APIClient()
response = client.get(url, **self.headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
示例11: create
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def create(self):
'''This will create the complete table'''
self.define_col_types() #define the data types for each column
self.generate_missing_cells() #generate missing cells
local_span_flag=False #no span initially
if(self.assigned_category==3): #if assigned category is 3, then it should have spanned rows or columns
local_span_flag=True
elif(self.assigned_category==4): #if assigned category is 4, spanning/not spanning doesn't matter
local_span_flag=random.choices([True,False],weights=[0.5,0.5])[0] #randomly choose if to span columns and rows for headers or not
#local_span_flag=True
if(local_span_flag):
self.make_header_col_spans()
html=self.create_html() #create equivalent html
#create same row, col and cell matrices
cells_matrix,cols_matrix,rows_matrix=self.create_same_cell_matrix(),\
self.create_same_col_matrix(),\
self.create_same_row_matrix()
tablecategory=self.select_table_category() #select table category of the table
return cells_matrix,cols_matrix,rows_matrix,self.idcounter,html,tablecategory
示例12: _bushes
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def _bushes(self, ctx):
if random.randint(0, 5) == 1:
choosen = random.choices(bushes_objects, bushes_weights)[0]()
result = await choosen.give(ctx.bot, ctx)
ctx.logger.info("Found in bushes : " + choosen.name)
if choosen.db:
db_name = choosen.db
if not result:
db_name += '_not_taken'
await ctx.bot.db.add_to_stat(ctx.message.channel, ctx.message.author, db_name, 1)
_ = self.bot._
language = await self.bot.db.get_pref(ctx.channel, "language")
if result:
await self.bot.send_message(ctx=ctx, message=(_("Searching the bushes around the duck, you found...", language) + "**" + _(choosen.name, language) + "**"))
else:
await self.bot.send_message(ctx=ctx, message=(
_("Searching the bushes around the duck, you found...", language) + "**" + _(choosen.name, language) + "**, " + _("that you unfortunately couldn't take, because your backpack is full.",
language)))
示例13: random_name
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def random_name():
return "".join(random.choices(string.ascii_letters,
k=random.randrange(1, 10)))
示例14: generatebase64
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def generatebase64(seed: int) -> str:
random.seed(seed)
letters = string.ascii_letters + string.digits + "+/="
return "".join(random.choices(letters, k=20))
示例15: setUp
# 需要導入模塊: import random [as 別名]
# 或者: from random import choices [as 別名]
def setUp(self):
self.soi_g80 = []
for i in range(10): #generate test sequences
length = random.randint(101, 1000)
self.soi_g80.append( ''.join( random.choices(['A', 'C', 'G', 'T', 'a', 'c', 'g', 't'], k = length) ) )
self.soi_g80 = np.array(self.soi_g80, dtype = np.string_)
self.features_metadata = model.load_features_metadata()