def fetch(self): places = [] response = requests.get(self.url) if response.status_code != 200: raise Exception("url {!r} failed with status code {}".format(self.url, response.status_code)) for line in response.text.splitlines(): line = line.rstrip() if line == "": continue name, latitude, longitude = line.split('\t') places.append(Location(name, float(longitude), float(latitude))) return places
def __init__(self, field, measure, barrier): threading.Thread.__init__(self) self.field = field self.measure = measure self.barrier = barrier while True: location = Location(random.randint(0, self.field.height - 1), random.randint(0, self.field.width - 1)) if self.field.getLocation(location) == 0: self.field.place(location) self.location = location break
def register_loc(x, y): # region_server_no # db[serverno] #rxy = region(x, y) loc = Location(x, y) d = locs.dbarray(loc) #TODO: loc ORM d.append(loc) print(repr(d)) return jsonify({'ok': 'ok'})
def __setitem__(self, item: Location, value: Tile): if isinstance(item, list) or isinstance(item, tuple): # They pass in a list instead of a tuple item = Location(item) if not isinstance(item, Location): raise IndexError( f"You must index a {World.__name__} at a {Location.__name__}, not '{item}'!" ) self.grid[item.y - 1][item.x - 1] = value
def _IsAnIncrementalUpgradeItemAvaliableInAShop(self) -> bool: for cave_type in [ CaveType.SHOP_A, CaveType.SHOP_B, CaveType.SHOP_C, CaveType.SHOP_D ]: for position_num in [1, 2, 3]: location = Location(cave_type=cave_type, position_num=position_num) if self.data_table.GetCaveItem( location).IsAnIncrementalUpgradeItem(): return True return False
def get_sound_locations(self, sound_name): req = urllib2.urlopen(self.make_position_url(sound_name)) location_list = json.loads(req.read()) ret_list = list() for location in location_list: position = Point(location["position"]["x"], location["position"]["y"]) ret_list.append(Location(position, location["confidence"])) return ret_list
def read_args(argv): """Check arguments for correctness and parse them.""" ConsoleArgs = namedtuple("ConsoleArgs", ["help", "filename", "start", "end", "bombs"]) if "--help" in argv and argv[1] == "--help" or "-h" in argv and argv[ 1] == "-h": return ConsoleArgs(help=True, filename=None, start=None, end=None, bombs=None) if len(argv) != 9: print("Incorrect arguments. Print --help or -h for more information.") raise ValueError other_args = list(map(int, argv[2:])) other_args = [x - 1 for x in other_args] return ConsoleArgs(help=False, filename=argv[1], start=Location(*other_args[0:3]), end=Location(*other_args[3:6]), bombs=other_args[-1] + 1)
def get_class_locations(self, class_name): req = urllib2.urlopen(self.class_pos_url + "/" + class_name) location_list = json.loads(req.read()) ret_list = list() for location in location_list: position = Point(location["position"]["x"], location["position"]["y"]) ret_list.append(Location(position, location["confidence"])) return ret_list
def _mouse_press_release(where=None, action=None, button=None, in_region=None): """Mouse press/release. :param where: Location , image name or Pattern. :param action: 'press' or 'release'. :param button: 'left','right' or 'middle'. :param in_region: Region object in order to minimize the area. :return: None. """ if isinstance(where, Pattern): needle = cv2.imread(where.get_file_path()) height, width, channels = needle.shape p_top = positive_image_search(pattern=where, region=in_region) if p_top is None: raise FindError('Unable to click on: %s' % where.get_file_path()) possible_offset = where.get_target_offset() if possible_offset is not None: location = Location(p_top.x + possible_offset.x, p_top.y + possible_offset.y) pyautogui.moveTo(location.x, location.y) if action == 'press': pyautogui.mouseDown(location.x, location.y, button) elif action == 'release': pyautogui.mouseUp(location.x, location.y, button) else: location = Location(p_top.x + width / 2, p_top.y + height / 2) pyautogui.moveTo(location.x, location.y) if action == 'press': pyautogui.mouseDown(location.x, location.y, button) elif action == 'release': pyautogui.mouseUp(location.x, location.y, button) elif isinstance(where, str): mouse = Controller() a_match = text_search_by(where, True, in_region) if a_match is not None: location = Location(a_match['x'] + a_match['width'] / 2, a_match['y'] + a_match['height'] / 2) mouse.move(location.x, location.y) if action == 'press': mouse.press(button) elif mouse == 'release': mouse.release(button)
def place(self, *args): if len(args) != 3: # PLACE command takes (X, Y, F) return # check if parameters are valid if (args[0].isnumeric() == False or args[1].isnumeric() == False or not (args[2] in Face.__dict__)): return # parse the parameters to location object and pass it to the robot loc = Location(int(args[0]), int(args[1]), Face[str(args[2])]) if self.is_valid_place(loc): self.robot.place(loc)
def addTail(self): tail = self.body[-1] print(tail) d = tail.cube.getDirection() if d == const.downDir: newTail = Node( Cube( 10, Location(tail.cube.getLocationX(), tail.cube.getLocationY() - 10), './images/snake-image.png'), tail) if d == const.upDir: newTail = Node( Cube( 10, Location(tail.cube.getLocationX(), tail.cube.getLocationY() + 10), './images/snake-image.png'), tail) if d == const.leftDir: newTail = Node( Cube( 10, Location(tail.cube.getLocationX() + 10, tail.cube.getLocationY()), './images/snake-image.png'), tail) if d == const.rightDir: newTail = Node( Cube( 10, Location(tail.cube.getLocationX() - 10, tail.cube.getLocationY()), './images/snake-image.png'), tail) self.body.append(newTail) self.body[-1].cube.updateDirection( self.body[-1].forward.cube.getDirection())
def get_bombs(data): bombs = [] for bombData in data['Bombs']: roundsUntilExplodes = int(bombData['RoundsUntilExplodes']) parsedLocation = get_location_from_string(bombData['Location']) location = Location(parsedLocation[0], parsedLocation[1]) explosionRadius = int(bombData['ExplosionRadius']) bomb = Bomb(roundsUntilExplodes, location, explosionRadius) bomb.print_debug() bombs.append(bomb) return bombs
def test_rover_can_turn(self): grid = Grid(3, 3) location = Location(grid, 0, 0, direction.W) rover = Rover(location) rover.move(command.R) self.assert_location(rover.location, 0, 0, direction.N) rover.move(command.L) self.assert_location(rover.location, 0, 0, direction.W) rover.move(command.L) self.assert_location(rover.location, 0, 0, direction.S)
def setLocation(mm, mutex, degrees, azim, distance): loc = Location() loc.degrees = degrees loc.azim = azim loc.distance = distance json_data = (json.dumps( (loc.degrees, loc.azim, loc.distance), ensure_ascii=False) + '\n') with mutex: mm.seek(0) mm.write(json_data) logging.debug("degrees: " + str(loc.degrees) + " azimuth: " + str(loc.azim) + " distance: " + str(loc.distance))
def Search(self, lat, lng, radiusMeters): """ Returns items within the provided radius. The operation is performed on object's container. """ if abs(lat) > 90 or abs(lng) > 180 or radiusMeters <= 0: raise ValueError loc1 = Location(lat, lng) results = [] for item in self.container: if CoordinateHelper.GetDistanceMeters( loc1, item.Location) <= radiusMeters: results.append(item) return results
def __init__(self, simulation, name, colour, strategy=""): self.location = Location() self.simulation = simulation if strategy == "": self.random_strategy() else: self.strategy = strategy self.name = name self.colour = colour # random_colour() ??? self.voters = [] self.previous_count = -1
def update_location_aggregator(self): if len(self.voters) > 0: sum_x = 0 sum_y = 0 for voter in self.voters: sum_x += voter.location.x sum_y += voter.location.y target_location = Location() target_location.set_x(sum_x / len(self.voters)) target_location.set_y(sum_y / len(self.voters)) self.location.move_towards(target_location)
def decode(self, reader): """ :param reader: :return: """ if not reader: return self.type = reader.read_byte() if self.type == -9: # All sides self.location = Location(reader) self.to = reader.read_ubyte() elif self.type == -23: # one side self.location = Location(reader) self.side = reader.read_ubyte() self.to = reader.read_ubyte() elif self.type == -19: # change party direction self.direction = reader.read_ubyte()
def __init__(self, name, retType, attrs, args): self.name = name self.isExported = hasAttr(attrs, "attr_export") self.isImported = hasAttr(attrs, "attr_import") self.isAlwaysRecursion = hasAttr(attrs, "attr_always_recursion") self.args = [a.children[0] for a in args] # type self.paramVars = {Location(str(a.children[1])): (a.children[0], i) for i,a in enumerate(args)} self.retType = retType self.localVars = {} self.maxTempVarIndex = -1 self.section = getSection(attrs, DEFAULT_CODE_SECTION) if self.isExported and self.isImported: raise ValueError("A function can't be exported and imported at the same time")
def testNehdaiJaisalmerRajasthan(self): lc = Location(state="Rajasthan", district="Jaisalmer") nehdai_cord = lc.getCoordinates(query="Nehdai", listLength=1)[0] nehdai_expected = Coordinates(lat=27.402876, lng=70.995243, state="Rajasthan", district="Jaisalmer", sub_district="Jaisalmer", level="Village", name="NEHDAI") self.assertEqual( nehdai_cord, nehdai_expected, "Cordinates didnot Match for Nehdai, (JSM) Rajasthan")
def setUp(self): start_time = datetime.datetime(2000, 1, 1, 6, 0) end_time = datetime.datetime(2000, 1, 1, 10, 0) self.duration = Duration(start_time, end_time) self.group = Group(0, 'TestGroup') self.location = Location(0, 'TestLoction') self.category = Category(0, 'TestCategory') good_tasks = [ Task(0, 'TestTask', self.duration, 8, self.group, self.location, self.category) ] generic = CommonTestFunctions() self.good_role = generic.role(good_tasks, name='Role', id=1)
def update_location_table(spreadsheet): ''' This method is used to push the changes from the location spreadsheet to the database. It includes addition, updation and deletion of data. :spreadsheet object: the access to google spreadsheet. ''' location = spreadsheet.get_worksheet(2) update_list = location.col_values(1) update_list = update_list[1:] for _id, state in enumerate(update_list, 1): location = Location(_id, state) location.insert_to_location()
def get_locations(param): # TODO add docstring api_url = f"{api_url_base_geocode}{param}.json?key={api_key}" logger.info("Api url: " + api_url_base_geocode) response = requests.get(api_url) if response.status_code == 200: global data_json global location_count global locations data_json = json.loads(response.content.decode("utf-8")) location_count = int(data_json["summary"]["numResults"]) locations = [] if location_count > 0: for i in data_json["results"]: loc_tmp = Location( location_id=i["id"].replace("/", "_"), address=i["address"]["freeformAddress"], country=i["address"]["country"], country_subdivision=None, country_secondary_subdivision=None, country_subdivision_name=None, latitude=i["position"]["lat"], longitude=i["position"]["lon"], locType=i["type"], ) if i["address"].get("country_subdivision") is not None: loc_tmp.country_subdivision = i["address"]["country_subdivision"] if i["address"].get("country_secondary_subdivision") is not None: loc_tmp.country_secondary_subdivision = i["address"][ "country_secondary_subdivision" ] if i["address"].get("country_subdivision_name") is not None: loc_tmp.country_subdivision_name = i["address"][ "country_subdivision_name" ] locations.append(loc_tmp) return response.status_code else: return 204 # HTTP No content else: logger.error("Error response code: " + response.status_code) return response.status_code
def _add_missiles(self): for missile in self.battlefieldInfo.missiles: radius = missile.explosionRadius node = self.nodes[missile.location.x][missile.location.y] if missile.moveDirection == MoveDirection.Up: vector = (0, -1) elif missile.moveDirection == MoveDirection.Right: vector = (1, 0) elif missile.moveDirection == MoveDirection.Down: vector = (0, 1) elif missile.moveDirection == MoveDirection.Left: vector = (-1, 0) # Go through nodes untill inavailable node is found so it means # that's the target of a missile location = node.location while self.nodes[location.x][location.y].metadata.isAvailable == True: # The trajectory of missile is available to go through self.nodes[location.x][location.y].metadata.markMissile(isAvailable=False) col = max(0, min(location.x + vector[0], self.mapWidth - 1)) row = max(0, min(location.y + vector[1], self.mapHeight - 1)) if ((row == 0 and vector[1] == -1) or (row == self.mapHeight - 1 and vector[1] == 1) or (col == 0 and vector[0] == -1) or (col == self.mapWidth - 1 and vector[0] == 1)): self.nodes[location.x][location.y].metadata.markMissile(isAvailable=False) location = Location(col, row) # mark missile position as unavailable self.nodes[missile.location.x][missile.location.y].metadata.markMissile(isAvailable=False) # Mark missile explosion for offset in range(0, radius + 1): explodingNodes = [ self.nodes[max(0, location.x - offset)][location.y], self.nodes[min(location.x + offset, self.mapWidth - 1)][location.y], self.nodes[location.x][max(0, location.y - offset)], self.nodes[location.x][min(location.y + offset, self.mapHeight - 1)] ] for explodingNode in explodingNodes: explodingNode.metadata.markMissile(isAvailable=False)
def decode(self, reader): """ :param reader: :return: """ if not reader: return self.type = reader.read_byte() self.item_id = reader.read_ushort() self.location = Location(reader) self.direction = reader.read_ubyte() self.sub_position = reader.read_ubyte()
def jump(self, jump_speed): ''' Makes the player jump. ''' self.jump_speed = jump_speed if not self.is_destroyed(): if self.check_up_or_down(UP, Player.STEP * self.jump_speed): new_y = self.get_location().get_y( ) - Player.STEP * self.jump_speed coordinates = Location(self.get_location().get_x(), new_y, self.game) self.set_location(coordinates) else: self.jump_speed = 0
def __init__(self, identifier, location_xy): """Initialize function for Event class""" self.id = identifier self.tickets = [] try: self.location = Location(location_xy) except ValueError: print( "Either incorrect number of parameters provided to unpack for location or incorrect type used." ) exit(0) self.distancesToLocation = {}
def setup_locations(self): file = "data/locations.csv" list_of_locations = [] with open(file, newline='', encoding='utf-8-sig') as locations_file: reader = csv.reader(locations_file) # SPACE | TIME COMPLEXITY: # O(N) | O(N) for row in reader: location = Location(row[0].strip(), row[1].strip(), row[2].strip(), row[3].strip(), row[4].strip()) list_of_locations.append(location) return list_of_locations
def init_locations(self): url = "https://lax-gateway.appspot.com/" \ "_ah/api/lacrosseClient/v1.1/active-user/locations" headers = {"Authorization": "Bearer " + self.token} r = requests.get(url, headers=headers) if r.status_code < 200 or r.status_code >= 300: raise ConnectionError("failed to get locations ()". format(r.status_code)) body = r.json() for loc in body.get('items'): self.locations.append(Location(loc)) if not self.locations: raise Exception("Unable to get account locations") return True
def addLocation(self, request, locationDao): locationDic = None keys = ['location_qrcode', 'email', 'auth_token', 'description'] try: locationDic = self.helperHandler.handleRequestAndAuth( request, keys) except Exception as e: return json.dumps({"success": False, "message": str(e)}) locationDic['lastPickup'] = datetime.now().strftime( '%Y-%m-%d %H:%M:%S') location = Location() location.dictToLocation(locationDic) res = self.locationdao.insertLocation(location) return self.helperHandler.handleResponse(res)