INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Generalization of the default iter file delimited by '\n'. Note: The newline string can be arbitrarily long; it need not be restricted to a single character. You can also set the read size and control whether or not the newline string is left on the end of the iterated lines. Setting newlin...
def iter_delimiter(self, byte_size=8192): """ Generalization of the default iter file delimited by '\n'. Note: The newline string can be arbitrarily long; it need not be restricted to a single character. You can also set the read size and control whether or not the newline string is left on th...
Read `size` of bytes.
def read(self, size=None): """ Read `size` of bytes.""" if size is None: return self.buf.read() + self.open_file.read() contents = self.buf.read(size) if len(contents) < size: contents += self.open_file.read(size - len(contents)) return contents
Apply `func` to lines of text in parallel or sequential. Args: func : a function that takes a list of lines.
def apply(self, func, workers=1, job_size=10000): """Apply `func` to lines of text in parallel or sequential. Args: func : a function that takes a list of lines. """ if workers == 1: for lines in self.iter_chunks(job_size): yield func(lines) else: with ProcessPoolExecutor(...
Annotate a squence of words with entity tags. Args: sent: sequence of strings/words.
def annotate(self, sent): """Annotate a squence of words with entity tags. Args: sent: sequence of strings/words. """ preds = [] words = [] for word, fv in self.sent2examples(sent): probs = self.predictor(fv) tags = probs.argsort() tag = self.ID_TAG[tags[-1]] word...
Convert ngrams into feature vectors.
def sent2examples(self, sent): """ Convert ngrams into feature vectors.""" # TODO(rmyeid): use expanders. words = [w if w in self.embeddings else TaggerBase.UNK for w in sent] ngrams = TaggerBase.ngrams(words, self.context, self.transfer) fvs = [] for word, ngram in zip(sent, ngrams): fv ...
Building the predictor out of the model.
def _load_network(self): """ Building the predictor out of the model.""" self.embeddings = load_embeddings(self.lang, type='cw', normalize=True) self.model = load_ner_model(lang=self.lang, version=2) first_layer, second_layer = self.model def predict_proba(input_): hidden = np.tanh(np.dot(fir...
Building the predictor out of the model.
def _load_network(self): """ Building the predictor out of the model.""" self.embeddings = load_embeddings(self.lang, type='cw') self.model = load_pos_model(lang=self.lang, version=2) def predict_proba(input_): hidden = np.tanh(np.dot(input_, self.model["W1"]) + self.model["b1"]) output = ...
Construct geocoding request url. Overridden. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL.
def _construct_url(self, base_api, params): """ Construct geocoding request url. Overridden. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL. """ params['...
Return a location point by address. :param str query: The address or query you wish to geocode. :param int limit: Defines the maximum number of items in the response structure. If not provided and there are multiple results the BAN API will return 5 results by default. ...
def geocode( self, query, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL, ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param int limit: Defines the maximum...
Wrap self._call_geocoder, handling tokens.
def _authenticated_call_geocoder(self, url, timeout=DEFAULT_SENTINEL): """ Wrap self._call_geocoder, handling tokens. """ if self.token is None or int(time()) > self.token_expiry: self._refresh_authentication_token() request = Request( "&".join((url, urlen...
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before rais...
def geocode(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, out_fields=None): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if ava...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, distance=None, wkid=DEFAULT_WKID): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :cla...
POST to ArcGIS requesting a new token.
def _refresh_authentication_token(self): """ POST to ArcGIS requesting a new token. """ if self.retry == self._MAX_RETRIES: raise GeocoderAuthenticationFailure( 'Too many retries for auth: %s' % self.retry ) token_request_arguments = { ...
Pair an iterable, e.g., (1, 2, 3, 4) -> ((1, 2), (2, 3), (3, 4))
def pairwise(seq): """ Pair an iterable, e.g., (1, 2, 3, 4) -> ((1, 2), (2, 3), (3, 4)) """ for i in range(0, len(seq) - 1): yield (seq[i], seq[i + 1])
Join with a filter.
def join_filter(sep, seq, pred=bool): """ Join with a filter. """ return sep.join([text_type(i) for i in seq if pred(i)])
Return unicode string of geocoder results. Nearly all services use JSON, so assume UTF8 encoding unless the response specifies otherwise.
def decode_page(page): """ Return unicode string of geocoder results. Nearly all services use JSON, so assume UTF8 encoding unless the response specifies otherwise. """ if hasattr(page, 'read'): # urllib if py3k: encoding = page.headers.get_param("charset") or "utf-8" ...
TODO docs.
def destination(self, point, bearing, distance=None): """ TODO docs. """ point = Point(point) lat1 = units.radians(degrees=point.latitude) lng1 = units.radians(degrees=point.longitude) bearing = units.radians(degrees=bearing) if distance is None: ...
TODO docs.
def destination(self, point, bearing, distance=None): """ TODO docs. """ point = Point(point) lat1 = point.latitude lon1 = point.longitude azi1 = bearing if distance is None: distance = self if isinstance(distance, Distance): ...
Change the ellipsoid used in the calculation.
def set_ellipsoid(self, ellipsoid): """ Change the ellipsoid used in the calculation. """ if not isinstance(ellipsoid, (list, tuple)): try: self.ELLIPSOID = ELLIPSOIDS[ellipsoid] self.ellipsoid_key = ellipsoid except KeyError: ...
TODO docs.
def destination(self, point, bearing, distance=None): """ TODO docs. """ point = Point(point) lat1 = units.radians(degrees=point.latitude) lng1 = units.radians(degrees=point.longitude) bearing = units.radians(degrees=bearing) if distance is None: ...
Normalize angle `x` to be within `[-limit; limit)` range.
def _normalize_angle(x, limit): """ Normalize angle `x` to be within `[-limit; limit)` range. """ double_limit = limit * 2.0 modulo = fmod(x, double_limit) or 0.0 # `or 0` is to turn -0 to +0. if modulo < -limit: return modulo + double_limit if modulo >= limit: return modulo...
Format decimal degrees (DD) to degrees minutes seconds (DMS)
def format(self, altitude=None, deg_char='', min_char='m', sec_char='s'): """ Format decimal degrees (DD) to degrees minutes seconds (DMS) """ latitude = "%s %s" % ( format_degrees(abs(self.latitude), symbols={ 'deg': deg_char, 'arcmin': min_char, 'arcsec': se...
Format decimal degrees with altitude
def format_decimal(self, altitude=None): """ Format decimal degrees with altitude """ coordinates = [str(self.latitude), str(self.longitude)] if altitude is None: altitude = bool(self.altitude) if altitude: if not isinstance(altitude, string_compa...
Parse degrees minutes seconds including direction (N, S, E, W)
def parse_degrees(cls, degrees, arcminutes, arcseconds, direction=None): """ Parse degrees minutes seconds including direction (N, S, E, W) """ degrees = float(degrees) negative = degrees < 0 arcminutes = float(arcminutes) arcseconds = float(arcseconds) i...
Parse altitude managing units conversion
def parse_altitude(cls, distance, unit): """ Parse altitude managing units conversion """ if distance is not None: distance = float(distance) CONVERTERS = { 'km': lambda d: d, 'm': lambda d: units.kilometers(meters=d), ...
Create and return a ``Point`` instance from a string containing latitude and longitude, and optionally, altitude. Latitude and longitude must be in degrees and may be in decimal form or indicate arcminutes and arcseconds (labeled with Unicode prime and double prime, ASCII quote and doub...
def from_string(cls, string): """ Create and return a ``Point`` instance from a string containing latitude and longitude, and optionally, altitude. Latitude and longitude must be in degrees and may be in decimal form or indicate arcminutes and arcseconds (labeled with Unicode pr...
Create and return a new ``Point`` instance from any iterable with 0 to 3 elements. The elements, if present, must be latitude, longitude, and altitude, respectively.
def from_sequence(cls, seq): """ Create and return a new ``Point`` instance from any iterable with 0 to 3 elements. The elements, if present, must be latitude, longitude, and altitude, respectively. """ args = tuple(islice(seq, 4)) if len(args) > 3: r...
Create and return a new ``Point`` instance from another ``Point`` instance.
def from_point(cls, point): """ Create and return a new ``Point`` instance from another ``Point`` instance. """ return cls(point.latitude, point.longitude, point.altitude)
Return a location point by address. :param str query: The address or query you wish to geocode. :param int max_results: The maximum number of resutls to request. :param float set_back: The distance to move the accessPoint away from the curb (in meters) and towards the interior of ...
def geocode( self, query, max_results=25, set_back=0, location_descriptor='any', exactly_one=True, timeout=DEFAULT_SENTINEL, ): """ Return a location point by address. :param str query: The address or query ...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitu...
Raise any exceptions if there were problems reported in the api response.
def _check_for_api_errors(geocoding_results): """ Raise any exceptions if there were problems reported in the api response. """ status_result = geocoding_results.get("STATUS", {}) if "NO_RESULTS" in status_result.get("status", ""): return api_call_succ...
Return a location point by address. :param str query: The address or query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `addressLine`, `locality` (city), `adminDistrict` (state), `countryRegion`, or `postalcode`. :param b...
def geocode( self, query, exactly_one=True, user_location=None, timeout=DEFAULT_SENTINEL, culture=None, include_neighborhood=None, include_country_code=False ): """ Return a location point by address. ...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def reverse( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, culture=None, include_country_code=False ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the ...
TODO docs.
def degrees(radians=0, arcminutes=0, arcseconds=0): """ TODO docs. """ deg = 0. if radians: deg = math.degrees(radians) if arcminutes: deg += arcminutes / arcmin(degrees=1.) if arcseconds: deg += arcseconds / arcsec(degrees=1.) return deg
TODO docs.
def radians(degrees=0, arcminutes=0, arcseconds=0): """ TODO docs. """ if arcminutes: degrees += arcminutes / arcmin(degrees=1.) if arcseconds: degrees += arcseconds / arcsec(degrees=1.) return math.radians(degrees)
TODO docs.
def kilometers(meters=0, miles=0, feet=0, nautical=0): """ TODO docs. """ ret = 0. if meters: ret += meters / 1000. if feet: ret += feet / ft(1.) if nautical: ret += nautical / nm(1.) ret += miles * 1.609344 return ret
TODO docs.
def meters(kilometers=0, miles=0, feet=0, nautical=0): """ TODO docs. """ return (kilometers + km(nautical=nautical, miles=miles, feet=feet)) * 1000
TODO docs.
def miles(kilometers=0, meters=0, feet=0, nautical=0): """ TODO docs. """ ret = 0. if nautical: kilometers += nautical / nm(1.) if feet: kilometers += feet / ft(1.) if meters: kilometers += meters / 1000. ret += kilometers / 1.609344 return ret
TODO docs.
def feet(kilometers=0, meters=0, miles=0, nautical=0): """ TODO docs. """ ret = 0. if nautical: kilometers += nautical / nm(1.) if meters: kilometers += meters / 1000. if kilometers: miles += mi(kilometers=kilometers) ret += miles * 5280 return ret
TODO docs.
def nautical(kilometers=0, meters=0, miles=0, feet=0): """ TODO docs. """ ret = 0. if feet: kilometers += feet / ft(1.) if miles: kilometers += km(miles=miles) if meters: kilometers += meters / 1000. ret += kilometers / 1.852 return ret
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before rais...
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, candidates=None, # TODO: change default value to `1` in geopy 2.0 ): """ Return a location point by address. :param str query: The address or query you wish to ...
Parse responses as JSON objects.
def _parse_json(self, response, exactly_one=True): """ Parse responses as JSON objects. """ if not len(response): return None if exactly_one: return self._format_structured_address(response[0]) else: return [self._format_structured_addr...
Pretty-print address and return lat, lon tuple.
def _format_structured_address(address): """ Pretty-print address and return lat, lon tuple. """ latitude = address['metadata'].get('latitude') longitude = address['metadata'].get('longitude') return Location( ", ".join((address['delivery_line_1'], address['la...
Construct geocoding request url. Overridden. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL.
def _construct_url(self, base_api, params): """ Construct geocoding request url. Overridden. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL. """ params['...
Returns a Premier account signed url. Docs on signature: https://developers.google.com/maps/documentation/business/webservices/auth#digital_signatures
def _get_signed_url(self, params): """ Returns a Premier account signed url. Docs on signature: https://developers.google.com/maps/documentation/business/webservices/auth#digital_signatures """ params['client'] = self.client_id if self.channel: params['ch...
Return a location point by address. :param str query: The address or query you wish to geocode. Optional, if ``components`` param is set:: >>> g.geocode(components={"city": "Paris", "country": "FR"}) Location(France, (46.227638, 2.213749, 0.0)) .. versi...
def geocode( self, query=None, exactly_one=True, timeout=DEFAULT_SENTINEL, bounds=None, region=None, components=None, place_id=None, language=None, sensor=False, ): """ Return a lo...
Find the timezone a `location` was in for a specified `at_time`, and return a pytz timezone object. .. versionadded:: 1.2.0 .. deprecated:: 1.18.0 Use :meth:`GoogleV3.reverse_timezone` instead. This method will be removed in geopy 2.0. .. versionchanged:: 1.18.1 ...
def timezone(self, location, at_time=None, timeout=DEFAULT_SENTINEL): """ Find the timezone a `location` was in for a specified `at_time`, and return a pytz timezone object. .. versionadded:: 1.2.0 .. deprecated:: 1.18.0 Use :meth:`GoogleV3.reverse_timezone` instead....
Find the timezone a point in `query` was in for a specified `at_time`. .. versionadded:: 1.18.0 .. versionchanged:: 1.18.1 Previously a :class:`KeyError` was raised for a point without an assigned Olson timezone id (e.g. for Antarctica). Now this method returns None fo...
def reverse_timezone(self, query, at_time=None, timeout=DEFAULT_SENTINEL): """ Find the timezone a point in `query` was in for a specified `at_time`. .. versionadded:: 1.18.0 .. versionchanged:: 1.18.1 Previously a :class:`KeyError` was raised for a point without ...
Returns location, (latitude, longitude) from json feed.
def _parse_json(self, page, exactly_one=True): '''Returns location, (latitude, longitude) from json feed.''' places = page.get('results', []) if not len(places): self._check_status(page.get('status')) return None def parse_place(place): '''Get the lo...
Validates error statuses.
def _check_status(status): """ Validates error statuses. """ if status == 'ZERO_RESULTS': # When there are no results, just return. return if status == 'OVER_QUERY_LIMIT': raise GeocoderQuotaExceeded( 'The given key has gone ove...
Return a location point by address. This implementation supports only a subset of all available parameters. A list of all parameters of the pure REST API is available here: https://developer.here.com/documentation/geocoder/topics/resource-geocode.html :param str query: The address or q...
def geocode( self, query, bbox=None, mapview=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, additional_data=False, timeout=DEFAULT_SENTINEL ): """ Re...
Return an address by location point. This implementation supports only a subset of all available parameters. A list of all parameters of the pure REST API is available here: https://developer.here.com/documentation/geocoder/topics/resource-reverse-geocode.html :param query: The coordin...
def reverse( self, query, radius=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, mode='retrieveAddresses', timeout=DEFAULT_SENTINEL ): """ Return an address by lo...
Parse a location name, latitude, and longitude from an JSON response.
def _parse_json(doc, exactly_one=True): """ Parse a location name, latitude, and longitude from an JSON response. """ status_code = doc.get("statusCode", 200) if status_code != 200: err = doc.get("errorDetails", "") if status_code == 401: r...
Do the right thing on "point" input. For geocoders with reverse methods.
def _coerce_point_to_string(point, output_format="%(lat)s,%(lon)s"): """ Do the right thing on "point" input. For geocoders with reverse methods. """ try: if not isinstance(point, Point): point = Point(point) except ValueError as e: ...
Transform bounding box boundaries to a string matching `output_format` from the following formats: - [Point(lat1, lon1), Point(lat2, lon2)] - [[lat1, lon1], [lat2, lon2]] - ["lat1,lon1", "lat2,lon2"] It is guaranteed that lat1 <= lat2 and lon1 <= lon2.
def _format_bounding_box(bbox, output_format="%(lat1)s,%(lon1)s,%(lat2)s,%(lon2)s"): """ Transform bounding box boundaries to a string matching `output_format` from the following formats: - [Point(lat1, lon1), Point(lat2, lon2)] - [[lat1, lon1], [lat2, lon2]] ...
For a generated query URL, get the results.
def _call_geocoder( self, url, timeout=DEFAULT_SENTINEL, raw=False, requester=None, deserializer=json.loads, **kwargs ): """ For a generated query URL, get the results. """ if requester: ...
Return a location point by address. :param str query: The address or query you wish to geocode. :param str language: an IETF format language code (such as `es` for Spanish or pt-BR for Brazilian Portuguese); if this is omitted a code of `en` (English) will be assumed by the rem...
def geocode( self, query, bounds=None, country=None, language=None, exactly_one=True, timeout=DEFAULT_SENTINEL, ): """ Return a location point by address. :param str query: The address or query you wish to g...
Validates error statuses.
def _check_status(status): """ Validates error statuses. """ status_code = status['code'] if status_code == 429: # Rate limit exceeded raise GeocoderQuotaExceeded( 'The given key has gone over the requests limit in the 24' '...
Return a location point by address. :param str query: The address or query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `country`, `state`, `city`, `zipcode`, `street`, `address`, `houseNumber` or `subNumber`. :param coun...
def geocode( self, query, country_codes=None, exactly_one=True, timeout=DEFAULT_SENTINEL, ): """ Return a location point by address. :param str query: The address or query you wish to geocode. For a structured query, p...
Returns location, (latitude, longitude) from json feed.
def _parse_json(self, page, exactly_one): """Returns location, (latitude, longitude) from json feed.""" if not page.get('success'): return None latitude = page['latitude'] longitude = page['longitude'] place = page.get('place') address = ", ".join([place['c...
Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be thrown. :param str query: The 3-word address you wish to geocode. :param str lang: two character language codes as supported by t...
def geocode(self, query, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be ...
Parse type, words, latitude, and longitude and language from a JSON response.
def _parse_json(self, resources, exactly_one=True): """ Parse type, words, latitude, and longitude and language from a JSON response. """ code = resources['status'].get('code') if code: # https://docs.what3words.com/api/v2/#errors exc_msg = "Erro...
Return a `3 words` address by location point. Each point on surface has a `3 words` address, so there's always a non-empty response. :param query: The coordinates for which you wish to obtain the 3 word address. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, ...
def reverse(self, query, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return a `3 words` address by location point. Each point on surface has a `3 words` address, so there's always a non-empty response. :param query: The coordinates for which you wish to o...
Return a location point by address. :param query: The address, query or a structured query you wish to geocode. .. versionchanged:: 1.0.0 For a structured query, provide a dictionary whose keys are one of: `street`, `city`, `county`, `state`, `country`, ...
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, addressdetails=False, language=False, geometry=None, extratags=False, country_codes=None, viewbox=None, ...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def reverse( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, language=False, addressdetails=True ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the ...
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before rais...
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, location_bias=None, language=False, limit=None, osm_tag=None ): """ Return a location point by address. :param str query: The...
Parse display name, latitude, and longitude from a JSON response.
def _parse_json(cls, resources, exactly_one=True): """ Parse display name, latitude, and longitude from a JSON response. """ if not len(resources['features']): # pragma: no cover return None if exactly_one: return cls.parse_resource(resources['features'][...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitu...
Parses a location from a single-result reverse API call.
def _parse_reverse_json(self, page, exactly_one=True): """ Parses a location from a single-result reverse API call. """ place = page.get('result') if not place: self._check_status(page.get('status')) return None location = place.get('formatted_ad...
Validates error statuses.
def _check_status(status): """ Validates error statuses. """ if status == 0: # When there are no results, just return. return if status == 1: raise GeocoderServiceError( 'Internal server error.' ) elif status...
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before rais...
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, typeahead=False, language=None, ): """ Return a location point by address. :param str query: The address or query you wish to...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def reverse( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None, ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addr...
Return a location point by address. :param str query: The query string to be geocoded. :param str query_type: The type to provide for geocoding. It can be `PositionOfInterest`, `StreetAddress` or `CadastralParcel`. `StreetAddress` is the default choice if none provided. ...
def geocode( self, query, query_type='StreetAddress', maximum_responses=25, is_freeform=False, filtering=None, exactly_one=True, timeout=DEFAULT_SENTINEL, ): """ Return a location point by address. ...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def reverse( self, query, reverse_geocode_preference=('StreetAddress', ), maximum_responses=25, filtering='', exactly_one=DEFAULT_SENTINEL, timeout=DEFAULT_SENTINEL, ): """ Return an address by location point. ...
Returns location, (latitude, longitude) from XML feed and transform to json
def _parse_xml(self, page, is_reverse=False, is_freeform=False, exactly_one=True): """ Returns location, (latitude, longitude) from XML feed and transform to json """ # Parse the page tree = ET.fr...
Transform the xml ElementTree due to XML webservice return to json
def _xml_to_json_places(tree, is_reverse=False): """ Transform the xml ElementTree due to XML webservice return to json """ select_multi = ( 'GeocodedAddress' if not is_reverse else 'ReverseGeocodedLocation' ) adresses = tree.findall(...
Send the request to get raw content.
def _request_raw_content(self, url, timeout): """ Send the request to get raw content. """ request = Request(url) if self.referer is not None: request.add_header('Referer', self.referer) raw_xml = self._call_geocoder( request, timeou...
Get the location, lat, lng and place from a single json place.
def _parse_place(place, is_freeform=None): """ Get the location, lat, lng and place from a single json place. """ # When freeform already so full address if is_freeform == 'true': location = place.get('freeformaddress') else: # For parcelle ...
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before rais...
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, country=None, country_bias=None, ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :par...
Return an address by location point. .. versionadded:: 1.2.0 :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latit...
def reverse( self, query, exactly_one=DEFAULT_SENTINEL, timeout=DEFAULT_SENTINEL, feature_code=None, lang=None, find_nearby_type='findNearbyPlaceName', ): """ Return an address by location point. .. vers...
Find the timezone for a point in `query`. GeoNames always returns a timezone: if the point being queried doesn't have an assigned Olson timezone id, a ``pytz.FixedOffset`` timezone is used to produce the :class:`geopy.timezone.Timezone`. .. versionadded:: 1.18.0 :param query: ...
def reverse_timezone(self, query, timeout=DEFAULT_SENTINEL): """ Find the timezone for a point in `query`. GeoNames always returns a timezone: if the point being queried doesn't have an assigned Olson timezone id, a ``pytz.FixedOffset`` timezone is used to produce the :class:`ge...
Parse JSON response body.
def _parse_json(self, doc, exactly_one): """ Parse JSON response body. """ places = doc.get('geonames', []) self._raise_for_error(doc) if not len(places): return None def parse_code(place): """ Parse each record. ""...
Return a location point by address. :param str query: The address, query or structured query to geocode you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding s...
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, boundary_rect=None, country_bias=None, ): """ Return a location point by address. :param str query: The address, query or structured query to geocode...
Returns location, (latitude, longitude) from json feed.
def _parse_json(self, json, exactly_one=True): '''Returns location, (latitude, longitude) from json feed.''' features = json['features'] if features == []: return None def parse_feature(feature): location = feature['place_name'] place = feature['text'...
Return a location point by address :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raisi...
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, proximity=None, country=None, bbox=None, ): """ Return a location point by address :param str query: The address or query you wish to geo...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def reverse( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query:...
For the service provided, try to return a geocoder class. >>> from geopy.geocoders import get_geocoder_for_service >>> get_geocoder_for_service("nominatim") geopy.geocoders.osm.Nominatim If the string given is not recognized, a :class:`geopy.exc.GeocoderNotFound` exception is raised.
def get_geocoder_for_service(service): """ For the service provided, try to return a geocoder class. >>> from geopy.geocoders import get_geocoder_for_service >>> get_geocoder_for_service("nominatim") geopy.geocoders.osm.Nominatim If the string given is not recognized, a :class:`geopy.exc.G...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
def reverse( self, query, exactly_one=DEFAULT_SENTINEL, timeout=DEFAULT_SENTINEL, kind=None, ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-reada...
Parse JSON response body.
def _parse_json(self, doc, exactly_one): """ Parse JSON response body. """ if doc.get('error'): raise GeocoderServiceError(doc['error']['message']) try: places = doc['response']['GeoObjectCollection']['featureMember'] except KeyError: ...
TODO docs.
def format_degrees(degrees, fmt=DEGREES_FORMAT, symbols=None): """ TODO docs. """ symbols = symbols or ASCII_SYMBOLS arcminutes = units.arcminutes(degrees=degrees - int(degrees)) arcseconds = units.arcseconds(arcminutes=arcminutes - int(arcminutes)) format_dict = dict( symbols, ...
TODO docs.
def format_distance(kilometers, fmt=DISTANCE_FORMAT, unit='km'): """ TODO docs. """ magnitude = DISTANCE_UNITS[unit](kilometers) return fmt % {'magnitude': magnitude, 'unit': unit}
If ``self._savepath`` doesn't exist, can't be read as JSON, or doesn't match ``VERSION``, return 0. Otherwise, return the step which that file lists as the last-run step for this release. :return: last-run step from the release or 0 :rtype: int
def _last_step(self): """ If ``self._savepath`` doesn't exist, can't be read as JSON, or doesn't match ``VERSION``, return 0. Otherwise, return the step which that file lists as the last-run step for this release. :return: last-run step from the release or 0 :rtype: int ...
Given a build object, find the acceptance36 job
def _find_travis_job(self, build, toxenv): """Given a build object, find the acceptance36 job""" for jobid in build.job_ids: j = self._travis.job(jobid) if 'TOXENV=%s' % toxenv in j.config['env']: logger.debug('Found %s job: %s', toxenv, j.number) ...
Run the specified tox environment. :param env_name: name of the tox environment to run :type env_name: str :param extra_env_vars: additional variables to set in the environment :type extra_env_vars: dict :raises: RuntimeError :returns: combined STDOUT / STDERR :r...
def _run_tox_env(self, env_name, extra_env_vars={}): """ Run the specified tox environment. :param env_name: name of the tox environment to run :type env_name: str :param extra_env_vars: additional variables to set in the environment :type extra_env_vars: dict :r...
Return the current PATH, fixed to remove the docker tox env. :return: sanitized path :rtype: str
def _fixed_path(self, projdir): """ Return the current PATH, fixed to remove the docker tox env. :return: sanitized path :rtype: str """ res = [] toxdir = os.path.join(projdir, '.tox') for p in os.environ['PATH'].split(':'): if not p.startswit...
Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
def find_usage(self): """ Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`. """ logger.debug("Getting usage for Lambda metrics") try: self.connect() resp...
Return all known limits for this service, as a dict of their names to :py:class:`~.AwsLimit` objects. :returns: dict of limit names to :py:class:`~.AwsLimit` objects :rtype: dict
def get_limits(self): """ Return all known limits for this service, as a dict of their names to :py:class:`~.AwsLimit` objects. :returns: dict of limit names to :py:class:`~.AwsLimit` objects :rtype: dict """ logger.debug("Getting limits for Lambda") if s...
Query Lambda's DescribeLimits API action, and update limits with the quotas returned. Updates ``self.limits``.
def _update_limits_from_api(self): """ Query Lambda's DescribeLimits API action, and update limits with the quotas returned. Updates ``self.limits``. """ logger.debug("Updating limits for Lambda from the AWS API") if len(self.limits) == 2: return self....
Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
def find_usage(self): """ Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`. """ logger.debug("Checking usage for service %s", self.service_name) self.connect() for lim i...
Return all known limits for this service, as a dict of their names to :py:class:`~.AwsLimit` objects. :returns: dict of limit names to :py:class:`~.AwsLimit` objects :rtype: dict
def get_limits(self): """ Return all known limits for this service, as a dict of their names to :py:class:`~.AwsLimit` objects. :returns: dict of limit names to :py:class:`~.AwsLimit` objects :rtype: dict """ if self.limits != {}: return self.limits ...