def sub_obfus(self, num): res = [] if self.arg.debug: self._utils.sep('obfuscate number') s = [num] if num > 3: s = [num / 2] * 2 if sum(s) != num: s = s + [num % 2] if self.arg.debug: print('{} -> {}'.format(num, s)) for i in range(len(s)): while True: ex = ' '.join([ '( {0} {1} {2} ) {3}'.format(_choice(INTER), _choice(OPER), _choice(INTER), _choice(['-', '+', '*'])) for _ in range( int(s[i]) if int(s[i]) not in (0, 1) else 2) ])[:-2] if eval(ex) == int(s[i]): res.append('( {} )'.format(ex)) break if self.arg.debug: for i in res: print(' -> {0}'.format(i)) return ' + '.join(res)
def gen_alias_bool(TF): while True: x = '( {0} {1} {2} )'.format(_choice(INTER), _choice(OPER), _choice(INTER)) if str(eval(x)) == TF: if not self.arg.with_space: x = _re.sub(r' ', '', x) return x
def test_marker_func(fname, *args): block = tosdb.TOSDB_DataBlock(N,True) block.add_items(*ITEMS) block.add_topics(*TOPICS) topics = list(TOPICS) _shuffle(topics) for topic in topics: item = _choice(ITEMS) date_time = _choice([True,False]) passes = _randint(3,10) wait = int(MAX_SEC_PER_TEST/passes) print("+ TEST", fname, str((item,topic,date_time,passes,wait))) test(fname, block, (item, topic, date_time) + args, passes, wait) block.close()
def chooseBooster(self): probs = _randint(0, 4) if probs != 0: return bst = _choice(['add_bomb', 'add_explosion_range', 'add_speed']) booster = Booster(bst, gameObjectGroup) booster.rect.center = self.rect.center
def GenerateNextBar(self, referenceBar: Bar): from copy import deepcopy as _deepcopy from random import choice as _choice # check first if nothing in referenceBar if len(referenceBar.SoundEvents) == 0: return [] generatedChordSoundEvents = [] if self.BeatsPicked == "All": soundEvents = _deepcopy(referenceBar.SoundEvents) elif self.BeatsPicked == "First": soundEvents = [_deepcopy(referenceBar.SoundEvents[0])] else: # two sound events, harder to implement... # Check if only size one soundEvents = _deepcopy(referenceBar.SoundEvents) if len(soundEvents) > 2: # 1 or 2 Sound events, nothing to do # else gotta do some stuff # compute estimated nb of beats nbBeatsEstimated = soundEvents[-1].Beat + soundEvents[-1].Duration # get the beat that is closest to and higher than half of nbBeatsEstimated target = nbBeatsEstimated / 2 closest = None closestDelta = 999 for s in soundEvents: if closest is None: closest = s else: delta = s.Beat - target if 0 < delta < closestDelta: closestDelta = delta closest = s soundEvents = [soundEvents[0], closest] for se in soundEvents: # Get a valid chord isValidChord = False for chord in self.AllowedChords: notes, errs = chord(se.Note) if sum([val is not None for val in errs]) == 0: # No errors for given scale, break out of loop isValidChord = True break # if no valid chord, choose random if not isValidChord: chord = _choice(self.AllowedChords) notes, _ = chord(se.Note) #, rootInOutput=self.RootInOutput) if (not self.RootInOutput): notes = notes[1:] generatedChordSoundEvents += GenerateSoundEventsFromListNotes( se.Beat, se.Duration, notes ) return generatedChordSoundEvents
def _get_random_start_frame(frames: list): candidates = [] for frame in frames: if frame[0][0] == _START: candidates.append(frame[0]) return _choice(candidates)
def float_rewards(rbound,N): """ Returns an array of N float rewards with absolute value <= rbound """ signs = _array([_choice([-1,1])]*N) return rbound*signs*_randnum(N)
def choice_without_replace(i, n, o=[]): i = list(i) o = list(o) if len(i) == 0 or len(o) >= n: return o else: v = _choice(i) i.remove(v) o.append(v) return choice_without_replace(i,n,o)
def choice_without_replace(i, n, o=[]): i = list(i) o = list(o) if len(i) == 0 or len(o) >= n: return o else: v = _choice(i) i.remove(v) o.append(v) return choice_without_replace(i, n, o)
def ChooseNextNote(self, refNote: Note, allowedNotes: List[Note]): from random import choice as _choice if refNote is None: return _choice(allowedNotes) else: possibleNotes = [] for interval in self.AllowedIntervals: currNote, err = refNote + interval if err is None: possibleNotes.append(currNote) currNote, err = refNote - interval if err is None: possibleNotes.append(currNote) filteredNotes = list( filter( lambda x: x in allowedNotes, possibleNotes ) ) return _choice(filteredNotes)
def __init__(self, *groups): super().__init__(*groups) self.image = enemy_img.subsurface([0, 0, 16, 16]) self.image = pg.transform.scale(self.image, [50, 50]) self.rect = self.image.get_rect() self.dead = False self.vel_x = 0 self.vel_y = 0 self.mov = 0 self.direction = _choice(['up', 'bottom', 'left', 'right']) self.target = None
def generate_new_script(self): PREVIOUS = '' if self.arg.debug: self._utils.sep('remake script') print('filename -> {}'.format(self.arg.infile)) f = self.clear_text(self.arg.infile) for num, i in enumerate(f): if i not in ('\n', ""): if self.arg.rand_if: if _choice([True, False]): if i[-1] not in EXTH: if num + 1 < len(f): if len(f[num + 1]) > 0: if _re.sub('^[ ]*', "", f[num + 1])[0] in EXCH or \ 'else' in f[num + 1]: continue jm = self._space(i) if "".join([_ for _ in i[jm:] if _ in EXCH]) == i[jm:] or \ i[jm:][0] in EXCH: continue if len(f[num - 1]) > 0: if f[num - 1][-1] in EXTH: if self._space(f[num - 1]) != jm: continue if i[-1] in EXCH: continue if_stat = self._utils.rand_if(jm) if not self.arg.with_space: for i in OPER + ['-', ':']: if_stat = if_stat.replace( ' {} '.format(i), i) if f[num] in [PREVIOUS, f[num - 1]]: if_stat = '{}el{}'.format( ' ' * jm, if_stat[jm:]) if self.arg.debug: self._utils.sep('added') print('{} -> line {}'.format( if_stat[jm:], num + 1)) # <-- update --> PREVIOUS, _INDEX = if_stat, 1 if 'return' in i or 'yield' in i: _INDEX = 0 f.insert(num + _INDEX, if_stat) f = '\n'.join(f).splitlines() if self.arg.indent: r = reindenter(f, self.arg.indent) return ''.join(r.run()) return '\n'.join(f)
def Roll(roll_description): roll = _parse_roll_description(roll_description) output = list() total = 0 for _ in range(roll.count): result = _choice(_simple_side_generation(roll.sides)) output.append(result) if roll.keep_best: output.sort() output.reverse() output = output[:roll.keep_best] output = map(lambda x: (x, roll.per_die), output) total = _reduce(_add, _reduce(_add, output)) total += roll.post_roll total = total if total >= 0 else 0 return (total, output)
def obfuscate(s): '''\ Simple Obfuscation Utility Output: URURURURUR...UR where U stands for chars in the clear text, and R stands for chars randomly generated. ''' length = len(s) _seed() randrange = [chr(i) for i in range(0x20, 0x7f)] # Randomized chars tmp2 = [_choice(randrange) for i in range(length)] # Interpolate # This integer division is Python 2.x-specific, but since # Django hasn't supported Py3k yet, this shouldn't cause # problem in understanding return ''.join(s[i/2] if i%2==0 \ else tmp2[i/2] \ for i in range(length*2))
def _try_to_say_something(bot, message): """Find a response and maybe say something.""" try: room = _rooms[message.chat_id] previous_messages = room['dict'].keys() similar_messages = _get_close_matches(message.text, previous_messages) if len(similar_messages) > 0 and _random() < _talkativeness: choosen_message = _choice(similar_messages) response = room['dict'][choosen_message] bot.send_message(message.chat_id, response) _update_last_message(room, response, 'bot') except TypeError as te: if "'NoneType' object is not iterable" in str(te): # this happens when message.text==None return else: raise
def flatten_choice(input_list: list) -> Any: r"""flatools.flatten_choice(input_list) Randomly selects an element from a flattened list which can containing any number of nested subslists. Usage: >>> alist = [[1, 4], [5, 7], [2], [9, 6, 10], [8, 3]] >>> flatools.flatten_choice(alist) 9 >>> alist = [1, 5, [3, [2, 4]]] >>> flatools.flatten_choice(alist) 4 The list can also be made out of any types: >>> alist = [1, [2.2, True], ['foo', [(1, 4), None]], [3+2j, {'a': 1}]] >>> flatools.flatten_choice(alist) (1, 4) """ if not isinstance(input_list, list): raise TypeError('\'input_list\' must be \'list\'') return _choice(flatten(input_list))
def rewire_edges(A, p=0.01, directed=False, copy=False): """Randomly rewire edges in an adjacency matrix with given probability. Parameters ---------- A : (N, N) array_like An adjacency matrix. p : float Rewiring probability. directed : bool Is the graph directed. copy : bool Should copy of the adjacency array be returned. """ if copy: A = A.copy() E = get_edgelist(A, directed=directed) loop = range(0, E.shape[0]) if directed else range(0, E.shape[0], 2) for u in loop: rand = _uniform(0, 1) if rand <= p: i, j = E[u, :2] if not directed and rand <= p / 2: new_i = j else: new_i = i idx = np.nonzero(np.where(A[new_i, :] == 0, 1, 0))[0] idx = idx[idx != new_i] if idx.size == 0: continue new_j = _choice(idx) A[i, j] = 0 A[new_i, new_j] = 1 if not directed: A[j, i] = 0 A[new_j, new_i] = 1 return A
def generate(self, count: int, upper_first_letter: bool = True): generated_strings = [] for _ in range(count): current_frame = _get_random_start_frame(self.frames) generated = [current_frame] while _END not in current_frame: available = self.frame_map[current_frame] if not available: available = [_END] generated.append(_choice(available)) current_frame = generated[-1] generated_strings.append(_generated_to_string(generated)) for i in range(len(generated_strings)): if upper_first_letter: generated_strings[i] = generated_strings[i][0].upper( ) + generated_strings[i][1:] return generated_strings
def getTempFilename(suffix='', prefix='tmp', dir=None, n=5, chars='abcdefghijklmnopqrstuvwxyz0123456789'): u""" 任意に使えるテンポラリファイル名をフルパスで得る。 :param `str` prefix: ファイル名に付ける任意の接頭辞を指定する。 :param `str` suffix: ファイル名に付ける任意の接尾辞を指定する。 :param `str` dir: ファイルを生成するディレクトリパスを指定する。 :param `int` n: ランダムに決まる部分の文字数を指定する。 :param `str` chars: ランダムに決まる部分に使用される文字。 :rtype: `str` """ if dir is None: dir = _gettempdir() namer = lambda: ''.join([_choice(chars) for i in range(n)]) name = _os_path_join(dir, prefix + namer() + suffix) while _os_path_exists(name): name = _os_path_join(dir, prefix + namer() + suffix) return name
def random(minlen=5, maxlen=10, punct=False): letters = [_letters, _letters_with_symbols][punct] return ''.join(_choice(letters) for _ in range(_randint(minlen, maxlen)))
def _random_str(size=1, choice_list=_last_names): """随机获取n个汉字""" string = "" for i in range(size): string += _choice(choice_list) return string
# -*- coding: iso-8859-1 -*- # Copyright (C) 2003-2009 Bastian Kleineidam """ Parameters for adminpass.html page. """ from wc import AppName, Version from wc.configuration import config from os.path import join as _join from random import choice as _choice import string as _string ConfigFile = _join(config.configdir, "webcleaner.conf") _chars = _string.letters + _string.digits adminpass = u''.join([_choice(_chars) for i in xrange(8)]) adminuser = config.get('adminuser', u'admin') adminpass_b64 = adminpass.encode("base64").strip()
def _department_name(): """生成部门""" return _choice(_department_list)
def encode_base(self, x): return _choice(ENCODE_BASE).format(self.convert(256), self.convert(0), self.convert(encode(x)))
def randstring(l): return "".join([_choice(_ascii_chars+_digs) for i in lzint(l)])
def begin(self): if self.arg.txt or self.arg.infile: if self.arg.only_strint or self.arg.only_variable: if self.arg.infile: if not _os.path.isfile(self.arg.infile): _sys.exit( "IOError: [Errno 2] No such file or directory: '%s'" % self.arg.infile) self.check_syntax() # None _fin = self.obfuscator.rebuild() if self.arg.debug or self.arg._eval or self.arg.verbose: self._utils.sep('result') print(_fin) if self.arg.outfile: if self.arg.serialization and not self.arg.only_variable: if self.arg.debug or self.arg.verbose: self._utils.sep('serialization') print 'None' new_fin = compile(_fin, '<script>', 'exec') _fin = 'import marshal\nexec(marshal.loads({}))'.format( repr(_marshal.dumps(new_fin))) self._utils.savefile(_fin, self.arg.outfile) else: self.parser.error('argument --infile is required') else: _text = self.re_text() if self.arg.verbose or self.arg.debug or self.arg._eval: self._utils.sep('original strint') print(_text) _text = _text.decode('string_escape') if not _text.isdigit(): if self.arg.encode: _fin = self.obfuscator.encode_base(_text) else: _fin = self.obfuscator.zero_base(_text) # <-- next --> if self.arg.stdout: _fin = _choice(STDOUT_BASE).format( self.obfuscator.convert(1), self.obfuscator.convert(2), self.obfuscator.convert(5), self.obfuscator.convert(8), _fin) elif self.arg._exec: _fin = _choice(EXEC_BASE).format( self.obfuscator.zero_base('<string>'), self.obfuscator.zero_base('exec'), self.obfuscator.convert(1), self.obfuscator.convert(95), self.obfuscator.zero_base(_text), self.obfuscator.convert(0)) # <-- NOT --> else: _fin = self.obfuscator.convert(int(_text)) if self.arg.debug or self.arg._eval or self.arg.verbose: self._utils.sep('result') if not self.arg.with_space: _fin = self._utils.fixing(_fin) print(_fin) if self.arg._eval: self._utils.sep('eval') print(eval(_fin)) if self.arg.outfile: self._utils.savefile(_fin, self.arg.outfile) else: print(BANNER) self.parser.print_usage()
def zero_base(self, x): if x != '': template = _choice(ZERO_BASE) else: template = _choice(NULL_STR) return template.format(self.convert(0), self.en_words(x))
def chooseDirection(self): if self.cur_dir_collide(): self.directions.pop(self.direction) self.direction = _choice(list(self.directions.keys()))
def get_word(self): if self.words is None: self._parse_file() return _choice(self.words)
def _full_name(): """生成名字""" return _random_str(1, _last_names) + _random_str(_choice(range(1, 3)), _first_names)
def serpentin_iteration( A: _np.ndarray, B: _np.ndarray, threshold: float = DEFAULT_THRESHOLD, minthreshold: float = DEFAULT_MIN_THRESHOLD, triangular: bool = False, force_symmetric: bool = False, verbose: bool = True, offset: int = 0, ) -> Tuple[_np.ndarray, _np.ndarray, _np.ndarray]: """Perform a single iteration of serpentin binning Each serpentin binning is generally executed in multiple iterations in order to smooth the random variability in the bin aggregation. This funciton performs a single iteration. Parameters ---------- A, B : array_like The matrices to be compared. threshold : float, optional The threshold of rebinning for the highest coverage matrix. minthreshold : float, optional The threshold for both matrices triangular : bool, optional Set triangular if you are interested in rebin only half of the matrix (for instance in the case of matrices which are already triangular, default is false) force_symmetric : bool, optional Force the final binned matrix to be symmetric. Default is False. verbose : bool, optional Set it false if you are annoyed by the printed output. offset : int, optional Diagonals to ignore when performing the binning. Returns ------- Amod, Bmod : array_like The rebinned matrices D : array_like The log-ratio matrix, expressend in base 2. Attention, the matrix need to be normalized by subtractiong an appropriate value for the zero (MDbefore or numpy.mean functions are there to help you in this task). """ if triangular: try: assert A.shape == B.shape assert len(A.shape) == 2 assert min(A.shape) == max(A.shape) except AssertionError: raise ValueError( "Matrices must be square and have identical shape" ) else: try: assert A.shape == B.shape assert len(A.shape) == 2 except AssertionError: raise ValueError("Matrices must have identical shape") try: assert minthreshold < threshold except AssertionError: raise ValueError("Minimal threshold should be lower than maximal") def pixel_neighs_triangular(i, j, size): if i > 0: if i - 1 >= j: yield (i - 1, j) if i < size - 1: if i + 1 >= j: yield (i + 1, j) if j > 0: if i >= j - 1: yield (i, j - 1) if j < size - 1: if i >= j + 1: yield (i, j + 1) def pixel_neighs(i, j, w, h): if i > 0: yield (i - 1, j) if i < w - 1: yield (i + 1, j) if j > 0: yield (i, j - 1) if j < h - 1: yield (i, j + 1) size = A.shape U = _np.copy(A) V = _np.copy(B) U = U.reshape((size[0] * size[1])) V = V.reshape((size[0] * size[1])) if triangular: pixels = [ _np.array([i * size[0] + j], dtype=_np.int32) for (i, j) in _it.product(range(size[0]), range(size[0])) if i >= j and abs(i - j) >= offset ] neighs = [ set( int((a * (a + 1) / 2)) + b for (a, b) in pixel_neighs_triangular(i, j, size[0]) ) for (i, j) in _it.product(range(size[0]), range(size[0])) if i >= j and abs(i - j) >= offset ] start = int(size[0] * (size[0] + 1) / 2) tot = start else: pixels = [ _np.array([i * size[1] + j], dtype=_np.int32) for (i, j) in _it.product(range(size[0]), range(size[1])) if abs(i - j) >= offset ] neighs = [ set( (a * size[1]) + b for (a, b) in pixel_neighs(i, j, size[0], size[1]) ) for (i, j) in _it.product(range(size[0]), range(size[1])) if abs(i - j) >= offset ] start = size[0] * size[1] tot = start previous_existent = 0 current_existent = 1 def print_iteration(i, tot, start, verbose): if not verbose: return percent = 100 * float(tot) / start iteration_string = "{}\t Total serpentines: {} ({} %)".format( i, tot, percent ) print(iteration_string) # merger i = 0 while current_existent != previous_existent: print_iteration(i, tot, start, verbose) i += 1 tot = 0 for serp in _np.random.permutation(range(len(pixels))): if pixels[serp] is not None: tot += 1 # choose where to expand if pixels[serp].size == 1: # Optimization for performances a = U[(pixels[serp])[0]] b = V[(pixels[serp])[0]] else: a = _np.sum(U[pixels[serp]]) b = _np.sum(V[pixels[serp]]) thresh = a < threshold and b < threshold minthresh = a < minthreshold or b < minthreshold if thresh or minthresh: try: min_neigh = _choice(tuple(neighs[serp])) except IndexError: break # Merge pixels pixels[serp] = _np.concatenate( (pixels[serp], pixels[min_neigh]), axis=0 ) # Merge neighbours (and remove self) neighs[serp].remove(min_neigh) neighs[min_neigh].remove(serp) neighs[serp].update(neighs[min_neigh]) # Update neighbours of merged for nneigh in neighs[min_neigh]: neighs[nneigh].remove(min_neigh) neighs[nneigh].add(serp) # Delete merged serpentin pixels[min_neigh] = None neighs[min_neigh] = None previous_existent = current_existent current_existent = sum((serp is not None for serp in pixels)) print_iteration(i, tot, start, verbose) if verbose: print("{}\t Over: {}".format(i, _datetime.now())) pix = (p for p in pixels if p is not None) U = U.astype(_np.float32) V = V.astype(_np.float32) for serp in pix: U[serp] = _np.sum(U[serp]) * 1.0 / len(serp) V[serp] = _np.sum(V[serp]) * 1.0 / len(serp) U = U.reshape((size[0], size[1])) V = V.reshape((size[0], size[1])) if triangular: Amod = ( _np.tril(U) + _np.transpose(_np.tril(U)) - _np.diag(_np.diag(_np.tril(U))) ) Bmod = ( _np.tril(V) + _np.transpose(_np.tril(V)) - _np.diag(_np.diag(_np.tril(V))) ) trili = _np.tril_indices(_np.int(_np.sqrt(Bmod.size))) D = _np.zeros_like(Bmod) D[trili] = V[trili] * 1.0 / U[trili] D[trili] = _np.log2(D[trili]) # elif force_symmetric: # Amod = (U + U.T) / 2 # Bmod = (V + V.T) / 2 # D = V * 1.0 / U # D = _np.log2(D) else: Amod = U Bmod = V D = V * 1.0 / U D = _np.log2(D) return (Amod, Bmod, D)
def __str__(self): return str(_choice(self.sides))
def string(stringLength=10): """Generate a random string of fixed length """ # https://pynative.com/python-generate-random-string/ letters = _ascii_uppercase return "".join(_choice(letters) for i in range(stringLength))
def _get_random_start_frame(frames: list): return _choice([frame[0] for frame in frames if frame[0][0] == _START])