def updatePoint(self, point: Point) -> Point: if len(point.id) != 24: return point col = self.getColl(point.mapId) result = col.update_one({'_id': ObjectId(point.id)}, {'$set': point.toDBMap()}, upsert=True) if result.upserted_id: point.id = str(result.upserted_id) path = edgeDao.findEdgeByPointAId(point.id, point.mapId) for item in path: item.pointA = { 'id': point.id, 'planCoordinate': point.planCoordinate, 'actualCoordinate': point.actualCoordinate } edgeDao.updateEdge(item) path = edgeDao.findEdgeByPointBId(point.id, point.mapId) for item in path: item.pointB = { 'id': point.id, 'planCoordinate': point.planCoordinate, 'actualCoordinate': point.actualCoordinate } edgeDao.updateEdge(item) return point
def __parse_base(self, item, city_name, point_type): point = Point() point.prov = self.uid point.type = point_type point.phones = [normalize_phone(item('.content_table table tbody tr:eq(0) td:eq(0) .office_phone').remove().text())] name_address_html = replace_br(item('.content_table table tbody tr:eq(0) td:eq(0)').remove().html(), ',') name, address = PQ(name_address_html).text().split(',', 1) point.name = normalize_text(name) point.address, point.place = self.__get_address(city_name, address) point.check_information = CHECK_OFFICIAL script_text = item('.ya_map script:eq(1)').text() for line in map(strip, script_text.splitlines()): if line.startswith('BX_GMapAddPlacemark('): lat_token = "'LAT':'" lat_start_index = line.find(lat_token) + len(lat_token) lat_end_index = line.find("'", lat_start_index) point.lat = line[lat_start_index:lat_end_index] lng_token = "'LON':'" lng_start_index = line.find(lng_token) + len(lng_token) lng_end_index = line.find("'", lng_start_index) point.lng = line[lng_start_index:lng_end_index] point.check_coordinates = CHECK_OFFICIAL break else: warning_not_official_coordinates(point) return point
def __parse_terminal(self, item): point = Point() point.prov = self.uid point.type = TYPE_TERMINAL city = normalize_text(item('td:eq(0)').text()) address = normalize_text(item('td:eq(2)').text()) point.address, point.place = split_address_place(u'г. %s, %s' % (city.title(), address)) point.place = normalize_text(item('td:eq(1)').text()) point.time = normalize_time(item('td:eq(3)').text()) point.check_information = CHECK_OFFICIAL for lat, lng, type_id, description in self.__get_coordinates(): if u'Минск' not in point.address or type_id != '2': continue for token in description.split(): if token not in point.address: break else: point.lat = lat point.lng = lng point.check_coordinates = CHECK_OFFICIAL break else: warning_not_official_coordinates(point) return point
def weakestDirection(self, point): """ 4方向の中で1番自分陣営の攻撃力が弱いポイント """ directions = [Point(0, 1), Point(0, -1), Point(1, 0), Point(-1, 0)] d = min(directions, key=lambda d: self.damage(point.plus(d))) return point.plus(d)
def __init__(self, width, height, player_vision): self.map_width = width self.map_heigth = height self.start_point = Point(0,0) self.finish_point = Point(self.map_width-1, self.map_heigth-1) self.player_vision = player_vision self.restart_game = False
def __get_offices(self, url, city_name=''): points = [] page = PQ(get_url(url).decode('utf8')) time = None for item in map(PQ, page('#oo__content_value table tr:gt(0)')): if item('td').attr('colspan') == '3': continue point = Point() point.prov = self.uid point.type = TYPE_OFFICE point.name = normalize_text(item('td:eq(0)').text()) point.address = normalize_address(city_name + item('td:eq(1) p:eq(0)').text()) place = item('td:eq(1) p:eq(2)').text() if not place: place = item('td:eq(1) p:eq(1)').text() if place: point.place = normalize_text(place) new_time = item('td:eq(2)').text() if new_time: time = new_time point.time = normalize_time(time) point.check_information = CHECK_OFFICIAL if point.address in self.__addresses: point.lat, point.lng = self.__addresses[point.address] point.check_coordinates = CHECK_OFFICIAL else: warning_not_official_coordinates(point) points.append(point) return points
def __parse_base(self, item, city, point_type): point = Point() point.prov = self.uid point.type = point_type point.name = normalize_text(item('.b-map-side>h5').text()) point.address, point.place = split_address_place(u'г. %s, %s' % (city, item('.b-map-side>p span:eq(0)').text())) coordinates = item('.b-map-side>p span:eq(1)').text() if coordinates: point.lat, point.lng = map(strip, coordinates.split(',')) text_html = replace_br(item('.b-map-side-more').html(), ';;;') time_items = [] for sub_item in map(normalize_text, PQ(text_html).text().split(';;;')): if not sub_item: continue if sub_item.startswith(u'Телефон:'): point.phones = normalize_phones(sub_item[len(u'Телефон:')].split(',')) continue time_items.append(sub_item) point.time = normalize_time(', '.join(time_items)) point.check_information = CHECK_OFFICIAL if point.lat and point.lng: point.check_coordinates = CHECK_OFFICIAL else: warning_not_official_coordinates(point) return point
def handle_options(self): self.map_width = self.map_info['width'] self.map_height = self.map_info['height'] self.start_position = Point(self.s_pos['x'], self.s_pos['y']) self.player_position = self.start_position self.player_vision = self.player_info['player-vision'] self.exit_position = Point(self.f_pos['x'], self.f_pos['y'])
def calculateGravity(pointList): # 重心坐标 gravity = Point() p1 = pointList[0] p2 = pointList[1] x1 = p1.x y1 = p1.y sum_x = 0 sum_y = 0 sum_area = 0 for i in range(2, len(pointList)): x2 = p2.x y2 = p2.y p3 = pointList[i] x3 = p3.x y3 = p3.y area = ((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2.0 sum_x += (x1 + x2 + x3) * area sum_y += (y1 + y2 + y3) * area sum_area += area p2 = p3 gravity.x = sum_x / sum_area / 3.0 gravity.y = sum_y / sum_area / 3.0 return gravity
def build_graph_context(graph) -> (Point, Point): # min of both axes using most points with min x and min y points = list(graph.keys()) points.sort(key=lambda x: x[0]) x1, x2 = points[0][0], points[-1][0] points.sort(key=lambda x: x[1]) y1, y2 = points[0][1], points[-1][1] return GraphContext(Point(x1, y1), Point(x2, y2))
def post(self): pointJson = json.loads(self.request.body) point = Point(pointJson['mapId'], pointJson) point = pointService.save(point) if 'name' in pointJson: loc = Loc(pointJson['mapId'], pointJson['name'], pointJson) locService.save(loc) self.write({'code': 0, 'data': point.toJsonMap()})
def aroundStrength(self, point, size): if self._aroundStrength.get((point, size)): return self._aroundStrength[(point, size)] p1 = Point(point.x - size, point.y - size) p2 = Point(point.x + size, point.y + size) self._aroundStrength[(point, size)] = self.rangeStrength(p1, p2) return self._aroundStrength[(point, size)]
def findById(self, id: str, mid: str) -> Point: col = self.getColl(mid) result = col.find_one({'_id': ObjectId(id)}) if result is not None: point = Point(mid, result) point.id = id return point return None
def change_positon(self, char): if char in "wsad": self.set_up_player.change_position(char) if self.read_new_position() == self.finish_point: self.restart_game = True elif char in "r": self.prepared_map.change_player_position(self.read_new_position(),Point(0,0)) self.set_up_player.position = Point(0,0)
class Envelope(object): # 外包矩形的四个顶点 rtPoint = Point() # 右上 lbPoint = Point() # 左下 def __str__(self): return "rt:" + "x:" + bytes(self.rtPoint.x) + " y:" + bytes(self.rtPoint.y) + " lb:" + "x:" + bytes( self.lbPoint.x) + " y:" + bytes(self.lbPoint.y)
def findAll(self, mid: str) -> typing.List[Point]: col = self.getColl(mid) cursor = col.find() result = [] for item in cursor: p = Point(item['mapId'], item) p.id = str(item['_id']) result.append(p) return result
def tiebian(): global sidePoints sidePoints = np.array(sidePoints) yawAim = getYawAim(sidePoints) log.info('已加载导航点,共有%d个点' % len(sidePoints)) index = 0 pos = Point(g.getValue('ship').lat, g.getValue('ship').lng) # 判断刚开始时,是否需要原地转 state = State.TURN if utils.getDistance( pos, Point(sidePoints[0, 0], sidePoints[0, 1])) > 3 else State.GO try: while index < len(sidePoints): yaw = g.getValue('ship').yaw lat = g.getValue('ship').lat lng = g.getValue('ship').lng gz = g.getValue('ship').gz speed = g.getValue('ship').speed pShip = Point(lat, lng) pAim = Point(sidePoints[index, 0], sidePoints[index, 1]) isFirst = True if index == 0 else False if state == State.TURN: thrust = 0 dire = PID_Turn(pShip, pAim, yaw, -gz, yawAim[index], isFirst) if dire == 0: # 转弯完毕,进入直行阶段 state = State.GO elif state == State.GO: # 判断直线段或是曲线段,之后五个点期望角度最大误差 slowSpeed = True if angleArray_ptp( yawAim[index:index + 5]) > 15 or index == 0 else False log.info('Go:当前期望方向角 %.1f 度,slowSpeed是 %s' % yawAim[index], slowSpeed) dire, thrust = PID_Go(pShip, pAim, yaw, -gz, yawAim[index], slowSpeed, isFirst) dist = utils.getDistance(pShip, pAim) if state == State.GO and index > 0: # 将最近点序号作为当前序号 index = index_cal(pShip, index, SearchLength=10) #函数中使用了global量sidePoints log.info('当前处于第 %d 个点' % index) if dist < 1 and index == 0: state = State.TURN index += 1 if index == len(sidePoints): # 跑完 thrust = 0 dire = 0 data = struct.pack("hhb", int(thrust), int(dire), 0) g.getValue("can").send(0x544, data) log.info("%s\t%d\t%.1f\t%.1f\t%d" % (state, index, thrust, dire, dist)) time.sleep(1) except Exception: log.error('贴边Error', exc_info=True) log.info('导航结束')
def __init__(self, map_width, map_heigth, start_position, exit_positon): super().__init__(map_width, map_heigth, start_position, exit_positon) self.populate_walls() self.points_round = defaultdict() self.points_round = { 'up': Point(0, 1), 'right': Point(1, 0), 'down': Point(0, -1), 'left': Point(-1, 0) }
def __parse_base_office_exchange(self, item, point_type, name_keywords): point = Point() point.prov = self.uid point.type = point_type point.name = normalize_text(item('th:eq(0) a:eq(0)').text()) if not point.name.startswith(name_keywords): return None city = normalize_text(item('td:eq(1)').text()) address = normalize_text(item('td:eq(2)').text()) point.address, point.place = split_address_place(u'г. %s, %s' % (city, address)) point.check_information = CHECK_OFFICIAL for lat, lng, type_id, description in self.__get_coordinates(): if u'Минск' not in point.address or type_id != '1': continue for token in description.split(): if token not in point.address and token not in point.name: break else: point.lat = lat point.lng = lng point.check_coordinates = CHECK_OFFICIAL break else: warning_not_official_coordinates(point) return point
def test_local_extrema(self): """function should return array of y indices and array of x indices""" test_array = np.array([[0, 0, 2, 1, 4, 5, 6, 0, 8], [9, 10, 0, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 24, 25, 26], [9, 10, 11, 12, 23, 14, 15, 34, 17], [9, 90, 11, 12, 13, 14, 15, 16, 17], [9, 10, 11, 12, 13, 14, 15, 30, 17]]) self.assertEqual(Point.local_extrema(test_array)[0].tolist(), [3, 3, 4]) self.assertEqual(Point.local_extrema(test_array)[1].tolist(), [4, 7, 1])
def read_from_file(filename, polygons=False): with open(os.path.join('data', filename), "r") as f: objects = [] for coordinates in f.readlines(): if polygons: list_of_pairs = list( zip(*[iter([int(i) for i in coordinates.split()])] * 2)) polygons = Polygon( vertices=[Point(x, y) for x, y in list_of_pairs]) objects.append(polygons) else: point = Point(*[int(i) for i in coordinates.split()]) objects.append(point) return objects
def polygonEnvelope(polygon): # 多边形的顶点序列 partList = polygon.partList # 两个顶点 rt = Point() lb = Point() rt.x = lb.x = partList[0][0].x rt.y = lb.y = partList[0][0].y for i in range(len(partList)): for k in range(len(partList[i])): if partList[i][k].x < lb.x: lb.x = partList[i][k].x if partList[i][k].x > rt.x: rt.x = partList[i][k].x if partList[i][k].y < lb.y: lb.y = partList[i][k].y if partList[i][k].y > rt.y: rt.y = partList[i][k].y envelope = Envelope() envelope.rtPoint = rt envelope.lbPoint = lb return envelope
def main(): points = console_io.get_number_of_points() pie = Pie(Point(50, 50), 90, 50) lines = [] for index in range(points): lines.append(console_io.read_line()) index = 0 for line in lines: index += 1 percent, x, y = list(map(lambda l: int(l), line.split(' '))) is_inside = pie.is_inside(Point(x, y), percent) color = 'black' if is_inside else 'white' console_io.show_result(index, color)
def buildBase(self, workers): halfStrength = self.brain.aStage.enemies.rangeStrength( self.brain.castle.point, Point(SILBER_POINT, SILBER_POINT)) if self.brain.aStage.isStartEnemyAttack and len( self.brain.unit(UnitType.BASE)) < 1 and self.brain.aStage.five: worker = min(workers, key=lambda x: x.point.dist(self.brain.castle.point)) else: zero = Point(60, 60) worker = min(workers, key=lambda x: x.point.dist(zero)) self.brain.actions[worker.cid] = UnitType.BASE.value self.brain.aStage.resourceNum -= Cost[UnitType.BASE] workers.remove(worker)
def populate_borders(self): minus_one = -1 for width in range(-1, self.map_width + 1): bottom_border_wall = Wall(Point(width, minus_one), self) upper_border_wall = Wall(Point(width, self.map_heigth), self) self.walls_positions[ bottom_border_wall.position] = bottom_border_wall self.walls_positions[ upper_border_wall.position] = upper_border_wall for height in range(self.map_heigth): left_border_wall = Wall(Point(minus_one, height), self) right_border_wall = Wall(Point(self.map_width, height), self) self.walls_positions[left_border_wall.position] = left_border_wall self.walls_positions[ right_border_wall.position] = right_border_wall
def __parse_atm(self, item, city, coordinates): point = Point() point.prov = self.uid point.type = TYPE_ATM point.address = normalize_address(u'%s, %s' % (city, item('td:eq(2)').text())) point.place = normalize_text(item('td:eq(1)').text()) point.currency = map(strip, item('td:eq(4)').text().replace('EURO', 'EUR').split(',')) point.time = normalize_time(item('td:eq(3)').text()) point.check_information = CHECK_OFFICIAL point.lat, point.lng = self.__get_point_coordinate(point, coordinates) if point.lat and point.lng: point.check_coordinates = CHECK_OFFICIAL else: warning_not_official_coordinates(point) return point
def __parse_office_main(self, coordinates): point = Point() point.prov = self.uid point.type = TYPE_OFFICE point.name = u'Центральный офис' point.address = u'г. Минск, ул. В.Хоружей, 31а' point.phones = [u'+375172899090', u'+375172899292'] point.time = u'пн-чт: 08:30-17:30, пт: 08:30-16:15, перерыв: 12:30-13:15, сб, вс: выходной' point.check_information = CHECK_OFFICIAL point.lat, point.lng = self.__get_point_coordinate(point.address, coordinates) if point.lat and point.lng: point.check_coordinates = CHECK_OFFICIAL else: warning_not_official_coordinates(point) return point
def post(self): user = users.get_current_user() if user == None: self.response.out.write() else: lat = float(self.request.get("lat")) lon = float(self.request.get("lon")) hash = geohash.encode(lat, lon) point = Point() point.geohash = hash point.owner = users.get_current_user() point.put() template_values = {"method": "post"} self.response.headers["Content-Type"] = "application/json" self.response.out.write('{result:"OK", geohash:"' + hash + '"}')
def __parse_terminal(self, item): point = Point() point.prov = self.uid point.type = TYPE_TERMINAL point.address, point.place = split_address_place(item('td:eq(2)').text()) point.place = normalize_text(item('td:eq(1)').text()) point.currency = map(strip, item('td:eq(4)').text().split(',')) if point.currency: point.deposit = True else: point.deposit = False point.time = normalize_time(item('td:eq(3)').text()) point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def _test_updatePoint(self): p = Point( '5e64cfce8aeb3647322e0880', { 'planCoordinate': { 'x': 0, 'y': 70 }, 'actualCoordinate': { 'x': 0, 'y': 70 }, }) p.id = '5e64d614b40dda58e5e7b190' p = self.pointDao.updatePoint(p) print(p.toJsonMap())
def __parse_terminal(self, item): point = Point() point.prov = self.uid point.type = TYPE_TERMINAL point.name = normalize_text(item('td:eq(0)').text()) point.address, point.place = split_address_place(item('td:eq(1)').text()) point.place = point.name point.time = normalize_time(item('td:eq(2)').text()) point.deposit = normalize_text(item('td:eq(3)').text()).lower() == u'есть' point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def solve_it(input_data): # Modify this code to run your optimization algorithm # parse the input lines = input_data.split('\n') nodeCount = int(lines[0]) points = [] for i in range(1, nodeCount+1): line = lines[i] parts = line.split() points.append(Point(float(parts[0]), float(parts[1]))) # build a trivial solution # visit the nodes in the order they appear in the file solution_point = solution_function(points.copy()) solution = point_to_order(solution_point,points) # # calculate the length of the tour obj = total_length_by_point(solution_point) # prepare the solution in the specified output format output_data = '%.2f' % obj + ' ' + str(0) + '\n' output_data += ' '.join(map(str, solution)) return output_data
def draw_box( out_img: np.ndarray, box: Box, labels: Iterable[Tuple[str, Point]], color: Color = Color.red(), line_thickness: int = 2, ) -> np.ndarray: cv.rectangle( img=out_img, pt1=box.top_left, pt2=box.bottom_right, color=color.to_bgr(), thickness=line_thickness, ) for text, translation in labels: text_loc: Point = translate_point( Point(box.top_left_x, box.bottom_right_y), translation) cv.putText( img=out_img, text=text, org=text_loc, fontFace=cv.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=Color.orange().to_bgr(), thickness=2, ) return out_img
class Polyline(object): # id oid = "" # 起止点 startPoint = Point() endPoint = Point() lines = [] # type: list[Line] # 长度 _length = 0 def getLength(self): if self._length == 0: for seg in self.lines: self._length += seg.getLength() return self._length
def houseSitting(self, force, resources): self.check(force) resources.sort(key=lambda x: x[0].point.dist(force.point)) if not force.goal and resources: for r in resources: if len(r[0].mother) < 3: r[0].mother.append(force) force.goal.append(r[0].point) break else: resources.remove(r) d = "" if force.goal: d = force.goToPoint(force.goal[0]) if not d: p, strength = self.brain.aStage.enemies.strongest( force.point, Range[force.forceType]) if strength > GATEKEEP_STRENGTH: d = force.goToPoint(p) if not d: d = force.goToPoint( Point(force.cid % 2 * (MAPSIZE - 1), (1 - force.cid % 2) * (MAPSIZE - 1))) return d
def get(self): user = users.get_current_user() if user == None: self.redirect(users.create_login_url(self.request.uri)) userPoints = Point.gql("WHERE owner = :1 ORDER BY created DESC ", users.get_current_user()) template_values = {"method": "get", "points": userPoints} self.response.out.write(template.render("templates/history.html", template_values))
def post(self): a, d = self.request.get('author'), self.request.get('description') # error: missing either key try: schedString = self.request.get('schedulestring') # error: missing parameter jsonSched = simplejson.loads(schedString) # error: bad json s = Schedule(auth = a, desc = d) s.put() # error: some puts succeed while others fail for pt in jsonSched["points"]: # error: not an object, or no "points" key p = Point(sched = s, location = map(int, pt), phase = ['R', 'R']) # error: setting all phases to RR p.put() # error: some puts succeed while others fail # schedule should be post-ed as json string # so parse the string into Schedule's and Point's, then save it # (check out previous versions of scheduler.py for examples of saving) self.response.out.write(simplejson.dumps({'success': 'Schedule was successfully saved!'})) # maybe add the schedule's id? except Exception, e: self.response.out.write(simplejson.dumps({'error': e.message}))
def get_offices(self): points = [] items_tree = ET.fromstring(get_url(self.__offices_xml_url)) for item in items_tree.iter('item'): point = self.__parse_office(item) if point: points.append(point) page = PQ(get_url(self.__regional_offices_page_url)) point = None for item in map(PQ, page('#content_internal span:eq(0)').children()): if item[0].tag not in self.__regional_offices_tags: continue if item[0].tag == 'h2': point = Point() point.prov = self.uid point.type = TYPE_OFFICE point.name = trim_spaces_and_commas(normalize_text(item.text())) point.check_information = CHECK_OFFICIAL continue if not point: continue item_html = replace_br(item.html(), ';;;') sub_items = PQ(item_html).text().split(';;;') point.address, point.place = split_address_place(sub_items[0]) for sub_item in map(normalize_text, sub_items[1:]): if sub_item.startswith(u'т.ф.:'): point.phone = normalize_phones(sub_item[len(u'т.ф.:'):].split(',')) warning_not_official_coordinates(point) points.append(point) point = None return points
def castlePoint(self, character): castle = self.enemies.unit[UnitType.CASTLE.value] if castle: p = min([ p for p in [Point(-1, -1), Point(1, -1), Point(0, -2), Point(-2, 0)] ], key=lambda x: castle[0].point.dist(p)) character.goal = [castle[0].point.plus(Point(-1, -1))] character.isFix = True return if character.goal and character.goal[0] == character.point: strongestPoint, strength = self.enemies.strongest( character.point, 5) character.goal.append(strongestPoint) character.goal.pop(0) if not character.goal: character.goal.append( Point(MAPSIZE - 5 - (self.turnNum % 6) * 5, MAPSIZE - 1)) character.goal.append( Point(MAPSIZE - 5 - (self.turnNum % 6) * 5, MAPSIZE - 45))
def __parse_atm(self, item): point = Point() point.prov = self.uid point.type = TYPE_ATM point.address = normalize_address(u'г. %s' % item('td:eq(0)').text()) point.place = normalize_text(item('td:eq(1)').text()) point.time = normalize_time(item('td:eq(2)').text()) point.currency = map(strip, item('td:eq(3)').text().split(',')) point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def __parse_atm(self, item): point = Point() point.prov = self.uid point.type = TYPE_ATM point.name = normalize_text(item('td:eq(0)').text()) point.address, point.place = split_address_place(item('td:eq(1)').text()) point.place = point.name point.time = normalize_time(item('td:eq(2)').text()) point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def damageTable(self): table = collections.defaultdict(int) for unit in self.units.values(): r = AttackRange[unit.type.value] # 気合入れれば半分にできる for x in xrange(-r, r + 1): for y in xrange(-r, r + 1): if 0 <= unit.point.x + x < MAPSIZE and 0 <= unit.point.y + y < MAPSIZE and abs(x) + abs(y) <= r: table[unit.point.plus(Point(x, y))] += Strength[unit.type.value] return table
def getPoints(filename): global sidePoints with open(filename) as f: reader = csv.reader(f) for row in reader: try: sidePoints.append(Point(float(row[0]), float(row[1]))) except ValueError: continue sidePoints = simplified(sidePoints)
def get_atms(self): points = [] page = PQ(get_url(self.__parse_list_atm_url).decode('utf8')) for item in map(PQ, page('#oo__content_value table tr:gt(0)')): point = Point() point.prov = self.uid point.type = TYPE_ATM point.address = normalize_address(item('td:eq(0) p:eq(0)').text()) point.place = normalize_text(item('td:eq(1)').text()) point.time = normalize_time(item('td:eq(2)').text()) point.currency = map(self.__get_currency, item('td:eq(3) p')) point.check_information = CHECK_OFFICIAL if point.address in self.__addresses: point.lat, point.lng = self.__addresses[point.address] point.check_coordinates = CHECK_OFFICIAL else: warning_not_official_coordinates(point) points.append(point) return points
def searchPoints(self): if self.searchPoints: return self.searchPoints() searchPoints = [] for i in xrange(MAPSIZE / self.GRID): for j in xrange(MAPSIZE / self.GRID): if self.field[i][j] == 0: searchPoints.append(Point(i * MAPSIZE, j * MAPSIZE)) self._searchPoints = searchPoints return searchPoints
def cast_point(value, cur): if value is None: return None # Convert from (f1, f2) syntax using a regular expression. m = re.match(r"\(([^)]+),([^)]+)\)", value) if m: return Point(float(m.group(1)), float(m.group(2))) else: raise InterfaceError("bad point representation: %r" % value)
def parse(filename,filepointer): rows = filepointer.readlines() airspaceFile = AirspaceFile(name=filename, importDate=datetime.now()) counter = 0 previousLine = '' for line in rows: #logger.debug(line) identifier = line[:2] bareline = line[3:].replace('\r\n','') if(re.match("^[A-Za-z]",identifier)): if identifier == 'AC': airspace = Airspace(type=AIRSPACE_CLASSES[bareline],description=previousLine[14:].replace('\r\n','')) airspaceFile.airspaces.append(airspace) counter = 0 elif identifier == 'AN': if bareline.startswith('BERGBAHN'): airspace.subtype = 'CABLECAR' airspace.name = bareline[9:] elif bareline.startswith('KABEL'): airspace.subtype = 'CABLE' airspace.name = bareline[6:] elif bareline.startswith('SCHUTZ'): airspace.subtype = 'WILDLIFE_PROTECTION' airspace.name = bareline[7:] else: airspace.name = bareline elif identifier == 'AH': #airspace.ceiling = int(bareline.replace('GND', '0').replace('ft', '').strip()) airspace.ceiling = bareline elif identifier == 'AL': #airspace.floor = int(bareline.replace('GND', '0').replace('ft', '').strip()) airspace.floor = bareline elif identifier == 'DP': point = Point(index=counter) point.latitude = bareline[:8] point.latitude_dec = dms2dec(point.latitude[:2],point.latitude[3:5],point.latitude[6:]) point.longitude = bareline[11:20] point.longitude_dec = dms2dec(point.longitude[:3],point.longitude[4:6],point.longitude[7:]) airspace.points.append(point) counter += 1 previousLine = line return airspaceFile
def __parse_base_office_exchange(self, item): point = Point() point.prov = self.uid point.name = normalize_text(item('td:eq(1)').text()) point.address, point.place = split_address_place(item('td:eq(2)').text()) point.time = normalize_time(item('td:eq(3)').text()) point.phones = normalize_phones(item('td:eq(4)').text().split(',')) point.check_information = CHECK_OFFICIAL return point
def __parse_base(self, item, city_name, point_type): point = Point() point.prov = self.uid point.type = point_type point.address, point.place = self.__parse_address(city_name, item('td:eq(0) a').text()) point.check_information = CHECK_OFFICIAL point.lat = item('td:eq(0) .item_coords .coord1').text() point.lng = item('td:eq(0) .item_coords .coord2').text() if point.lat and point.lng: point.check_coordinates = CHECK_OFFICIAL else: warning_not_official_coordinates(point) return point
def __parse_exchange(self, item, city): point = Point() point.prov = self.uid point.type = TYPE_EXCHANGE point.name = normalize_text(item('td:eq(0)').text()) point.address, point.place = split_address_place(u'г. %s, %s' % (city, item('td:eq(1)').text())) if len(item('td')) == 4: point.time = normalize_time(item('td:eq(2)').text()) else: point.time = normalize_time(item('td:eq(2)').text().split(u'Операции:')[0]) point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def __parse_terminal(self, item): point = Point() point.prov = self.uid point.type = TYPE_TERMINAL point.address, point.place = split_address_place(item('td:eq(1)').text()) point.time = normalize_time(item('td:eq(2)').text()) point.deposit = u'Пополнение карточки наличными' in item('td:eq(3)').text() point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def __parse_terminal(self, item): point = Point() point.prov = self.uid point.type = TYPE_TERMINAL city = u'г. %s' % normalize_text(item('td:eq(0)').text()).title() point.address = normalize_address(u'%s, %s' % (city, item('td:eq(1)').text())) point.place = normalize_text(item('td:eq(2)').text()) point.time = normalize_time(item('td:eq(3)').text()) point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def __parse_office(self, item): point = Point() point.prov = self.uid point.type = TYPE_OFFICE point.name = normalize_text(item('td:eq(0)').text()) address_items = item('td:eq(1)').text().split(u'тел.') address = address_items[0] point.address, point.place = split_address_place(address) if len(address_items) > 1: phone = address_items[1] phones_items = phone.split(u'доб') point.phones = normalize_phones(phones_items[0].split(',')) point.time = self.__parse_time(item) point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def get_exchanges(self): points = [] page = PQ(get_url(self.__parse_list_exchange_url).decode('utf8')) for item in map(PQ, page('#oo__content_value table tr:gt(0)')): point = Point() point.prov = self.uid point.type = TYPE_EXCHANGE add_city_literal = (u'Минск', u'Витебск') address = normalize_text(item('td:eq(0)').text()) point.address = normalize_address((u'г. ' + address) if address.startswith(add_city_literal) else address) point.place = normalize_text(item('td:eq(1)').text()) point.time = normalize_time(item('td:eq(2)').text()) point.check_information = CHECK_OFFICIAL if point.address in self.__addresses: point.lat, point.lng = self.__addresses[point.address] point.check_coordinates = CHECK_OFFICIAL else: warning_not_official_coordinates(point) points.append(point) return points
def __parse_atm(self, item, coordinates): point = Point() point.prov = self.uid point.type = TYPE_ATM bank = item.find('bank').text if bank != u'ЗАО БелСвиссБанк': return None city = item.find('region').text address = item.find('address').text point.address = normalize_address(u'г. %s, %s' % (city.title(), address)) point.place = normalize_text(item.find('location').text) point.time = normalize_time(item.find('time').text) point.currency = map(strip, item.find('currency').text.split(',')) point.check_information = CHECK_OFFICIAL terminal_id = item.find('terminal_id').text if terminal_id in coordinates: point.lat, point.lng = coordinates[terminal_id] if point.lat and point.lng: point.check_coordinates = CHECK_OFFICIAL else: warning_not_official_coordinates(point) return point
def __parse_exchange(self, item): point = Point() point.prov = self.uid point.type = TYPE_EXCHANGE sub_items = item.text().split(u'—') point.name = normalize_text(sub_items[0]) point.address, point.place = split_address_place(sub_items[1]) point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def __parse_base(self, item): point = Point() point.prov = self.uid point.name = normalize_text(item("td:eq(0)").text()) point.address, point.place = self.__parse_address(item) more_url = self.site + item("td:eq(0) a").attr("href") more = PQ(get_url(more_url)) point.time = None point.phones = [] return point, more
def get_offices(self): points = [] point = Point() point.prov = self.uid point.type = TYPE_OFFICE point.address = u'г. Минск, ул. Клары Цеткин, д. 51, пом. 1' point.phones = [u'+375173060690', u'+375173062591'] point.time = u'пн-чт: 08:30-17:30, обед: 12:30-13:15, пт: 08:30-16:15, обед: 12:30-13:15' point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) points.append(point) return points
def __parse_office(self, item): point = Point() point.prov = self.uid point.type = TYPE_OFFICE point.name = normalize_text(item('h1').text()) point.address, point.place = split_address_place(item('tr:eq(2) td:eq(1)').text()) phones = [] phone_html = replace_br(item('tr:eq(5) td:eq(1)').html(), ';;;') if phone_html: phones += map(strip, PQ(phone_html).text().split(';;;')) phone_html = replace_br(item('tr:eq(6) td:eq(1)').html(), ';;;') if phone_html: phones += map(strip, PQ(phone_html).text().split(';;;')) point.phones = normalize_phones(filter(lambda phone: phone.startswith((u'+', u'тел')), phones)) point.time = normalize_time(item('tr:eq(8) td:eq(1)').text()) point.check_information = CHECK_OFFICIAL warning_not_official_coordinates(point) return point
def __parse_base_atm_terminals(self, item, map_points, point_type, start_names): point = Point() point.prov = self.uid point.type = point_type if not item('.name').text().split()[0].startswith(start_names): return None point.address, point.place = split_address_place(' '.join(item('.name').text().strip().split()[1:])) point.place = trim_spaces_and_commas(normalize_text(item('.addres strong').text())) point.check_information = CHECK_OFFICIAL for lat, lng, name, address, place in map_points: if (name in start_names) and\ (point.address and address and point.address in address) and\ (point.place in place if point.place and place else True): point.lat = lat point.lng = lng point.check_coordinates = CHECK_OFFICIAL break else: warning_not_official_coordinates(point) return point