Python random.choice() Examples
The following are 30
code examples of random.choice().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
random
, or try the search function
.
Example #1
Source File: moving_mnist.py From DDPAE-video-prediction with MIT License | 6 votes |
def __getitem__(self, idx): length = self.n_frames_input + self.n_frames_output if self.is_train or self.num_objects[0] != 2: # Sample number of objects num_digits = random.choice(self.num_objects) # Generate data on the fly images = self.generate_moving_mnist(num_digits) else: images = self.dataset[:, idx, ...] if self.transform is not None: images = self.transform(images) input = images[:self.n_frames_input] if self.n_frames_output > 0: output = images[self.n_frames_input:length] else: output = [] return input, output
Example #2
Source File: test_crud.py From hydrus with MIT License | 6 votes |
def test_delete_type(self): """Test CRUD delete when wrong/undefined class is given.""" object_ = gen_dummy_object(random.choice( self.doc_collection_classes), self.doc) id_ = str(uuid.uuid4()) insert_response = crud.insert( object_=object_, id_=id_, session=self.session) assert isinstance(insert_response, str) assert insert_response == id_ response_code = None try: delete_response = crud.delete( id_=id_, type_="otherClass", session=self.session) except Exception as e: error = e.get_HTTP() response_code = error.code assert 400 == response_code
Example #3
Source File: ggtnn_train.py From gated-graph-transformer-network with MIT License | 6 votes |
def visualize(m, story_buckets, wordlist, answerlist, output_format, outputdir, batch_size=1, seq_len=5, debugmode=False, snap=False): cur_bucket = random.choice(story_buckets) sampled_batch = sample_batch(cur_bucket, batch_size, len(answerlist), output_format) part_sampled_batch = sampled_batch[:3] with open(os.path.join(outputdir,'stories.txt'),'w') as f: ggtnn_graph_parse.print_batch(part_sampled_batch, wordlist, answerlist, file=f) with open(os.path.join(outputdir,'answer_list.txt'),'w') as f: f.write('\n'.join(answerlist) + '\n') if debugmode: args = sampled_batch fn = m.debug_test_fn else: args = part_sampled_batch[:2] + ((seq_len,) if output_format == model.ModelOutputFormat.sequence else ()) fn = m.snap_test_fn if snap else m.fuzzy_test_fn results = fn(*args) for i,result in enumerate(results): np.save(os.path.join(outputdir,'result_{}.npy'.format(i)), result)
Example #4
Source File: test_crud.py From hydrus with MIT License | 6 votes |
def test_delete(self): """Test CRUD delete.""" object_ = gen_dummy_object(random.choice( self.doc_collection_classes), self.doc) id_ = str(uuid.uuid4()) insert_response = crud.insert( object_=object_, id_=id_, session=self.session) delete_response = crud.delete( id_=id_, type_=object_["@type"], session=self.session) assert isinstance(insert_response, str) response_code = None try: get_response = crud.get( id_=id_, type_=object_["@type"], session=self.session, api_name="api") except Exception as e: error = e.get_HTTP() response_code = error.code assert 404 == response_code
Example #5
Source File: test_cli.py From hydrus with MIT License | 6 votes |
def gen_dummy_object(class_title, doc): """Create a dummy object based on the definitions in the API Doc. :param class_title: Title of the class whose object is being created. :param doc: ApiDoc. :return: A dummy object of class `class_title`. """ object_ = { "@type": class_title } for class_path in doc.parsed_classes: if class_title == doc.parsed_classes[class_path]["class"].title: for prop in doc.parsed_classes[class_path]["class"].supportedProperty: if isinstance(prop.prop, HydraLink) or prop.write is False: continue if "vocab:" in prop.prop: prop_class = prop.prop.replace("vocab:", "") object_[prop.title] = gen_dummy_object(prop_class, doc) else: object_[prop.title] = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(6)) return object_
Example #6
Source File: test_crud.py From hydrus with MIT License | 6 votes |
def test_insert(self): """Test CRUD insert.""" object_ = gen_dummy_object(random.choice( self.doc_collection_classes), self.doc) id_ = str(uuid.uuid4()) response = crud.insert(object_=object_, id_=id_, session=self.session) assert isinstance(response, str)
Example #7
Source File: turing.py From gated-graph-transformer-network with MIT License | 6 votes |
def encode_turing_machine_rules(rules, starting_state=None, story=None): if story is None: story = graph_tools.Story() graph = story.graph if starting_state is None: starting_state = random.choice(len(rules)) the_edges = [(cstate, read, write, nstate, direc) for (cstate, stuff) in enumerate(rules) for (read, (write, nstate, direc)) in enumerate(stuff)] random.shuffle(the_edges) for cstate, read, write, nstate, direc in the_edges: source = graph.make_unique('state_{}'.format(cstate)) dest = graph.make_unique('state_{}'.format(nstate)) edge_type = "rule_{}_{}_{}".format(read,write,direc) source[edge_type] = dest story.add_line("rule {} {} {} {} {}".format(source.type, read, write, dest.type, direc)) head = graph.make_unique('head') head.state = graph.make_unique('state_{}'.format(starting_state)) story.add_line("start {}".format(head.state.type)) return story
Example #8
Source File: test_crud.py From hydrus with MIT License | 6 votes |
def gen_dummy_object(class_title, doc): """Create a dummy object based on the definitions in the API Doc. :param class_title: Title of the class whose object is being created. :param doc: ApiDoc. :return: A dummy object of class `class_title`. """ object_ = { "@type": class_title } for class_path in doc.parsed_classes: if class_title == doc.parsed_classes[class_path]["class"].title: for prop in doc.parsed_classes[class_path]["class"].supportedProperty: if isinstance(prop.prop, HydraLink) or prop.write is False: continue if "vocab:" in prop.prop: prop_class = prop.prop.replace("vocab:", "") object_[prop.title] = gen_dummy_object(prop_class, doc) else: object_[prop.title] = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(6)) return object_
Example #9
Source File: test_app.py From hydrus with MIT License | 6 votes |
def gen_dummy_object(class_title, doc): """Create a dummy object based on the definitions in the API Doc. :param class_title: Title of the class whose object is being created. :param doc: ApiDoc. :return: A dummy object of class `class_title`. """ object_ = { "@type": class_title } for class_path in doc.parsed_classes: if class_title == doc.parsed_classes[class_path]["class"].title: for prop in doc.parsed_classes[class_path]["class"].supportedProperty: if isinstance(prop.prop, HydraLink) or prop.write is False: continue if "vocab:" in prop.prop: prop_class = prop.prop.replace("vocab:", "") object_[prop.title] = gen_dummy_object(prop_class, doc) else: object_[prop.title] = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(6)) return object_
Example #10
Source File: grammr2.py From ALF with Apache License 2.0 | 6 votes |
def generate(self, gstate): if gstate.instances[self.ref]: gstate.output.append(random.choice(gstate.instances[self.ref])) else: pass # TODO, no instances yet, what now? generate one? # dharma generates content first, then reference definitions after (which must be created before the content) # this makes the testcases much cleaner ... but how to work with the cracker? # IDEA: # we know which variables are tracked .. (ie references are possible, added to Grammar.tracked) # so whenever a tracked variable could occur, don't generate it, but keep track of where it could be # - if it's in a choice, set the weight to 0 # - if it's somewhere else ?? error? # if a reference to the tracked variable is used, go back and generate the tracked variable in one of the preceding places # it could have occurred. # # simpler: # don't mess with the weights, but do keep track of the first place one could have occurred but didn't # if a reference is needed before one is actually generated, go back and generate it where it could have occurred. # - might be complicated (might violate repeat conditions, might need a reference before we find a place to generate the declaration) # # alternate: go dharma style and don't allow reference variables to be declared except when called for, then defined in a specific place # - how does this work with parsing?
Example #11
Source File: JSON_test_client.py From comport with BSD 3-Clause "New" or "Revised" License | 6 votes |
def generate_disposition(self): return random.choice( ["Inactivated", "Informational Purpose On", "No Violation", "Not Sustained", "Not within Policy", "Partially Sustained", "Sustained", "Unfounded/Exonerated", "Unfounded/False", "Unfounded/Not Involved", "Unfounded/Unwarranted", "Withdrawn", "Within policy", None ])
Example #12
Source File: turing.py From gated-graph-transformer-network with MIT License | 6 votes |
def make_turing_machine_rules(n_states, n_symbols): the_rules = [ [ (random.randrange(n_symbols), random.randrange(n_states), random.choice('LNR')) for symbol in range(n_symbols)] for state in range(n_states)] return the_rules
Example #13
Source File: test_crud.py From hydrus with MIT License | 6 votes |
def test_delete_id(self): """Test CRUD delete when wrong/undefined ID is given.""" object_ = gen_dummy_object(random.choice( self.doc_collection_classes), self.doc) id_ = str(uuid.uuid4()) insert_response = crud.insert( object_=object_, id_=id_, session=self.session) response_code = None try: delete_response = crud.delete( id_=999, type_=object_["@type"], session=self.session) except Exception as e: error = e.get_HTTP() response_code = error.code assert 404 == response_code assert isinstance(insert_response, str) assert insert_response == id_
Example #14
Source File: test_crud.py From hydrus with MIT License | 6 votes |
def test_delete_ids(self): objects = list() ids = "{},{}".format(str(uuid.uuid4()), str(uuid.uuid4())) for index in range(len(ids.split(','))): object = gen_dummy_object(random.choice( self.doc_collection_classes), self.doc) objects.append(object) insert_response = crud.insert_multiple(objects_=objects, session=self.session, id_=ids) delete_response = crud.delete_multiple( id_=ids, type_=objects[0]["@type"], session=self.session) response_code = None id_list = ids.split(',') try: for index in range(len(id_list)): get_response = crud.get( id_=id_list[index], type_=objects[index]["@type"], session=self.session, api_name="api") except Exception as e: error = e.get_HTTP() response_code = error.code assert 404 == response_code
Example #15
Source File: run.py From mutatest with MIT License | 6 votes |
def colorize_output(output: str, color: str) -> str: """Color output for the terminal display as either red or green. Args: output: string to colorize color: choice of terminal color, "red" vs. "green" Returns: colorized string, or original string for bad color choice. """ colors = { "red": f"\033[91m{output}\033[0m", # Red text "green": f"\033[92m{output}\033[0m", # Green text "yellow": f"\033[93m{output}\033[0m", # Yellow text "blue": f"\033[94m{output}\033[0m", # Blue text } return colors.get(color, output)
Example #16
Source File: anneal.py From simulated-annealing-tsp with MIT License | 6 votes |
def initial_solution(self): """ Greedy algorithm to get an initial solution (closest-neighbour). """ cur_node = random.choice(self.nodes) # start from a random node solution = [cur_node] free_nodes = set(self.nodes) free_nodes.remove(cur_node) while free_nodes: next_node = min(free_nodes, key=lambda x: self.dist(cur_node, x)) # nearest neighbour free_nodes.remove(next_node) solution.append(next_node) cur_node = next_node cur_fit = self.fitness(solution) if cur_fit < self.best_fitness: # If best found so far, update best fitness self.best_fitness = cur_fit self.best_solution = solution self.fitness_list.append(cur_fit) return solution, cur_fit
Example #17
Source File: trade_utils.py From indras_net with GNU General Public License v3.0 | 6 votes |
def get_rand_good(goods_dict, nonzero=False): """ What should this do with empty dict? """ # print("Calling get_rand_good()") if goods_dict is None or not len(goods_dict): return None else: if nonzero and is_depleted(goods_dict): # we can't allocate what we don't have! print("Goods are depleted!") return None goods_list = list(goods_dict.keys()) good = random.choice(goods_list) if nonzero: # pick again if the goods is endowed (amt is 0) # if we get big goods dicts, this could be slow: while goods_dict[good][AMT_AVAIL] == 0: good = random.choice(goods_list) return good
Example #18
Source File: el_farol.py From indras_net with GNU General Public License v3.0 | 6 votes |
def discourage(unwanted): """ Discourages extra drinkers from going to the bar by decreasing motivation. Chooses drinkers randomly from the drinkers that went to the bar. """ discouraged = 0 drinkers = get_group(DRINKERS) while unwanted: if DEBUG: user_tell("The members are: " + drinkers.members) rand_name = random.choice(list(drinkers.members)) rand_agent = drinkers[rand_name] if DEBUG: user_tell("drinker ", rand_agent, " = " + repr(drinkers[rand_agent])) rand_agent[MOTIV] = max(rand_agent[MOTIV] - DISC_AMT, MIN_MOTIV) discouraged += 1 unwanted -= 1 return discouraged
Example #19
Source File: menger_model.py From indras_net with GNU General Public License v3.0 | 6 votes |
def add_prod_goods(self): """ Add who produces which good, and make them a vendor of that good in the market. """ my_good = None for agent in self.agents: for good in self.market.goods_iter(): if not self.market.has_vendor(good): my_good = good break if my_good is None: my_good = random.choice(list(self.market.goods_iter())) agent.prod_good = my_good self.market.add_vendor(my_good, agent) print("Market = " + str(self.market))
Example #20
Source File: FireFlies.py From BiblioPixelAnimations with MIT License | 6 votes |
def step(self, amt=1): amt = 1 # anything other than 1 would be just plain silly if self._step > self.layout.numLEDs: self._step = 0 self.layout.all_off() for i in range(self._count): pixel = random.randint(0, self.layout.numLEDs - 1) color = random.choice(self.palette) for i in range(self._width): if pixel + i < self.layout.numLEDs: self.layout.set(pixel + i, color) self._step += amt
Example #21
Source File: hyperspace.py From BiblioPixelAnimations with MIT License | 6 votes |
def step(self, amt=1): self.layout.all_off() for i in range(self._growthRate): newTail = random.randrange(0, 360, self._angleDiff) color = random.choice(self.palette) self._tails[newTail].append((0, color)) for a in range(360): angle = self._tails[a] if len(angle) > 0: removals = [] for r in range(len(angle)): tail = angle[r] if tail[0] <= self.lastRing: self._drawTail(a, tail[0], tail[1]) if tail[0] - (self._tail - 1) <= self.lastRing: tail = (tail[0] + amt, tail[1]) self._tails[a][r] = tail else: removals.append(tail) for r in removals: self._tails[a].remove(r) self._step = 0
Example #22
Source File: klass_review.py From everyclass-server with Mozilla Public License 2.0 | 5 votes |
def import_demo_content(cls): """给每一门class导入若干随机生成的评价""" from everyclass.server.course.model import KlassMeta comments_content = [ "这个课挺好的", "不知道老师在讲啥", "老师讲的非常好", "英语学渣表示听不懂" ] comments_score = [ "分给的有点低", "分数还可以", "分数巨高", "分数很满意", "分太低了" ] student_ids = [] with open(os.path.join(os.path.dirname(__file__), "student_ids.csv")) as f: for line in f.readlines(): student_ids.append(line[:len(line) - 1]) classes = db_session.query(KlassMeta).all() for klass in classes: for _ in range(random.randint(0, 3)): student_id = random.choice(student_ids) print("student_id: %s" % student_id) cls.new(klass.klass_id, student_id, random.randint(2, 5), random.randint(2, 5), random.randint(60, 100), random.randint(3, 8), f"{random.choice(comments_content)},{random.choice(comments_score)}")
Example #23
Source File: turing.py From gated-graph-transformer-network with MIT License | 5 votes |
def generate_universal(num_seqs, num_states, num_symbols, input_len, run_len): result = [] for _ in range(num_seqs): rules = make_turing_machine_rules(num_states, num_symbols) start_state = random.randrange(num_states) input_list = [random.choice(range(num_symbols)) for _ in range(input_len)] head_index = random.randrange(input_len) story = encode_turing_machine_rules(rules, start_state) story = encode_turing_machine_process(rules, start_state, input_list, run_len, head_index, story, True) result.extend(story.lines) return "\n".join(result)+"\n"
Example #24
Source File: fireflies.py From BiblioPixelAnimations with MIT License | 5 votes |
def step(self, amt=1): amt = 1 # anything other than 1 would be just plain silly if self._step > self.layout.numLEDs: self._step = 0 self.layout.all_off() for i in range(self._count): pixel = random.randint(0, self.layout.numLEDs - 1) color = random.choice(self.palette) self.layout._set_base(pixel, color) self._step += amt
Example #25
Source File: Provider.py From bomb3r with GNU General Public License v3.0 | 5 votes |
def __init__(self, target, proxy={}, verbose=False, cc='91', config=False): if config: self.config = config else: self.config = random.choice(PROVIDERS[cc if cc in PROVIDERS else 'multi']) self.target = target self.headers = self._headers() self.done = False self.proxy = proxy self.verbose = verbose self.cc = cc
Example #26
Source File: ebay-watcher.py From ebay-watcher with MIT License | 5 votes |
def get_proxy(proxy_list): ''' (list) -> dict Given a proxy list <proxy_list>, a proxy is selected and returned. ''' # Choose a random proxy proxy = random.choice(proxy_list) # Split up the proxy proxy_parts = proxy.split(':') # Set up the proxy to be used try: proxies = { "http": "http://" + proxy_parts[2] + ":" + proxy_parts[3] + "@" +\ proxy_parts[0] + ":" + proxy_parts[1], "https": "https://" + proxy_parts[2] + ":" + proxy_parts[3] + "@" +\ proxy_parts[0] + ":" + proxy_parts[1] } except: proxies = { "http": str(proxy), "https": str(proxy) } # Return the proxy return proxies
Example #27
Source File: ngram_next.py From gated-graph-transformer-network with MIT License | 5 votes |
def generate(num_seqs, seq_length, ngram_size, symbols): assert ITEM_PTR not in symbols assert seq_length > ngram_size result = [] for _ in range(num_seqs): while True: #just in case we don't find a good query story = [] last_ptr = None values = [] nodes = [] edges = [] for i in range(seq_length): # Choose next number next_item = random.choice(symbols) if not next_item in nodes: nodes.append(next_item) cur_ptr = ITEM_PTR + "#" + str(i) nodes.append(cur_ptr) if last_ptr is not None: edges.append({"from":last_ptr,"to":cur_ptr,"type":"next"}) edges.append({"from":cur_ptr,"to":next_item,"type":"value"}) last_ptr = cur_ptr values.append(next_item) graph_str = json.dumps({ "nodes":nodes, "edges":edges, }) story.append("{} {}={}".format(i+1, next_item, graph_str)) possible_queries = ngram_next_map(values, ngram_size) if len(possible_queries) > 0: key, val = random.choice(list(possible_queries.items())) story.append("{} {}?\t{}".format(seq_length+1, ' '.join(key), val)) result.extend(story) break return "\n".join(result)+"\n"
Example #28
Source File: mutator.py From sandsifter with BSD 3-Clause "New" or "Revised" License | 5 votes |
def generate_seed(): b="" # prefix if random.randint(0,1)==1: b+=random.choice(prefixes) # opcode o = random.randint(1,3) if o==1: b+=rand_byte() elif o==2: b+="\x0f" b+=rand_byte() elif o==3: b+="\x0f\x38" b+=rand_byte() # modr/m b+=rand_byte() # sib # disp b+="".join(rand_byte() for _ in range(4)) # imm b+="".join(rand_byte() for _ in range(4)) return b
Example #29
Source File: work_data.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 5 votes |
def try_pick_piece_of_work(self, worker_id, submission_id=None): """Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_id: if not None then this method will try to pick piece of work for this submission Returns: ID of the claimed work piece """ client = self._datastore_client unclaimed_work_ids = None if submission_id: unclaimed_work_ids = [ k for k, v in iteritems(self.work) if is_unclaimed(v) and (v['submission_id'] == submission_id) ] if not unclaimed_work_ids: unclaimed_work_ids = [k for k, v in iteritems(self.work) if is_unclaimed(v)] if unclaimed_work_ids: next_work_id = random.choice(unclaimed_work_ids) else: return None try: with client.transaction() as transaction: work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id, KIND_WORK, next_work_id) work_entity = client.get(work_key, transaction=transaction) if not is_unclaimed(work_entity): return None work_entity['claimed_worker_id'] = worker_id work_entity['claimed_worker_start_time'] = get_integer_time() transaction.put(work_entity) except: return None return next_work_id
Example #30
Source File: MathFunc.py From BiblioPixelAnimations with MIT License | 5 votes |
def step(self, amt=1): self.layout.all_off() for y in range(self.height): for x in range(self.width): h = self.call_func(self.cur_func, x, y, self._step) if self.next_func: h_next = self.call_func(self.next_func, x, y, self._step) h = hue_fade(h, h_next, self.fade_step * self.fade_count) c = self.palette(h) self.layout.set(x, y, c) if self.next_func: self.fade_count += 1 if self.fade_count >= self.fade_frames: self.cur_func = self.next_func self.next_func = None self.fade_count = 0 self.count = 0 else: self.count += 1 if not self.next_func and self.frames_per and self.count >= self.frames_per: if self.rand: self.next_func = random.choice(range(len(self.funcs))) else: self.next_func = self.cur_func + 1 if self.next_func >= len(self.funcs): self.next_func = 0 self.state = 2 self.count = 0 if not self.fade_frames: self.cur_func = self.next_func self.next_func = None self._step += amt