def isvalid(x_new, x_near, constraints, obstacles): l = line(x_new, x_near) if isinstance(constraints, list): isinside = any(contains(c, x_new) for c in constraints) else: isinside = contains(constraints, x_new) return isinside and \ all(not obs.contains(l) for obs in obstacles)
def nice_print(str, option=[]): for n in range(len(str)): pp(str[n], option) if not params.term_immediate and util.contains(option, 'beep'): beep() if not params.term_immediate and not util.contains( option, 'immediate'): time.sleep(0.05) if not params.term_immediate and util.contains(option, 'pause'): time.sleep(0.5) reset_color()
def _get_media_data(url): if contains(r'^https?://(www\.)?gfycat\.com', url): #if gfycat gif, deals with http and https sites url = url.replace('gfycat.com', 'giant.gfycat.com').replace('www.', '') + '.mp4' if contains(r'^https?://(?:i\.)?imgur\.com/.+?\.gifv', url): #if imgur gifv url = url.replace('.gifv', '.mp4') format = _get_format(url, _IMG_FILES + _VIDEO_FILES) if format: #if the media is in one of the acceptable formats response = get(url) if response.status_code == 200: #make sure we got the content properly return {'data': response.content, 'format': format} else: #if there was a bad status code don't download the content print "GOT A WEIRD STATUS CODE: {0}".format(response.status_code) return None
def build_tree(self, x_init, goal, t_init=None, iters=-1): if t_init is None: t = Tree(x_init) else: t = t_init cur = t while not contains(goal, cur.node) and iters != 0: x_random = self.pick_random() x_near_tree = nearest(t, x_random) x_near = x_near_tree.node v = x_random - x_near vnorm = np.linalg.norm(v) if vnorm > self.dx: x_new = x_near + self.dx * v / vnorm else: x_new = x_random if isvalid(x_new, x_near, self.constraints, self.obstacles): cur = Tree(x_new) x_near_tree.add_child(cur) g = connect(x_new, goal, self.constraints, self.obstacles) if g is not None: g_tree = Tree(g) cur.add_child(g_tree) cur = g_tree iters -= 1 return t, cur
def visit_function(self,function_): function = copy.deepcopy(function_) name = cpp_file_parser.get_function_name_for_type_erasure(function) function_pointer_alias = name + '_function' function_pointer_alias_definition = 'using ' + function_pointer_alias + ' = ' index, offset = cpp.find_function_name(function.name, function.tokens) returns_self = util.contains(function.tokens[:index], function.classname) returns_self_by_reference = cpp.contains_sequence(function.tokens[:index], [cpp.SimpleToken(function.classname), cpp.SimpleToken('&')]) if returns_self: cpp_file_parser.replace_in_tokens(function.classname, self.data.interface_type, function.tokens[:index]) function_pointer_alias_definition += util.concat(function.tokens[:index], ' ') function_pointer_alias_definition += '( * ) ( ' if returns_self_by_reference: interface_type = ('const ' if cpp.is_const(function) else '') + self.data.interface_type + ' &' function_pointer_alias_definition += interface_type + ' , ' function_pointer_alias_definition += 'void * ' arguments = cpp.get_function_arguments(function) adjust_table_arguments_tokens(function.classname, arguments) for arg in arguments: function_pointer_alias_definition += ' , ' + arg.in_declaration() # Seems to be redundant, TODO Verify #start_index = cpp_file_parser.get_arguments_end_index(function.name, function.tokens) #end_index = cpp_file_parser.get_declaration_end_index(function.name, function.tokens) #for token in function.tokens[start_index:end_index]: # if token.spelling not in ['const','noexcept']: # function_pointer_alias_definition += token.spelling + ' ' function_pointer_alias_definition += ');' self.scope.add(cpp_file_parser.get_alias_from_text(function_pointer_alias, function_pointer_alias_definition)) self.scope.add(cpp.Variable(function_pointer_alias + ' ' + name + ';'))
def move(self, player, x, y): """Puts a tile at the specified coordinates and makes sure all game rules are followed. """ pkey = player.key() if pkey not in self.players: raise MoveError('Player not in game.') if self.state != 'playing': raise MoveError('Game not in play.') whose_turn = self.current_player player_turn = self.players.index(pkey) + 1 if whose_turn != player_turn: raise MoveError('Not player\'s turn.') rs = self.rule_set np = rs.num_players m, n, k, p, q = rs.m, rs.n, rs.k, rs.p, rs.q board = self.unpack_board() if (x < 0 or x >= m or y < 0 or y >= n or board[x][y]): raise MoveError('Invalid tile position.') board[x][y] = whose_turn # Next turn. self.turn += 1 # There's a win according to the rule set. if rs.is_win(board, player_turn, x, y): self.state = 'win' player.wins += 1 player.put() for pkey in self.players: if pkey == player.key(): continue p = db.get(pkey) p.losses += 1 p.put() self.rule_set.num_games += 1 self.rule_set.put() # Board has been filled; draw. elif not util.contains(board, 0): self.state = 'draw' for pkey in self.players: p = db.get(pkey) p.draws += 1 p.put() self.rule_set.num_games += 1 self.rule_set.put() else: self.current_player = rs.whose_turn(self.turn) self.put(True)
def getSpectrum(self, energyResolution = 10**(-10)): degeneracies = list() energies = list() for e in self.eigenEnergies: if contains(energies, e, energyResolution): degeneracies[getIndex(energies, e, energyResolution)] += 1 else: degeneracies.append(1) energies.append(e) return energies, degeneracies
def calculate_busiest_time(key_values_dict, key_value): key, value = key_value.strip().split("\t", 1) entries, date, time = value.strip().split('\t') entries_num = float(entries) entry_time = datetime.strptime(date + "T" + time, "%Y-%m-%dT%H:%M:%S") keys = list(key_values_dict) current_count = key_values_dict[key] if contains(keys, key) else (0.0, datetime(1970,1,1)) entry_high = current_count if current_count[0] > entries_num or (current_count[0] == entries_num and current_count[1] > entry_time) else (entries_num, entry_time) key_values_dict[key] = entry_high return key_values_dict
def expand_tree(region, obstacles, t, goal, dx, eps, t_max, explored=None, iters=50): cur = t while not contains(goal, cur.node): cur = explore(region, obstacles, t, goal, dx, iters) if contains(goal, cur.node): break for node in t.flat(): if connect_to_explored(node, explored, region, obstacles): logger.debug("Connected") break if isinstance(goal, Box): exclude = goal.corners() else: exclude = goal if len(explored) > 0: exclude = np.vstack([exclude] + [x.nodes() for x in explored]) logger.debug("Included:\n{}".format(np.array(t.nodes()).__repr__())) logger.debug("Exluded:\n{}".format(exclude.__repr__())) exp_region = cover(np.array(t.nodes()), exclude, eps) # util.plot_casestudy2(region, goal, obstacles, t, region) try: cur, explored_tree = connect_to_expansion( exp_region, region, obstacles, t, goal, dx, eps, t_max, explored, iters) if any(contains(goal, x) for x in explored_tree.nodes()): cur = explored_tree.find( next(x for x in explored_tree.nodes() if contains(goal, x))) break except DRMNotConnected: raise DRMNotConnected(t) return t, cur
def derive_dl(distances): distances = Counter(distances) X = set([0]) width = max(distances) while len(distances) > 0: y = max(distances) if contains(dist(y, X), distances): X |= frozenset([y]) distances -= dist(y, X) else: X |= frozenset([width - y]) distances -= dist(width - y, X) return sorted(X)
def is_central(rect, point, percentage): """Returns True if a point is somewhere in the center of a rectangle `percentage` percentage per dimension of the rectangle that is considered central. `rect` = (xTL, yTL, xBR, yBR) tuple `point` = (x, y) tuple """ # Define a rectangle that's the center of the input rectangle x1, y1, x2, y2 = rect h, w = y2 - y1, x2 - x1 central_rect = ( x1 + w * (.5 - percentage/2), y1 + h * (.5 - percentage/2), x1 + w * (.5 + percentage/2), y1 + h * (.5 + percentage/2), ) central_rect = tuple(map(int, central_rect)) return util.contains(central_rect, point)
def one_vs_all(bb, CG): """Window is positive if it contains the CG, negative otherwise """ return util.contains(bb, CG)
while True: t = clock() ret, img = cam.read() with the_lock: low_image[:] = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) low_image[:] = cv2.equalizeHist(low_image) if high_proc is None: high_proc = mp.Process(target=high_level_tracker, args=(low_image, stopping, the_lock, possible_targets, cascade,)) high_proc.start() with the_lock: if len(possible_targets) > 0: for rect in possible_targets: if contains(targets, rect): continue targets.append((rect, 0, np.zeros(2), 0)) possible_targets[:] = [] vis = img.copy() next_targets = [] for rect, misses, velocity, karlness in targets: x1, y1, x2, y2 = rect with the_lock: roi = low_image[max(0, y1-BUFFER):min(width, y2+BUFFER), max(0, x1-BUFFER):min(height, x2+BUFFER)] # draw_rects(vis, [[max(0, x1-BUFFER), max(0, y1-BUFFER), min(height, x2+BUFFER), min(width, y2+BUFFER)]], (255,0,0)) subt = clock()
if high_proc is None: high_proc = mp.Process(target=high_level_tracker, args=( low_image, stopping, the_lock, possible_targets, cascade, )) high_proc.start() with the_lock: if len(possible_targets) > 0: for rect in possible_targets: if contains(targets, rect): continue targets.append((rect, 0, np.zeros(2), 0)) possible_targets[:] = [] vis = img.copy() next_targets = [] for rect, misses, velocity, karlness in targets: x1, y1, x2, y2 = rect with the_lock: roi = low_image[max(0, y1 - BUFFER):min(width, y2 + BUFFER), max(0, x1 - BUFFER):min(height, x2 + BUFFER)]
def visit_function(self,function_): function = copy.deepcopy(function_) name = cpp_file_parser.get_function_name_for_type_erasure(function) index, offset = cpp.find_function_name(function.name, function.tokens) returns_self = util.contains(function.tokens[:index], function.classname) returns_self_by_reference = cpp.contains_sequence(function.tokens[:index], [cpp.SimpleToken(function.classname), cpp.SimpleToken('&')]) if returns_self: cpp_file_parser.replace_in_tokens(function.classname, self.data.interface_type, function.tokens[:index]) arguments = copy.deepcopy(cpp.get_function_arguments(function)) wrapper = 'static ' + util.concat(function.tokens[:index], ' ') wrapper += name + ' ( ' if returns_self_by_reference: wrapper += cpp_file_parser.const_specifier(function) + self.data.interface_type + ' & ' + self.data.interface_variable + ' , ' wrapper += ' void * impl ' for arg in arguments: if cpp_file_parser.contains(function.classname, arg.tokens): wrapper += ' , void * ' + arg.tokens[-1].spelling else: wrapper += ' , ' + arg.in_declaration() wrapper += ' ) ' if 'noexcept' in function.tokens[cpp.get_arguments_end_index(function.name, function.tokens): cpp.get_declaration_end_index(function.name, function.tokens)]: wrapper += 'noexcept ' wrapper += '{ ' returns_class_ref = cpp.returns_class_ref(self.data.interface_type, function) if not returns_class_ref: wrapper += function.return_str + ' ' wrapper += 'static_cast ' const = 'const ' if cpp.is_const(function) else '' if self.for_reference_wrapper: wrapper += '< std :: reference_wrapper < Impl > * > ( impl ) -> get ( ) . ' else: wrapper += '< ' + const + ' Impl * > ( impl ) -> ' wrapper += function.name + ' ( ' for arg in arguments: if cpp_file_parser.contains(function.classname, arg.tokens): typename = util.concat(arg.tokens[:-1], ' ') typename = typename.replace(' ' + function.classname + ' ', ' Impl ') if self.for_reference_wrapper: if typename.endswith('* '): wrapper += '& ' wrapper += 'static_cast < std :: reference_wrapper < Impl > * > ( ' + arg.in_single_function_call() wrapper += ' ) -> get ( )' else: if typename.endswith('& '): wrapper += '* ' wrapper += 'static_cast< ' + ('const ' if cpp.is_const(function) else '') wrapper += 'Impl * > ( ' + arg.in_single_function_call() + ' )' else: wrapper += arg.in_single_function_call() if arg is not arguments[-1]: wrapper += ' , ' wrapper += ' ) ; ' if returns_class_ref: wrapper += 'return interface ; ' wrapper += '}' self.scope.add(cpp_file_parser.get_function_from_text('execution_wrapper', name, function.return_str, wrapper))
def configured( self ): return ( self.scanUnit is not None and self.scanUnit.configured and self.scanInput is not None and contains( self.scanUnit, self.scanInput ) )
def _get_format(link, file_types): for t in file_types: if contains(r'\.' + t + r'$', link): return t return None
def is_img(path): for t in _IMG_FILES: if contains(r'\.' + t + r'$', path): return True return False