nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geonames.py
GeoNames.reverse_timezone
(self, query, *, timeout=DEFAULT_SENTINEL)
return self._call_geocoder(url, self._parse_json_timezone, timeout=timeout)
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`. :param query: The coordinates for which you want a timezone. :type query: :class:`geopy.point.Point`, list or tuple of (latitude, longitude), or string as "%(latitude)s, %(longitude)s" :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.timezone.Timezone`.
Find the timezone for a point in `query`.
260
295
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:`geopy.timezone.Timezone`. :param query: The coordinates for which you want a timezone. :type query: :class:`geopy.point.Point`, list or tuple of (latitude, longitude), or string as "%(latitude)s, %(longitude)s" :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.timezone.Timezone`. """ ensure_pytz_is_installed() try: lat, lng = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { "lat": lat, "lng": lng, "username": self.username, } url = "?".join((self.api_timezone, urlencode(params))) logger.debug("%s.reverse_timezone: %s", self.__class__.__name__, url) return self._call_geocoder(url, self._parse_json_timezone, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geonames.py#L260-L295
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
52.777778
[ 19, 21, 22, 23, 24, 26, 32, 34, 35 ]
25
false
25.217391
36
2
75
16
def reverse_timezone(self, query, *, timeout=DEFAULT_SENTINEL): ensure_pytz_is_installed() try: lat, lng = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { "lat": lat, "lng": lng, "username": self.username, } url = "?".join((self.api_timezone, urlencode(params))) logger.debug("%s.reverse_timezone: %s", self.__class__.__name__, url) return self._call_geocoder(url, self._parse_json_timezone, timeout=timeout)
21,113
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geonames.py
GeoNames._raise_for_error
(self, body)
297
309
def _raise_for_error(self, body): err = body.get('status') if err: code = err['value'] message = err['message'] # http://www.geonames.org/export/webservice-exception.html if message.startswith("user account not enabled to use"): raise GeocoderInsufficientPrivileges(message) if code == 10: raise GeocoderAuthenticationFailure(message) if code in (18, 19, 20): raise GeocoderQuotaExceeded(message) raise GeocoderServiceError(message)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geonames.py#L297-L309
31
[ 0 ]
7.692308
[ 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12 ]
84.615385
false
25.217391
13
5
15.384615
0
def _raise_for_error(self, body): err = body.get('status') if err: code = err['value'] message = err['message'] # http://www.geonames.org/export/webservice-exception.html if message.startswith("user account not enabled to use"): raise GeocoderInsufficientPrivileges(message) if code == 10: raise GeocoderAuthenticationFailure(message) if code in (18, 19, 20): raise GeocoderQuotaExceeded(message) raise GeocoderServiceError(message)
21,114
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geonames.py
GeoNames._parse_json_timezone
(self, response)
311
323
def _parse_json_timezone(self, response): self._raise_for_error(response) timezone_id = response.get("timezoneId") if timezone_id is None: # Sometimes (e.g. for Antarctica) GeoNames doesn't return # a `timezoneId` value, but it returns GMT offsets. # Apparently GeoNames always returns these offsets -- for # every single point on the globe. raw_offset = response["rawOffset"] return from_fixed_gmt_offset(raw_offset, raw=response) else: return from_timezone_name(timezone_id, raw=response)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geonames.py#L311-L323
31
[ 0 ]
7.692308
[ 1, 3, 4, 9, 10, 12 ]
46.153846
false
25.217391
13
2
53.846154
0
def _parse_json_timezone(self, response): self._raise_for_error(response) timezone_id = response.get("timezoneId") if timezone_id is None: # Sometimes (e.g. for Antarctica) GeoNames doesn't return # a `timezoneId` value, but it returns GMT offsets. # Apparently GeoNames always returns these offsets -- for # every single point on the globe. raw_offset = response["rawOffset"] return from_fixed_gmt_offset(raw_offset, raw=response) else: return from_timezone_name(timezone_id, raw=response)
21,115
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geonames.py
GeoNames._parse_json
(self, doc, exactly_one)
Parse JSON response body.
Parse JSON response body.
325
359
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. """ latitude = place.get('lat', None) longitude = place.get('lng', None) if latitude and longitude: latitude = float(latitude) longitude = float(longitude) else: return None placename = place.get('name') state = place.get('adminName1', None) country = place.get('countryName', None) location = ', '.join( [x for x in [placename, state, country] if x] ) return Location(location, (latitude, longitude), place) if exactly_one: return parse_code(places[0]) else: return [parse_code(place) for place in places]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geonames.py#L325-L359
31
[ 0, 1, 2, 3 ]
11.428571
[ 4, 5, 6, 7, 9, 13, 14, 15, 16, 17, 19, 21, 22, 23, 25, 29, 31, 32, 34 ]
54.285714
false
25.217391
35
8
45.714286
1
def _parse_json(self, doc, exactly_one): places = doc.get('geonames', []) self._raise_for_error(doc) if not len(places): return None def parse_code(place): latitude = place.get('lat', None) longitude = place.get('lng', None) if latitude and longitude: latitude = float(latitude) longitude = float(longitude) else: return None placename = place.get('name') state = place.get('adminName1', None) country = place.get('countryName', None) location = ', '.join( [x for x in [placename, state, country] if x] ) return Location(location, (latitude, longitude), place) if exactly_one: return parse_code(places[0]) else: return [parse_code(place) for place in places]
21,116
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/azure.py
AzureMaps.__init__
( self, subscription_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='atlas.microsoft.com' )
:param str subscription_key: Azure Maps subscription key. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: Domain where the target Azure Maps service is hosted.
:param str subscription_key: Azure Maps subscription key.
17
65
def __init__( self, subscription_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='atlas.microsoft.com' ): """ :param str subscription_key: Azure Maps subscription key. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: Domain where the target Azure Maps service is hosted. """ super().__init__( api_key=subscription_key, scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, domain=domain, )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/azure.py#L17-L65
31
[ 0 ]
2.040816
[ 39 ]
2.040816
false
75
49
1
97.959184
25
def __init__( self, subscription_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='atlas.microsoft.com' ): super().__init__( api_key=subscription_key, scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, domain=domain, )
21,117
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/azure.py
AzureMaps._geocode_params
(self, formatted_query)
return { 'api-version': '1.0', 'subscription-key': self.api_key, 'query': formatted_query, }
67
72
def _geocode_params(self, formatted_query): return { 'api-version': '1.0', 'subscription-key': self.api_key, 'query': formatted_query, }
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/azure.py#L67-L72
31
[ 0 ]
16.666667
[ 1 ]
16.666667
false
75
6
1
83.333333
0
def _geocode_params(self, formatted_query): return { 'api-version': '1.0', 'subscription-key': self.api_key, 'query': formatted_query, }
21,118
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/azure.py
AzureMaps._reverse_params
(self, position)
return { 'api-version': '1.0', 'subscription-key': self.api_key, 'query': position, }
74
79
def _reverse_params(self, position): return { 'api-version': '1.0', 'subscription-key': self.api_key, 'query': position, }
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/azure.py#L74-L79
31
[ 0 ]
16.666667
[ 1 ]
16.666667
false
75
6
1
83.333333
0
def _reverse_params(self, position): return { 'api-version': '1.0', 'subscription-key': self.api_key, 'query': position, }
21,119
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/opencage.py
OpenCage.__init__
( self, api_key, *, domain='api.opencagedata.com', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: The API key required by OpenCageData to perform geocoding requests. You can get your key here: https://opencagedata.com/ :param str domain: Currently it is ``'api.opencagedata.com'``, can be changed for testing purposes. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
26
79
def __init__( self, api_key, *, domain='api.opencagedata.com', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: The API key required by OpenCageData to perform geocoding requests. You can get your key here: https://opencagedata.com/ :param str domain: Currently it is ``'api.opencagedata.com'``, can be changed for testing purposes. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.api = '%s://%s%s' % (self.scheme, self.domain, self.api_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/opencage.py#L26-L79
31
[ 0, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 ]
25.925926
[]
0
false
30
54
1
100
27
def __init__( self, api_key, *, domain='api.opencagedata.com', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.api = '%s://%s%s' % (self.scheme, self.domain, self.api_path)
21,120
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/opencage.py
OpenCage.geocode
( self, query, *, bounds=None, country=None, language=None, annotations=True, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. :type bounds: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param bounds: Provides the geocoder with a hint to the region that the query resides in. This value will help the geocoder but will not restrict the possible results to the supplied region. The bounds parameter should be specified as 2 coordinate points -- corners of a bounding box. Example: ``[Point(22, 180), Point(-22, -180)]``. :param country: Restricts the results to the specified country or countries. The country code is a 2 character code as defined by the ISO 3166-1 Alpha 2 standard (e.g. ``fr``). Might be a Python list of strings. :type country: str or list :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 remote service. :param bool annotations: Enable `annotations <https://opencagedata.com/api#annotations>`_ data, which can be accessed via :attr:`.Location.raw`. Set to False if you don't need it to gain a little performance win. .. versionadded:: 2.2 :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
81
160
def geocode( self, query, *, bounds=None, country=None, language=None, annotations=True, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :type bounds: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param bounds: Provides the geocoder with a hint to the region that the query resides in. This value will help the geocoder but will not restrict the possible results to the supplied region. The bounds parameter should be specified as 2 coordinate points -- corners of a bounding box. Example: ``[Point(22, 180), Point(-22, -180)]``. :param country: Restricts the results to the specified country or countries. The country code is a 2 character code as defined by the ISO 3166-1 Alpha 2 standard (e.g. ``fr``). Might be a Python list of strings. :type country: str or list :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 remote service. :param bool annotations: Enable `annotations <https://opencagedata.com/api#annotations>`_ data, which can be accessed via :attr:`.Location.raw`. Set to False if you don't need it to gain a little performance win. .. versionadded:: 2.2 :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'key': self.api_key, 'q': query, } if not annotations: params['no_annotations'] = 1 if bounds: params['bounds'] = self._format_bounding_box( bounds, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if language: params['language'] = language if not country: country = [] if isinstance(country, str): country = [country] if country: params['countrycode'] = ",".join(country) url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/opencage.py#L81-L160
31
[ 0 ]
1.25
[ 56, 60, 61, 62, 63, 65, 66, 68, 69, 70, 71, 72, 73, 75, 77, 78, 79 ]
21.25
false
30
80
7
78.75
42
def geocode( self, query, *, bounds=None, country=None, language=None, annotations=True, exactly_one=True, timeout=DEFAULT_SENTINEL ): params = { 'key': self.api_key, 'q': query, } if not annotations: params['no_annotations'] = 1 if bounds: params['bounds'] = self._format_bounding_box( bounds, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if language: params['language'] = language if not country: country = [] if isinstance(country, str): country = [country] if country: params['countrycode'] = ",".join(country) url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,121
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/opencage.py
OpenCage.reverse
( self, query, *, language=None, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
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"``. :param str language: The language in which to return results. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
162
203
def reverse( self, query, *, language=None, 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 ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str language: The language in which to return results. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'key': self.api_key, 'q': self._coerce_point_to_string(query), } if language: params['language'] = language url = "?".join((self.api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/opencage.py#L162-L203
31
[ 0 ]
2.380952
[ 31, 35, 36, 38, 39, 40, 41 ]
16.666667
false
30
42
2
83.333333
19
def reverse( self, query, *, language=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): params = { 'key': self.api_key, 'q': self._coerce_point_to_string(query), } if language: params['language'] = language url = "?".join((self.api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,122
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/opencage.py
OpenCage._parse_json
(self, page, exactly_one=True)
Returns location, (latitude, longitude) from json feed.
Returns location, (latitude, longitude) from json feed.
205
223
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 location, lat, lng from a single json place.''' location = place.get('formatted') latitude = place['geometry']['lat'] longitude = place['geometry']['lng'] return Location(location, (latitude, longitude), place) if exactly_one: return parse_place(places[0]) else: return [parse_place(place) for place in places]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/opencage.py#L205-L223
31
[ 0 ]
5.263158
[ 3, 4, 5, 6, 8, 10, 11, 12, 13, 15, 16, 18 ]
63.157895
false
30
19
5
36.842105
1
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 location, lat, lng from a single json place.''' location = place.get('formatted') latitude = place['geometry']['lat'] longitude = place['geometry']['lng'] return Location(location, (latitude, longitude), place) if exactly_one: return parse_place(places[0]) else: return [parse_place(place) for place in places]
21,123
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/opencage.py
OpenCage._check_status
(self, status)
225
232
def _check_status(self, status): status_code = status['code'] message = status['message'] if status_code == 200: return # https://opencagedata.com/api#codes exc_cls = ERROR_CODE_MAP.get(status_code, GeocoderServiceError) raise exc_cls(message)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/opencage.py#L225-L232
31
[ 0 ]
12.5
[ 1, 2, 3, 4, 6, 7 ]
75
false
30
8
2
25
0
def _check_status(self, status): status_code = status['code'] message = status['message'] if status_code == 200: return # https://opencagedata.com/api#codes exc_cls = ERROR_CODE_MAP.get(status_code, GeocoderServiceError) raise exc_cls(message)
21,124
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
_format_coordinate
(coordinate)
return f"{coordinate:.7f}"
424
427
def _format_coordinate(coordinate): if abs(coordinate) >= 1: return coordinate # use the default arbitrary precision scientific notation return f"{coordinate:.7f}"
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L424-L427
31
[ 0, 1, 2, 3 ]
100
[]
0
true
50.340136
4
2
100
0
def _format_coordinate(coordinate): if abs(coordinate) >= 1: return coordinate # use the default arbitrary precision scientific notation return f"{coordinate:.7f}"
21,125
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
_synchronized
(func)
return f
A decorator for geocoder methods which makes the method always run under a lock. The lock is reentrant. This decorator transparently handles sync and async working modes.
A decorator for geocoder methods which makes the method always run under a lock. The lock is reentrant.
430
483
def _synchronized(func): """A decorator for geocoder methods which makes the method always run under a lock. The lock is reentrant. This decorator transparently handles sync and async working modes. """ sync_lock = threading.RLock() def locked_sync(self, *args, **kwargs): with sync_lock: return func(self, *args, **kwargs) # At the moment this decorator is evaluated we don't know if we # will work in sync or async mode. # But we shouldn't create the asyncio Lock in sync mode to avoid # unwanted implicit loop initialization. async_lock = None # asyncio.Lock() async_lock_task = None # support reentrance async def locked_async(self, *args, **kwargs): nonlocal async_lock nonlocal async_lock_task if async_lock is None: async_lock = asyncio.Lock() if async_lock.locked(): assert async_lock_task is not None if compat.current_task() is async_lock_task: res = func(self, *args, **kwargs) if inspect.isawaitable(res): res = await res return res async with async_lock: async_lock_task = compat.current_task() try: res = func(self, *args, **kwargs) if inspect.isawaitable(res): res = await res return res finally: async_lock_task = None @functools.wraps(func) def f(self, *args, **kwargs): run_async = isinstance(self.adapter, BaseAsyncAdapter) if run_async: return locked_async(self, *args, **kwargs) else: return locked_sync(self, *args, **kwargs) return f
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L430-L483
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 44, 45, 46, 52, 53 ]
42.592593
[ 10, 11, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 43, 47, 48, 49, 51 ]
42.592593
false
50.340136
54
13
57.407407
4
def _synchronized(func): sync_lock = threading.RLock() def locked_sync(self, *args, **kwargs): with sync_lock: return func(self, *args, **kwargs) # At the moment this decorator is evaluated we don't know if we # will work in sync or async mode. # But we shouldn't create the asyncio Lock in sync mode to avoid # unwanted implicit loop initialization. async_lock = None # asyncio.Lock() async_lock_task = None # support reentrance async def locked_async(self, *args, **kwargs): nonlocal async_lock nonlocal async_lock_task if async_lock is None: async_lock = asyncio.Lock() if async_lock.locked(): assert async_lock_task is not None if compat.current_task() is async_lock_task: res = func(self, *args, **kwargs) if inspect.isawaitable(res): res = await res return res async with async_lock: async_lock_task = compat.current_task() try: res = func(self, *args, **kwargs) if inspect.isawaitable(res): res = await res return res finally: async_lock_task = None @functools.wraps(func) def f(self, *args, **kwargs): run_async = isinstance(self.adapter, BaseAsyncAdapter) if run_async: return locked_async(self, *args, **kwargs) else: return locked_sync(self, *args, **kwargs) return f
21,126
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder.__init__
( self, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
219
259
def __init__( self, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): self.scheme = scheme or options.default_scheme if self.scheme not in ('http', 'https'): raise ConfigurationError( 'Supported schemes are `http` and `https`.' ) self.timeout = (timeout if timeout is not DEFAULT_SENTINEL else options.default_timeout) self.proxies = (proxies if proxies is not DEFAULT_SENTINEL else options.default_proxies) self.headers = {'User-Agent': user_agent or options.default_user_agent} self.ssl_context = (ssl_context if ssl_context is not DEFAULT_SENTINEL else options.default_ssl_context) if isinstance(self.proxies, str): self.proxies = {'http': self.proxies, 'https': self.proxies} if adapter_factory is None: adapter_factory = options.default_adapter_factory self.adapter = adapter_factory( proxies=self.proxies, ssl_context=self.ssl_context, ) if isinstance(self.adapter, BaseSyncAdapter): self.__run_async = False elif isinstance(self.adapter, BaseAsyncAdapter): self.__run_async = True else: raise ConfigurationError( "Adapter %r must extend either BaseSyncAdapter or BaseAsyncAdapter" % (type(self.adapter),) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L219-L259
31
[ 0, 10, 11, 15, 17, 19, 20, 22, 23, 25, 26, 27, 28, 32, 33 ]
36.585366
[ 12, 24, 34, 35, 37 ]
12.195122
false
50.340136
41
8
87.804878
0
def __init__( self, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): self.scheme = scheme or options.default_scheme if self.scheme not in ('http', 'https'): raise ConfigurationError( 'Supported schemes are `http` and `https`.' ) self.timeout = (timeout if timeout is not DEFAULT_SENTINEL else options.default_timeout) self.proxies = (proxies if proxies is not DEFAULT_SENTINEL else options.default_proxies) self.headers = {'User-Agent': user_agent or options.default_user_agent} self.ssl_context = (ssl_context if ssl_context is not DEFAULT_SENTINEL else options.default_ssl_context) if isinstance(self.proxies, str): self.proxies = {'http': self.proxies, 'https': self.proxies} if adapter_factory is None: adapter_factory = options.default_adapter_factory self.adapter = adapter_factory( proxies=self.proxies, ssl_context=self.ssl_context, ) if isinstance(self.adapter, BaseSyncAdapter): self.__run_async = False elif isinstance(self.adapter, BaseAsyncAdapter): self.__run_async = True else: raise ConfigurationError( "Adapter %r must extend either BaseSyncAdapter or BaseAsyncAdapter" % (type(self.adapter),) )
21,127
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder.__enter__
(self)
return self
Context manager for synchronous adapters. At exit all open connections will be closed. In synchronous mode context manager usage is not required, and connections will be automatically closed by garbage collection.
Context manager for synchronous adapters. At exit all open connections will be closed.
261
272
def __enter__(self): """Context manager for synchronous adapters. At exit all open connections will be closed. In synchronous mode context manager usage is not required, and connections will be automatically closed by garbage collection. """ if self.__run_async: raise TypeError("`async with` must be used with async adapters") res = self.adapter.__enter__() assert res is self.adapter, "adapter's __enter__ must return `self`" return self
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L261-L272
31
[ 0, 1, 2, 3, 4, 5, 6 ]
58.333333
[ 7, 8, 9, 10, 11 ]
41.666667
false
50.340136
12
3
58.333333
5
def __enter__(self): if self.__run_async: raise TypeError("`async with` must be used with async adapters") res = self.adapter.__enter__() assert res is self.adapter, "adapter's __enter__ must return `self`" return self
21,128
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder.__exit__
(self, exc_type, exc_val, exc_tb)
274
275
def __exit__(self, exc_type, exc_val, exc_tb): self.adapter.__exit__(exc_type, exc_val, exc_tb)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L274-L275
31
[ 0 ]
50
[ 1 ]
50
false
50.340136
2
1
50
0
def __exit__(self, exc_type, exc_val, exc_tb): self.adapter.__exit__(exc_type, exc_val, exc_tb)
21,129
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder.__aenter__
(self)
return self
Context manager for asynchronous adapters. At exit all open connections will be closed. In asynchronous mode context manager usage is not required, however, it is strongly advised to avoid warnings about resources leaks.
Context manager for asynchronous adapters. At exit all open connections will be closed.
277
289
async def __aenter__(self): """Context manager for asynchronous adapters. At exit all open connections will be closed. In asynchronous mode context manager usage is not required, however, it is strongly advised to avoid warnings about resources leaks. """ if not self.__run_async: raise TypeError("`async with` cannot be used with sync adapters") res = await self.adapter.__aenter__() assert res is self.adapter, "adapter's __enter__ must return `self`" return self
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L277-L289
31
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
61.538462
[ 8, 9, 10, 11, 12 ]
38.461538
false
50.340136
13
3
61.538462
6
async def __aenter__(self): if not self.__run_async: raise TypeError("`async with` cannot be used with sync adapters") res = await self.adapter.__aenter__() assert res is self.adapter, "adapter's __enter__ must return `self`" return self
21,130
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder.__aexit__
(self, exc_type, exc_val, exc_tb)
291
292
async def __aexit__(self, exc_type, exc_val, exc_tb): await self.adapter.__aexit__(exc_type, exc_val, exc_tb)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L291-L292
31
[ 0 ]
50
[ 1 ]
50
false
50.340136
2
1
50
0
async def __aexit__(self, exc_type, exc_val, exc_tb): await self.adapter.__aexit__(exc_type, exc_val, exc_tb)
21,131
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder._coerce_point_to_string
(self, point, output_format="%(lat)s,%(lon)s")
return output_format % dict(lat=_format_coordinate(point.latitude), lon=_format_coordinate(point.longitude))
Do the right thing on "point" input. For geocoders with reverse methods.
Do the right thing on "point" input. For geocoders with reverse methods.
294
310
def _coerce_point_to_string(self, point, output_format="%(lat)s,%(lon)s"): """ Do the right thing on "point" input. For geocoders with reverse methods. """ if not isinstance(point, Point): point = Point(point) # Altitude is silently dropped. # # Geocoding services (almost?) always consider only lat and lon # in queries, so altitude doesn't affect the request. # A non-zero altitude should not raise an exception # though, because PoIs are assumed to span the whole # altitude axis (i.e. not just the 0km plane). return output_format % dict(lat=_format_coordinate(point.latitude), lon=_format_coordinate(point.longitude))
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L294-L310
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
50.340136
17
2
100
2
def _coerce_point_to_string(self, point, output_format="%(lat)s,%(lon)s"): if not isinstance(point, Point): point = Point(point) # Altitude is silently dropped. # # Geocoding services (almost?) always consider only lat and lon # in queries, so altitude doesn't affect the request. # A non-zero altitude should not raise an exception # though, because PoIs are assumed to span the whole # altitude axis (i.e. not just the 0km plane). return output_format % dict(lat=_format_coordinate(point.latitude), lon=_format_coordinate(point.longitude))
21,132
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder._format_bounding_box
( self, bbox, output_format="%(lat1)s,%(lon1)s,%(lat2)s,%(lon2)s" )
return output_format % dict(lat1=min(p1.latitude, p2.latitude), lon1=min(p1.longitude, p2.longitude), lat2=max(p1.latitude, p2.latitude), lon2=max(p1.longitude, p2.longitude))
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.
Transform bounding box boundaries to a string matching `output_format` from the following formats:
312
332
def _format_bounding_box( self, 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]] - ["lat1,lon1", "lat2,lon2"] It is guaranteed that lat1 <= lat2 and lon1 <= lon2. """ if len(bbox) != 2: raise GeocoderQueryError("Unsupported format for a bounding box") p1, p2 = bbox p1, p2 = Point(p1), Point(p2) return output_format % dict(lat1=min(p1.latitude, p2.latitude), lon1=min(p1.longitude, p2.longitude), lat2=max(p1.latitude, p2.latitude), lon2=max(p1.longitude, p2.longitude))
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L312-L332
31
[ 0, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
47.619048
[]
0
false
50.340136
21
2
100
8
def _format_bounding_box( self, bbox, output_format="%(lat1)s,%(lon1)s,%(lat2)s,%(lon2)s" ): if len(bbox) != 2: raise GeocoderQueryError("Unsupported format for a bounding box") p1, p2 = bbox p1, p2 = Point(p1), Point(p2) return output_format % dict(lat1=min(p1.latitude, p2.latitude), lon1=min(p1.longitude, p2.longitude), lat2=max(p1.latitude, p2.latitude), lon2=max(p1.longitude, p2.longitude))
21,133
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder._geocoder_exception_handler
(self, error)
Geocoder-specific exceptions handler. Override if custom exceptions processing is needed. For example, raising an appropriate GeocoderQuotaExceeded on non-200 response with a textual message in the body about the exceeded quota. Return `NONE_RESULT` to have the geocoding call return `None` (meaning empty result).
Geocoder-specific exceptions handler. Override if custom exceptions processing is needed. For example, raising an appropriate GeocoderQuotaExceeded on non-200 response with a textual message in the body about the exceeded quota.
334
344
def _geocoder_exception_handler(self, error): """ Geocoder-specific exceptions handler. Override if custom exceptions processing is needed. For example, raising an appropriate GeocoderQuotaExceeded on non-200 response with a textual message in the body about the exceeded quota. Return `NONE_RESULT` to have the geocoding call return `None` (meaning empty result). """ pass
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L334-L344
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
90.909091
[ 10 ]
9.090909
false
50.340136
11
1
90.909091
7
def _geocoder_exception_handler(self, error): pass
21,134
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder._call_geocoder
( self, url, callback, *, timeout=DEFAULT_SENTINEL, is_json=True, headers=None )
For a generated query URL, get the results.
For a generated query URL, get the results.
346
391
def _call_geocoder( self, url, callback, *, timeout=DEFAULT_SENTINEL, is_json=True, headers=None ): """ For a generated query URL, get the results. """ req_headers = self.headers.copy() if headers: req_headers.update(headers) timeout = (timeout if timeout is not DEFAULT_SENTINEL else self.timeout) try: if is_json: result = self.adapter.get_json(url, timeout=timeout, headers=req_headers) else: result = self.adapter.get_text(url, timeout=timeout, headers=req_headers) if self.__run_async: async def fut(): try: res = callback(await result) if inspect.isawaitable(res): res = await res return res except Exception as error: res = self._adapter_error_handler(error) if res is NONE_RESULT: return None raise return fut() else: return callback(result) except Exception as error: res = self._adapter_error_handler(error) if res is NONE_RESULT: return None raise
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L346-L391
31
[ 0, 12, 13, 14, 16, 17, 19, 20, 21, 22, 25, 40 ]
26.086957
[ 15, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 41, 42, 43, 44, 45 ]
41.304348
false
50.340136
46
10
58.695652
1
def _call_geocoder( self, url, callback, *, timeout=DEFAULT_SENTINEL, is_json=True, headers=None ): req_headers = self.headers.copy() if headers: req_headers.update(headers) timeout = (timeout if timeout is not DEFAULT_SENTINEL else self.timeout) try: if is_json: result = self.adapter.get_json(url, timeout=timeout, headers=req_headers) else: result = self.adapter.get_text(url, timeout=timeout, headers=req_headers) if self.__run_async: async def fut(): try: res = callback(await result) if inspect.isawaitable(res): res = await res return res except Exception as error: res = self._adapter_error_handler(error) if res is NONE_RESULT: return None raise return fut() else: return callback(result) except Exception as error: res = self._adapter_error_handler(error) if res is NONE_RESULT: return None raise
21,135
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/base.py
Geocoder._adapter_error_handler
(self, error)
393
415
def _adapter_error_handler(self, error): if isinstance(error, AdapterHTTPError): if error.text: logger.info( 'Received an HTTP error (%s): %s', error.status_code, error.text, exc_info=False, ) res = self._geocoder_exception_handler(error) if res is NONE_RESULT: return NONE_RESULT exc_cls = ERROR_CODE_MAP.get(error.status_code, GeocoderServiceError) if issubclass(exc_cls, GeocoderRateLimited): raise exc_cls( str(error), retry_after=get_retry_after(error.headers) ) from error else: raise exc_cls(str(error)) from error else: res = self._geocoder_exception_handler(error) if res is NONE_RESULT: return NONE_RESULT
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/base.py#L393-L415
31
[ 0 ]
4.347826
[ 1, 2, 3, 9, 10, 11, 12, 13, 14, 18, 20, 21, 22 ]
56.521739
false
50.340136
23
6
43.478261
0
def _adapter_error_handler(self, error): if isinstance(error, AdapterHTTPError): if error.text: logger.info( 'Received an HTTP error (%s): %s', error.status_code, error.text, exc_info=False, ) res = self._geocoder_exception_handler(error) if res is NONE_RESULT: return NONE_RESULT exc_cls = ERROR_CODE_MAP.get(error.status_code, GeocoderServiceError) if issubclass(exc_cls, GeocoderRateLimited): raise exc_cls( str(error), retry_after=get_retry_after(error.headers) ) from error else: raise exc_cls(str(error)) from error else: res = self._geocoder_exception_handler(error) if res is NONE_RESULT: return NONE_RESULT
21,136
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/databc.py
DataBC.__init__
( self, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
21
63
def __init__( self, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) domain = 'apps.gov.bc.ca' self.api = '%s://%s%s' % (self.scheme, domain, self.geocode_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/databc.py#L21-L63
31
[ 0 ]
2.325581
[ 33, 41, 42 ]
6.976744
false
32.5
43
1
93.023256
20
def __init__( self, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) domain = 'apps.gov.bc.ca' self.api = '%s://%s%s' % (self.scheme, domain, self.geocode_path)
21,137
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/databc.py
DataBC.geocode
( self, query, *, max_results=25, set_back=0, location_descriptor='any', exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
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 the parcel. location_descriptor must be set to accessPoint for set_back to take effect. :param str location_descriptor: The type of point requested. It can be any, accessPoint, frontDoorPoint, parcelPoint, rooftopPoint and routingPoint. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
65
124
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 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 the parcel. location_descriptor must be set to accessPoint for set_back to take effect. :param str location_descriptor: The type of point requested. It can be any, accessPoint, frontDoorPoint, parcelPoint, rooftopPoint and routingPoint. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {'addressString': query} if set_back != 0: params['setBack'] = set_back if location_descriptor not in ['any', 'accessPoint', 'frontDoorPoint', 'parcelPoint', 'rooftopPoint', 'routingPoint']: raise GeocoderQueryError( "You did not provided a location_descriptor " "the webservice can consume. It should be any, accessPoint, " "frontDoorPoint, parcelPoint, rooftopPoint or routingPoint." ) params['locationDescriptor'] = location_descriptor if exactly_one: max_results = 1 params['maxResults'] = max_results url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/databc.py#L65-L124
31
[ 0 ]
1.666667
[ 37, 38, 39, 40, 46, 51, 52, 53, 54, 56, 57, 58, 59 ]
21.666667
false
32.5
60
4
78.333333
25
def geocode( self, query, *, max_results=25, set_back=0, location_descriptor='any', exactly_one=True, timeout=DEFAULT_SENTINEL ): params = {'addressString': query} if set_back != 0: params['setBack'] = set_back if location_descriptor not in ['any', 'accessPoint', 'frontDoorPoint', 'parcelPoint', 'rooftopPoint', 'routingPoint']: raise GeocoderQueryError( "You did not provided a location_descriptor " "the webservice can consume. It should be any, accessPoint, " "frontDoorPoint, parcelPoint, rooftopPoint or routingPoint." ) params['locationDescriptor'] = location_descriptor if exactly_one: max_results = 1 params['maxResults'] = max_results url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,138
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/databc.py
DataBC._parse_json
(self, response, exactly_one)
return geocoded
126
135
def _parse_json(self, response, exactly_one): # Success; convert from GeoJSON if not len(response['features']): return None geocoded = [] for feature in response['features']: geocoded.append(self._parse_feature(feature)) if exactly_one: return geocoded[0] return geocoded
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/databc.py#L126-L135
31
[ 0, 1 ]
20
[ 2, 3, 4, 5, 6, 7, 8, 9 ]
80
false
32.5
10
4
20
0
def _parse_json(self, response, exactly_one): # Success; convert from GeoJSON if not len(response['features']): return None geocoded = [] for feature in response['features']: geocoded.append(self._parse_feature(feature)) if exactly_one: return geocoded[0] return geocoded
21,139
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/databc.py
DataBC._parse_feature
(self, feature)
return Location( properties['fullAddress'], (coordinates[1], coordinates[0]), properties )
137
143
def _parse_feature(self, feature): properties = feature['properties'] coordinates = feature['geometry']['coordinates'] return Location( properties['fullAddress'], (coordinates[1], coordinates[0]), properties )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/databc.py#L137-L143
31
[ 0 ]
14.285714
[ 1, 2, 3 ]
42.857143
false
32.5
7
1
57.142857
0
def _parse_feature(self, feature): properties = feature['properties'] coordinates = feature['geometry']['coordinates'] return Location( properties['fullAddress'], (coordinates[1], coordinates[0]), properties )
21,140
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/ignfrance.py
IGNFrance.__init__
( self, api_key=None, *, username=None, password=None, referer=None, domain='wxs.ign.fr', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: Not used. .. deprecated:: 2.3 IGNFrance geocoding methods no longer accept or require authentication, see `<https://geoservices.ign.fr/actualites/2021-10-04-evolution-des-modalites-dacces-aux-services-web>`_. This parameter is scheduled for removal in geopy 3.0. :param str username: Not used. .. deprecated:: 2.3 See the `api_key` deprecation note. :param str password: Not used. .. deprecated:: 2.3 See the `api_key` deprecation note. :param str referer: Not used. .. deprecated:: 2.3 See the `api_key` deprecation note. :param str domain: Currently it is ``'wxs.ign.fr'``, can be changed for testing purposes for developer API e.g ``'gpp3-wxs.ign.fr'`` at the moment. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
39
125
def __init__( self, api_key=None, *, username=None, password=None, referer=None, domain='wxs.ign.fr', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: Not used. .. deprecated:: 2.3 IGNFrance geocoding methods no longer accept or require authentication, see `<https://geoservices.ign.fr/actualites/2021-10-04-evolution-des-modalites-dacces-aux-services-web>`_. This parameter is scheduled for removal in geopy 3.0. :param str username: Not used. .. deprecated:: 2.3 See the `api_key` deprecation note. :param str password: Not used. .. deprecated:: 2.3 See the `api_key` deprecation note. :param str referer: Not used. .. deprecated:: 2.3 See the `api_key` deprecation note. :param str domain: Currently it is ``'wxs.ign.fr'``, can be changed for testing purposes for developer API e.g ``'gpp3-wxs.ign.fr'`` at the moment. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ # noqa super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) if api_key or username or password or referer: warnings.warn( "IGNFrance no longer accepts or requires authentication, " "so api_key, username, password and referer are not used " "anymore. These arguments should be removed. " "In geopy 3 these options will be removed, causing " "an error instead of this warning.", DeprecationWarning, stacklevel=2, ) self.domain = domain.strip('/') api_path = self.api_path self.api = '%s://%s%s' % (self.scheme, self.domain, api_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/ignfrance.py#L39-L125
31
[ 0 ]
1.149425
[ 64, 73, 74, 84, 85, 86 ]
6.896552
false
15.2
87
5
93.103448
46
def __init__( self, api_key=None, *, username=None, password=None, referer=None, domain='wxs.ign.fr', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): # noqa super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) if api_key or username or password or referer: warnings.warn( "IGNFrance no longer accepts or requires authentication, " "so api_key, username, password and referer are not used " "anymore. These arguments should be removed. " "In geopy 3 these options will be removed, causing " "an error instead of this warning.", DeprecationWarning, stacklevel=2, ) self.domain = domain.strip('/') api_path = self.api_path self.api = '%s://%s%s' % (self.scheme, self.domain, api_path)
21,141
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/ignfrance.py
IGNFrance.geocode
( self, query, *, query_type='StreetAddress', maximum_responses=25, is_freeform=False, filtering=None, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._request_raw_content(url, callback, timeout=timeout)
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. :param int maximum_responses: The maximum number of responses to ask to the API in the query body. :param str is_freeform: Set if return is structured with freeform structure or a more structured returned. By default, value is False. :param str filtering: Provide string that help setting geocoder filter. It contains an XML string. See examples in documentation and ignfrance.py file in directory tests. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
127
227
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. :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. :param int maximum_responses: The maximum number of responses to ask to the API in the query body. :param str is_freeform: Set if return is structured with freeform structure or a more structured returned. By default, value is False. :param str filtering: Provide string that help setting geocoder filter. It contains an XML string. See examples in documentation and ignfrance.py file in directory tests. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ # Check if acceptable query type if query_type not in ['PositionOfInterest', 'StreetAddress', 'CadastralParcel']: raise GeocoderQueryError("""You did not provided a query_type the webservice can consume. It should be PositionOfInterest, 'StreetAddress or CadastralParcel""") # Check query validity for CadastralParcel if query_type == 'CadastralParcel' and len(query.strip()) != 14: raise GeocoderQueryError("""You must send a string of fourteen characters long to match the cadastre required code""") sub_request = """ <GeocodeRequest returnFreeForm="{is_freeform}"> <Address countryCode="{query_type}"> <freeFormAddress>{query}</freeFormAddress> {filtering} </Address> </GeocodeRequest> """ xml_request = self.xml_request.format( method_name='LocationUtilityService', sub_request=sub_request, maximum_responses=maximum_responses ) # Manage type change for xml case sensitive if is_freeform: is_freeform = 'true' else: is_freeform = 'false' # Manage filtering value if filtering is None: filtering = '' # Create query using parameters request_string = xml_request.format( is_freeform=is_freeform, query=query, query_type=query_type, filtering=filtering ) params = { 'xls': request_string } url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial( self._parse_xml, is_freeform=is_freeform, exactly_one=exactly_one ) return self._request_raw_content(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/ignfrance.py#L127-L227
31
[ 0 ]
0.990099
[ 45, 48, 53, 54, 57, 66, 73, 74, 76, 79, 80, 83, 90, 94, 96, 97, 100 ]
16.831683
false
15.2
101
6
83.168317
29
def geocode( self, query, *, query_type='StreetAddress', maximum_responses=25, is_freeform=False, filtering=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): # Check if acceptable query type if query_type not in ['PositionOfInterest', 'StreetAddress', 'CadastralParcel']: raise GeocoderQueryError("""You did not provided a query_type the webservice can consume. It should be PositionOfInterest, 'StreetAddress or CadastralParcel""") # Check query validity for CadastralParcel if query_type == 'CadastralParcel' and len(query.strip()) != 14: raise GeocoderQueryError("""You must send a string of fourteen characters long to match the cadastre required code""") sub_request = xml_request = self.xml_request.format( method_name='LocationUtilityService', sub_request=sub_request, maximum_responses=maximum_responses ) # Manage type change for xml case sensitive if is_freeform: is_freeform = 'true' else: is_freeform = 'false' # Manage filtering value if filtering is None: filtering = '' # Create query using parameters request_string = xml_request.format( is_freeform=is_freeform, query=query, query_type=query_type, filtering=filtering ) params = { 'xls': request_string } url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial( self._parse_xml, is_freeform=is_freeform, exactly_one=exactly_one ) return self._request_raw_content(url, callback, timeout=timeout)
21,142
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/ignfrance.py
IGNFrance.reverse
( self, query, *, reverse_geocode_preference=('StreetAddress', ), maximum_responses=25, filtering='', exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._request_raw_content(url, callback, timeout=timeout)
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"``. :param list reverse_geocode_preference: Enable to set expected results type. It can be `StreetAddress` or `PositionOfInterest`. Default is set to `StreetAddress`. :param int maximum_responses: The maximum number of responses to ask to the API in the query body. :param str filtering: Provide string that help setting geocoder filter. It contains an XML string. See examples in documentation and ignfrance.py file in directory tests. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
229
319
def reverse( self, query, *, reverse_geocode_preference=('StreetAddress', ), maximum_responses=25, filtering='', 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 ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param list reverse_geocode_preference: Enable to set expected results type. It can be `StreetAddress` or `PositionOfInterest`. Default is set to `StreetAddress`. :param int maximum_responses: The maximum number of responses to ask to the API in the query body. :param str filtering: Provide string that help setting geocoder filter. It contains an XML string. See examples in documentation and ignfrance.py file in directory tests. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ sub_request = """ <ReverseGeocodeRequest> {reverse_geocode_preference} <Position> <gml:Point> <gml:pos>{query}</gml:pos> </gml:Point> {filtering} </Position> </ReverseGeocodeRequest> """ xml_request = self.xml_request.format( method_name='ReverseGeocodeRequest', sub_request=sub_request, maximum_responses=maximum_responses ) for pref in reverse_geocode_preference: if pref not in ('StreetAddress', 'PositionOfInterest'): raise GeocoderQueryError( '`reverse_geocode_preference` must contain ' 'one or more of: StreetAddress, PositionOfInterest' ) point = self._coerce_point_to_string(query, "%(lat)s %(lon)s") reverse_geocode_preference = '\n'.join( '<ReverseGeocodePreference>%s</ReverseGeocodePreference>' % pref for pref in reverse_geocode_preference ) request_string = xml_request.format( maximum_responses=maximum_responses, query=point, reverse_geocode_preference=reverse_geocode_preference, filtering=filtering ) url = "?".join((self.api, urlencode({'xls': request_string}))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial( self._parse_xml, exactly_one=exactly_one, is_reverse=True, is_freeform='false' ) return self._request_raw_content(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/ignfrance.py#L229-L319
31
[ 0 ]
1.098901
[ 42, 54, 60, 61, 62, 67, 68, 74, 81, 83, 84, 90 ]
13.186813
false
15.2
91
3
86.813187
28
def reverse( self, query, *, reverse_geocode_preference=('StreetAddress', ), maximum_responses=25, filtering='', exactly_one=True, timeout=DEFAULT_SENTINEL ): sub_request = xml_request = self.xml_request.format( method_name='ReverseGeocodeRequest', sub_request=sub_request, maximum_responses=maximum_responses ) for pref in reverse_geocode_preference: if pref not in ('StreetAddress', 'PositionOfInterest'): raise GeocoderQueryError( '`reverse_geocode_preference` must contain ' 'one or more of: StreetAddress, PositionOfInterest' ) point = self._coerce_point_to_string(query, "%(lat)s %(lon)s") reverse_geocode_preference = '\n'.join( '<ReverseGeocodePreference>%s</ReverseGeocodePreference>' % pref for pref in reverse_geocode_preference ) request_string = xml_request.format( maximum_responses=maximum_responses, query=point, reverse_geocode_preference=reverse_geocode_preference, filtering=filtering ) url = "?".join((self.api, urlencode({'xls': request_string}))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial( self._parse_xml, exactly_one=exactly_one, is_reverse=True, is_freeform='false' ) return self._request_raw_content(url, callback, timeout=timeout)
21,143
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/ignfrance.py
IGNFrance._parse_xml
(self, page, is_reverse=False, is_freeform=False, exactly_one=True)
Returns location, (latitude, longitude) from XML feed and transform to json
Returns location, (latitude, longitude) from XML feed and transform to json
321
359
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.fromstring(page.encode('utf-8')) # Clean tree from namespace to facilitate XML manipulation def remove_namespace(doc, namespace): """Remove namespace in the document in place.""" ns = '{%s}' % namespace nsl = len(ns) for elem in doc.iter(): if elem.tag.startswith(ns): elem.tag = elem.tag[nsl:] remove_namespace(tree, 'http://www.opengis.net/gml') remove_namespace(tree, 'http://www.opengis.net/xls') remove_namespace(tree, 'http://www.opengis.net/xlsext') # Return places as json instead of XML places = self._xml_to_json_places(tree, is_reverse=is_reverse) if not places: return None if exactly_one: return self._parse_place(places[0], is_freeform=is_freeform) else: return [ self._parse_place( place, is_freeform=is_freeform ) for place in places ]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/ignfrance.py#L321-L359
31
[ 0 ]
2.564103
[ 10, 13, 15, 16, 17, 18, 19, 21, 22, 23, 26, 28, 29, 30, 31, 33 ]
41.025641
false
15.2
39
7
58.974359
2
def _parse_xml(self, page, is_reverse=False, is_freeform=False, exactly_one=True): # Parse the page tree = ET.fromstring(page.encode('utf-8')) # Clean tree from namespace to facilitate XML manipulation def remove_namespace(doc, namespace): ns = '{%s}' % namespace nsl = len(ns) for elem in doc.iter(): if elem.tag.startswith(ns): elem.tag = elem.tag[nsl:] remove_namespace(tree, 'http://www.opengis.net/gml') remove_namespace(tree, 'http://www.opengis.net/xls') remove_namespace(tree, 'http://www.opengis.net/xlsext') # Return places as json instead of XML places = self._xml_to_json_places(tree, is_reverse=is_reverse) if not places: return None if exactly_one: return self._parse_place(places[0], is_freeform=is_freeform) else: return [ self._parse_place( place, is_freeform=is_freeform ) for place in places ]
21,144
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/ignfrance.py
IGNFrance._xml_to_json_places
(self, tree, is_reverse=False)
return places
Transform the xml ElementTree due to XML webservice return to json
Transform the xml ElementTree due to XML webservice return to json
361
442
def _xml_to_json_places(self, 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('.//' + select_multi) places = [] sel_pl = './/Address/Place[@type="{}"]' for adr in adresses: el = {} el['pos'] = adr.find('./Point/pos') el['street'] = adr.find('.//Address/StreetAddress/Street') el['freeformaddress'] = adr.find('.//Address/freeFormAddress') el['municipality'] = adr.find(sel_pl.format('Municipality')) el['numero'] = adr.find(sel_pl.format('Numero')) el['feuille'] = adr.find(sel_pl.format('Feuille')) el['section'] = adr.find(sel_pl.format('Section')) el['departement'] = adr.find(sel_pl.format('Departement')) el['commune_absorbee'] = adr.find(sel_pl.format('CommuneAbsorbee')) el['commune'] = adr.find(sel_pl.format('Commune')) el['insee'] = adr.find(sel_pl.format('INSEE')) el['qualite'] = adr.find(sel_pl.format('Qualite')) el['territoire'] = adr.find(sel_pl.format('Territoire')) el['id'] = adr.find(sel_pl.format('ID')) el['id_tr'] = adr.find(sel_pl.format('ID_TR')) el['bbox'] = adr.find(sel_pl.format('Bbox')) el['nature'] = adr.find(sel_pl.format('Nature')) el['postal_code'] = adr.find('.//Address/PostalCode') el['extended_geocode_match_code'] = adr.find( './/ExtendedGeocodeMatchCode' ) place = {} def testContentAttrib(selector, key): """ Helper to select by attribute and if not attribute, value set to empty string """ return selector.attrib.get( key, None ) if selector is not None else None place['accuracy'] = testContentAttrib( adr.find('.//GeocodeMatchCode'), 'accuracy') place['match_type'] = testContentAttrib( adr.find('.//GeocodeMatchCode'), 'matchType') place['building'] = testContentAttrib( adr.find('.//Address/StreetAddress/Building'), 'number') place['search_centre_distance'] = testContentAttrib( adr.find('.//SearchCentreDistance'), 'value') for key, value in iter(el.items()): if value is not None: place[key] = value.text else: place[key] = None # We check if lat lng is not empty and unpack accordingly if place['pos']: lat, lng = place['pos'].split(' ') place['lat'] = lat.strip() place['lng'] = lng.strip() else: place['lat'] = place['lng'] = None # We removed the unused key place.pop("pos", None) places.append(place) return places
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/ignfrance.py#L361-L442
31
[ 0, 1, 2, 3, 4 ]
6.097561
[ 5, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 39, 41, 46, 51, 54, 57, 60, 63, 64, 65, 67, 70, 71, 72, 73, 75, 78, 79, 81 ]
53.658537
false
15.2
82
6
46.341463
1
def _xml_to_json_places(self, tree, is_reverse=False): select_multi = ( 'GeocodedAddress' if not is_reverse else 'ReverseGeocodedLocation' ) adresses = tree.findall('.//' + select_multi) places = [] sel_pl = './/Address/Place[@type="{}"]' for adr in adresses: el = {} el['pos'] = adr.find('./Point/pos') el['street'] = adr.find('.//Address/StreetAddress/Street') el['freeformaddress'] = adr.find('.//Address/freeFormAddress') el['municipality'] = adr.find(sel_pl.format('Municipality')) el['numero'] = adr.find(sel_pl.format('Numero')) el['feuille'] = adr.find(sel_pl.format('Feuille')) el['section'] = adr.find(sel_pl.format('Section')) el['departement'] = adr.find(sel_pl.format('Departement')) el['commune_absorbee'] = adr.find(sel_pl.format('CommuneAbsorbee')) el['commune'] = adr.find(sel_pl.format('Commune')) el['insee'] = adr.find(sel_pl.format('INSEE')) el['qualite'] = adr.find(sel_pl.format('Qualite')) el['territoire'] = adr.find(sel_pl.format('Territoire')) el['id'] = adr.find(sel_pl.format('ID')) el['id_tr'] = adr.find(sel_pl.format('ID_TR')) el['bbox'] = adr.find(sel_pl.format('Bbox')) el['nature'] = adr.find(sel_pl.format('Nature')) el['postal_code'] = adr.find('.//Address/PostalCode') el['extended_geocode_match_code'] = adr.find( './/ExtendedGeocodeMatchCode' ) place = {} def testContentAttrib(selector, key): return selector.attrib.get( key, None ) if selector is not None else None place['accuracy'] = testContentAttrib( adr.find('.//GeocodeMatchCode'), 'accuracy') place['match_type'] = testContentAttrib( adr.find('.//GeocodeMatchCode'), 'matchType') place['building'] = testContentAttrib( adr.find('.//Address/StreetAddress/Building'), 'number') place['search_centre_distance'] = testContentAttrib( adr.find('.//SearchCentreDistance'), 'value') for key, value in iter(el.items()): if value is not None: place[key] = value.text else: place[key] = None # We check if lat lng is not empty and unpack accordingly if place['pos']: lat, lng = place['pos'].split(' ') place['lat'] = lat.strip() place['lng'] = lng.strip() else: place['lat'] = place['lng'] = None # We removed the unused key place.pop("pos", None) places.append(place) return places
21,145
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/ignfrance.py
IGNFrance._request_raw_content
(self, url, callback, *, timeout)
return self._call_geocoder( url, callback, timeout=timeout, is_json=False, )
Send the request to get raw content.
Send the request to get raw content.
444
453
def _request_raw_content(self, url, callback, *, timeout): """ Send the request to get raw content. """ return self._call_geocoder( url, callback, timeout=timeout, is_json=False, )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/ignfrance.py#L444-L453
31
[ 0, 1, 2, 3 ]
40
[ 4 ]
10
false
15.2
10
1
90
1
def _request_raw_content(self, url, callback, *, timeout): return self._call_geocoder( url, callback, timeout=timeout, is_json=False, )
21,146
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/ignfrance.py
IGNFrance._parse_place
(self, place, is_freeform=None)
return Location(location, (place.get('lat'), place.get('lng')), place)
Get the location, lat, lng and place from a single json place.
Get the location, lat, lng and place from a single json place.
455
484
def _parse_place(self, 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 if place.get('numero'): location = place.get('street') else: # When classic geocoding # or when reverse geocoding location = "%s %s" % ( place.get('postal_code', ''), place.get('commune', ''), ) if place.get('street'): location = "%s, %s" % ( place.get('street', ''), location, ) if place.get('building'): location = "%s %s" % ( place.get('building', ''), location, ) return Location(location, (place.get('lat'), place.get('lng')), place)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/ignfrance.py#L455-L484
31
[ 0, 1, 2, 3, 4 ]
16.666667
[ 5, 6, 9, 10, 14, 18, 19, 23, 24, 29 ]
33.333333
false
15.2
30
5
66.666667
1
def _parse_place(self, place, is_freeform=None): # When freeform already so full address if is_freeform == 'true': location = place.get('freeformaddress') else: # For parcelle if place.get('numero'): location = place.get('street') else: # When classic geocoding # or when reverse geocoding location = "%s %s" % ( place.get('postal_code', ''), place.get('commune', ''), ) if place.get('street'): location = "%s, %s" % ( place.get('street', ''), location, ) if place.get('building'): location = "%s %s" % ( place.get('building', ''), location, ) return Location(location, (place.get('lat'), place.get('lng')), place)
21,147
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/__init__.py
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.nominatim.Nominatim If the string given is not recognized, a :class:`geopy.exc.GeocoderNotFound` exception is raised. Given that almost all of the geocoders provide the ``geocode`` method it could be used to make basic queries based entirely on user input:: from geopy.geocoders import get_geocoder_for_service def geocode(geocoder, config, query): cls = get_geocoder_for_service(geocoder) geolocator = cls(**config) location = geolocator.geocode(query) return location.address >>> geocode("nominatim", dict(user_agent="specify_your_app_name_here"), \ "london") 'London, Greater London, England, SW1A 2DX, United Kingdom' >>> geocode("photon", dict(), "london") 'London, SW1A 2DX, London, England, United Kingdom'
For the service provided, try to return a geocoder class.
287
323
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.nominatim.Nominatim If the string given is not recognized, a :class:`geopy.exc.GeocoderNotFound` exception is raised. Given that almost all of the geocoders provide the ``geocode`` method it could be used to make basic queries based entirely on user input:: from geopy.geocoders import get_geocoder_for_service def geocode(geocoder, config, query): cls = get_geocoder_for_service(geocoder) geolocator = cls(**config) location = geolocator.geocode(query) return location.address >>> geocode("nominatim", dict(user_agent="specify_your_app_name_here"), \ "london") 'London, Greater London, England, SW1A 2DX, United Kingdom' >>> geocode("photon", dict(), "london") 'London, SW1A 2DX, London, England, United Kingdom' """ try: return SERVICE_TO_GEOCODER[service.lower()] except KeyError: raise GeocoderNotFound( "Unknown geocoder '%s'; options are: %s" % (service, SERVICE_TO_GEOCODER.keys()) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/__init__.py#L287-L323
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 ]
100
[]
0
true
100
37
2
100
26
def get_geocoder_for_service(service): try: return SERVICE_TO_GEOCODER[service.lower()] except KeyError: raise GeocoderNotFound( "Unknown geocoder '%s'; options are: %s" % (service, SERVICE_TO_GEOCODER.keys()) )
21,148
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geocodio.py
Geocodio.__init__
( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: A valid Geocod.io API key. (https://dash.geocod.io/apikey/create) :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`.
:param str api_key: A valid Geocod.io API key. (https://dash.geocod.io/apikey/create)
39
81
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: A valid Geocod.io API key. (https://dash.geocod.io/apikey/create) :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geocodio.py#L39-L81
31
[ 0 ]
2.325581
[ 34, 42 ]
4.651163
false
27.631579
43
1
95.348837
21
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key
21,149
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geocodio.py
Geocodio.geocode
( self, query, *, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param query: The address, query or a structured query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `street`, `city`, `state`, `postal_code` or `country`. :type query: dict or str :param int limit: The maximum number of matches to return. This will be reset to 1 if ``exactly_one`` is ``True``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
83
138
def geocode( self, query, *, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a location point by address. :param query: The address, query or a structured query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `street`, `city`, `state`, `postal_code` or `country`. :type query: dict or str :param int limit: The maximum number of matches to return. This will be reset to 1 if ``exactly_one`` is ``True``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } else: params = {'q': query} params['api_key'] = self.api_key if limit: params['limit'] = limit if exactly_one: params['limit'] = 1 api = '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) url = "?".join((api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geocodio.py#L83-L138
31
[ 0 ]
1.785714
[ 33, 34, 41, 43, 45, 46, 47, 48, 50, 51, 53, 54, 55 ]
23.214286
false
27.631579
56
4
76.785714
22
def geocode( self, query, *, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } else: params = {'q': query} params['api_key'] = self.api_key if limit: params['limit'] = limit if exactly_one: params['limit'] = 1 api = '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) url = "?".join((api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,150
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geocodio.py
Geocodio.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param str query: The coordinates for which you wish to obtain the closest human-readable addresses :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: The maximum number of matches to return. This will be reset to 1 if ``exactly_one`` is ``True``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
140
181
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None ): """Return an address by location point. :param str query: The coordinates for which you wish to obtain the closest human-readable addresses :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: The maximum number of matches to return. This will be reset to 1 if ``exactly_one`` is ``True``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'q': self._coerce_point_to_string(query), 'api_key': self.api_key } if exactly_one: limit = 1 if limit is not None: params['limit'] = limit api = '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) url = "?".join((api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geocodio.py#L140-L181
31
[ 0 ]
2.380952
[ 27, 31, 32, 33, 34, 36, 37, 39, 40, 41 ]
23.809524
false
27.631579
42
3
76.190476
18
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None ): params = { 'q': self._coerce_point_to_string(query), 'api_key': self.api_key } if exactly_one: limit = 1 if limit is not None: params['limit'] = limit api = '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) url = "?".join((api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,151
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geocodio.py
Geocodio._parse_json
(self, page, exactly_one=True)
Returns location, (latitude, longitude) from json feed.
Returns location, (latitude, longitude) from json feed.
183
200
def _parse_json(self, page, exactly_one=True): """Returns location, (latitude, longitude) from json feed.""" places = page.get('results', []) if not places: return None def parse_place(place): """Get the location, lat, lng from a single json place.""" location = place.get('formatted_address') latitude = place['location']['lat'] longitude = place['location']['lng'] return Location(location, (latitude, longitude), place) if exactly_one: return parse_place(places[0]) else: return [parse_place(place) for place in places]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geocodio.py#L183-L200
31
[ 0, 1, 2 ]
16.666667
[ 3, 4, 5, 7, 9, 10, 11, 12, 14, 15, 17 ]
61.111111
false
27.631579
18
5
38.888889
1
def _parse_json(self, page, exactly_one=True): places = page.get('results', []) if not places: return None def parse_place(place): location = place.get('formatted_address') latitude = place['location']['lat'] longitude = place['location']['lng'] return Location(location, (latitude, longitude), place) if exactly_one: return parse_place(places[0]) else: return [parse_place(place) for place in places]
21,152
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geocodio.py
Geocodio._geocoder_exception_handler
(self, error)
Custom exception handling for invalid queries and exceeded quotas. Geocod.io returns a ``422`` status code for invalid queries, which is not mapped in :const:`~geopy.geocoders.base.ERROR_CODE_MAP`. The service also returns a ``403`` status code for exceeded quotas instead of the ``429`` code mapped in :const:`~geopy.geocoders.base.ERROR_CODE_MAP`
Custom exception handling for invalid queries and exceeded quotas.
202
227
def _geocoder_exception_handler(self, error): """Custom exception handling for invalid queries and exceeded quotas. Geocod.io returns a ``422`` status code for invalid queries, which is not mapped in :const:`~geopy.geocoders.base.ERROR_CODE_MAP`. The service also returns a ``403`` status code for exceeded quotas instead of the ``429`` code mapped in :const:`~geopy.geocoders.base.ERROR_CODE_MAP` """ if not isinstance(error, AdapterHTTPError): return if error.status_code is None or error.text is None: return if error.status_code == 422: error_message = self._get_error_message(error) if ( 'could not geocode address' in error_message.lower() and 'postal code or city required' in error_message.lower() ): return NONE_RESULT raise GeocoderQueryError(error_message) from error if error.status_code == 403: error_message = self._get_error_message(error) quota_exceeded_snippet = "You can't make this request as it is " \ "above your daily maximum." if quota_exceeded_snippet in error_message: raise GeocoderQuotaExceeded(error_message) from error
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geocodio.py#L202-L227
31
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
30.769231
[ 8, 9, 10, 11, 12, 13, 14, 18, 19, 20, 21, 22, 24, 25 ]
53.846154
false
27.631579
26
9
46.153846
6
def _geocoder_exception_handler(self, error): if not isinstance(error, AdapterHTTPError): return if error.status_code is None or error.text is None: return if error.status_code == 422: error_message = self._get_error_message(error) if ( 'could not geocode address' in error_message.lower() and 'postal code or city required' in error_message.lower() ): return NONE_RESULT raise GeocoderQueryError(error_message) from error if error.status_code == 403: error_message = self._get_error_message(error) quota_exceeded_snippet = "You can't make this request as it is " \ "above your daily maximum." if quota_exceeded_snippet in error_message: raise GeocoderQuotaExceeded(error_message) from error
21,153
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geocodio.py
Geocodio._get_error_message
(self, error)
return error_message or error.text
Try to extract an error message from the 'error' property of a JSON response.
Try to extract an error message from the 'error' property of a JSON response.
229
236
def _get_error_message(self, error): """Try to extract an error message from the 'error' property of a JSON response. """ try: error_message = json.loads(error.text).get('error') except ValueError: error_message = None return error_message or error.text
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geocodio.py#L229-L236
31
[ 0, 1, 2 ]
37.5
[ 3, 4, 5, 6, 7 ]
62.5
false
27.631579
8
3
37.5
1
def _get_error_message(self, error): try: error_message = json.loads(error.text).get('error') except ValueError: error_message = None return error_message or error.text
21,154
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/mapbox.py
MapBox.__init__
( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='api.mapbox.com', referer=None )
:param str api_key: The API key required by Mapbox to perform geocoding requests. API keys are managed through Mapox's account page (https://www.mapbox.com/account/access-tokens). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: base api domain for mapbox :param str referer: The URL used to satisfy the URL restriction of mapbox tokens. .. versionadded:: 2.3
:param str api_key: The API key required by Mapbox to perform geocoding requests. API keys are managed through Mapox's account page (https://www.mapbox.com/account/access-tokens).
21
79
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='api.mapbox.com', referer=None ): """ :param str api_key: The API key required by Mapbox to perform geocoding requests. API keys are managed through Mapox's account page (https://www.mapbox.com/account/access-tokens). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: base api domain for mapbox :param str referer: The URL used to satisfy the URL restriction of mapbox tokens. .. versionadded:: 2.3 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.api = "%s://%s%s" % (self.scheme, self.domain, self.api_path) if referer: self.headers['Referer'] = referer
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/mapbox.py#L21-L79
31
[ 0 ]
1.694915
[ 46, 54, 55, 56, 57, 58 ]
10.169492
false
22.413793
59
2
89.830508
31
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='api.mapbox.com', referer=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.api = "%s://%s%s" % (self.scheme, self.domain, self.api_path) if referer: self.headers['Referer'] = referer
21,155
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/mapbox.py
MapBox._parse_json
(self, json, exactly_one=True)
Returns location, (latitude, longitude) from json feed.
Returns location, (latitude, longitude) from json feed.
81
95
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'] longitude = feature['geometry']['coordinates'][0] latitude = feature['geometry']['coordinates'][1] return Location(location, (latitude, longitude), feature) if exactly_one: return parse_feature(features[0]) else: return [parse_feature(feature) for feature in features]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/mapbox.py#L81-L95
31
[ 0 ]
6.666667
[ 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14 ]
73.333333
false
22.413793
15
5
26.666667
1
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'] longitude = feature['geometry']['coordinates'][0] latitude = feature['geometry']['coordinates'][1] return Location(location, (latitude, longitude), feature) if exactly_one: return parse_feature(features[0]) else: return [parse_feature(feature) for feature in features]
21,156
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/mapbox.py
MapBox.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, proximity=None, country=None, language=None, bbox=None )
return self._call_geocoder(url, callback, timeout=timeout)
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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param proximity: A coordinate to bias local results based on a provided location. :type proximity: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param country: Country to filter result in form of ISO 3166-1 alpha-2 country code (e.g. ``FR``). Might be a Python list of strings. :type country: str or list :param str language: This parameter controls the language of the text supplied in responses, and also affects result scoring, with results matching the user’s query in the requested language being preferred over results that match in another language. You can pass two letters country codes (ISO 639-1). .. versionadded:: 2.3 :param bbox: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. :type bbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
97
174
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, proximity=None, country=None, language=None, bbox=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 available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param proximity: A coordinate to bias local results based on a provided location. :type proximity: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param country: Country to filter result in form of ISO 3166-1 alpha-2 country code (e.g. ``FR``). Might be a Python list of strings. :type country: str or list :param str language: This parameter controls the language of the text supplied in responses, and also affects result scoring, with results matching the user’s query in the requested language being preferred over results that match in another language. You can pass two letters country codes (ISO 639-1). .. versionadded:: 2.3 :param bbox: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. :type bbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {} params['access_token'] = self.api_key if bbox: params['bbox'] = self._format_bounding_box( bbox, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if not country: country = [] if isinstance(country, str): country = [country] if country: params['country'] = ",".join(country) if proximity: p = Point(proximity) params['proximity'] = "%s,%s" % (p.longitude, p.latitude) if language: params['language'] = language quoted_query = quote(query.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/mapbox.py#L97-L174
31
[ 0 ]
1.282051
[ 51, 53, 54, 55, 58, 59, 60, 61, 62, 63, 65, 66, 67, 69, 70, 72, 73, 75, 76, 77 ]
25.641026
false
22.413793
78
7
74.358974
38
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, proximity=None, country=None, language=None, bbox=None ): params = {} params['access_token'] = self.api_key if bbox: params['bbox'] = self._format_bounding_box( bbox, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if not country: country = [] if isinstance(country, str): country = [country] if country: params['country'] = ",".join(country) if proximity: p = Point(proximity) params['proximity'] = "%s,%s" % (p.longitude, p.latitude) if language: params['language'] = language quoted_query = quote(query.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,157
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/mapbox.py
MapBox.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
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"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
176
211
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 ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {} params['access_token'] = self.api_key point = self._coerce_point_to_string(query, "%(lon)s,%(lat)s") quoted_query = quote(point.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/mapbox.py#L176-L211
31
[ 0 ]
2.777778
[ 26, 27, 29, 30, 31, 33, 34, 35 ]
22.222222
false
22.413793
36
1
77.777778
17
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL ): params = {} params['access_token'] = self.api_key point = self._coerce_point_to_string(query, "%(lon)s,%(lat)s") quoted_query = quote(point.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,158
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/maptiler.py
MapTiler.__init__
( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='api.maptiler.com' )
:param str api_key: The API key required by Maptiler to perform geocoding requests. API keys are managed through Maptiler's account page (https://cloud.maptiler.com/account/keys). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: base api domain for Maptiler
:param str api_key: The API key required by Maptiler to perform geocoding requests. API keys are managed through Maptiler's account page (https://cloud.maptiler.com/account/keys).
21
71
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='api.maptiler.com' ): """ :param str api_key: The API key required by Maptiler to perform geocoding requests. API keys are managed through Maptiler's account page (https://cloud.maptiler.com/account/keys). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: base api domain for Maptiler """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.api = "%s://%s%s" % (self.scheme, self.domain, self.api_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/maptiler.py#L21-L71
31
[ 0 ]
1.960784
[ 40, 48, 49, 50 ]
7.843137
false
23.636364
51
1
92.156863
26
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='api.maptiler.com' ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.api = "%s://%s%s" % (self.scheme, self.domain, self.api_path)
21,159
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/maptiler.py
MapTiler._parse_json
(self, json, exactly_one=True)
73
88
def _parse_json(self, json, exactly_one=True): # Returns location, (latitude, longitude) from json feed. features = json['features'] if not features: return None def parse_feature(feature): location = feature['place_name'] longitude = feature['center'][0] latitude = feature['center'][1] return Location(location, (latitude, longitude), feature) if exactly_one: return parse_feature(features[0]) else: return [parse_feature(feature) for feature in features]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/maptiler.py#L73-L88
31
[ 0, 1 ]
12.5
[ 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 15 ]
68.75
false
23.636364
16
5
31.25
0
def _parse_json(self, json, exactly_one=True): # Returns location, (latitude, longitude) from json feed. features = json['features'] if not features: return None def parse_feature(feature): location = feature['place_name'] longitude = feature['center'][0] latitude = feature['center'][1] return Location(location, (latitude, longitude), feature) if exactly_one: return parse_feature(features[0]) else: return [parse_feature(feature) for feature in features]
21,160
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/maptiler.py
MapTiler.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, proximity=None, language=None, bbox=None )
return self._call_geocoder(url, callback, timeout=timeout)
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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param proximity: A coordinate to bias local results based on a provided location. :type proximity: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param language: Prefer results in specific languages. Accepts a single string like ``"en"`` or a list like ``["de", "en"]``. :type language: str or list :param bbox: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. :type bbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
90
152
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, proximity=None, language=None, bbox=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 available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param proximity: A coordinate to bias local results based on a provided location. :type proximity: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param language: Prefer results in specific languages. Accepts a single string like ``"en"`` or a list like ``["de", "en"]``. :type language: str or list :param bbox: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. :type bbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {'key': self.api_key} query = query if bbox: params['bbox'] = self._format_bounding_box( bbox, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if isinstance(language, str): language = [language] if language: params['language'] = ','.join(language) if proximity: p = Point(proximity) params['proximity'] = "%s,%s" % (p.longitude, p.latitude) quoted_query = quote(query.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/maptiler.py#L90-L152
31
[ 0 ]
1.587302
[ 41, 43, 44, 45, 48, 49, 50, 51, 53, 54, 55, 57, 58, 60, 61, 62 ]
25.396825
false
23.636364
63
5
74.603175
29
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, proximity=None, language=None, bbox=None ): params = {'key': self.api_key} query = query if bbox: params['bbox'] = self._format_bounding_box( bbox, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if isinstance(language, str): language = [language] if language: params['language'] = ','.join(language) if proximity: p = Point(proximity) params['proximity'] = "%s,%s" % (p.longitude, p.latitude) quoted_query = quote(query.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,161
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/maptiler.py
MapTiler.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None )
return self._call_geocoder(url, callback, timeout=timeout)
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"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param language: Prefer results in specific languages. Accepts a single string like ``"en"`` or a list like ``["de", "en"]``. :type language: str or list :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
154
198
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 addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param language: Prefer results in specific languages. Accepts a single string like ``"en"`` or a list like ``["de", "en"]``. :type language: str or list :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {'key': self.api_key} if isinstance(language, str): language = [language] if language: params['language'] = ','.join(language) point = self._coerce_point_to_string(query, "%(lon)s,%(lat)s") quoted_query = quote(point.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/maptiler.py#L154-L198
31
[ 0 ]
2.222222
[ 31, 33, 34, 35, 36, 38, 39, 40, 42, 43, 44 ]
24.444444
false
23.636364
45
3
75.555556
21
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None ): params = {'key': self.api_key} if isinstance(language, str): language = [language] if language: params['language'] = ','.join(language) point = self._coerce_point_to_string(query, "%(lon)s,%(lat)s") quoted_query = quote(point.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,162
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/yandex.py
Yandex.__init__
( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, scheme=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: Yandex API key, mandatory. The key can be created at https://developer.tech.yandex.ru/ :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
21
68
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, scheme=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: Yandex API key, mandatory. The key can be created at https://developer.tech.yandex.ru/ :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key domain = 'geocode-maps.yandex.ru' self.api = '%s://%s%s' % (self.scheme, domain, self.api_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/yandex.py#L21-L68
31
[ 0 ]
2.083333
[ 37, 45, 46, 47 ]
8.333333
false
20.967742
48
1
91.666667
23
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, scheme=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key domain = 'geocode-maps.yandex.ru' self.api = '%s://%s%s' % (self.scheme, domain, self.api_path)
21,163
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/yandex.py
Yandex.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, lang=None )
return self._call_geocoder(url, callback, timeout=timeout)
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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str lang: Language of the response and regional settings of the map. List of supported values: - ``tr_TR`` -- Turkish (only for maps of Turkey); - ``en_RU`` -- response in English, Russian map features; - ``en_US`` -- response in English, American map features; - ``ru_RU`` -- Russian (default); - ``uk_UA`` -- Ukrainian; - ``be_BY`` -- Belarusian. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
70
116
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, lang=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 available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str lang: Language of the response and regional settings of the map. List of supported values: - ``tr_TR`` -- Turkish (only for maps of Turkey); - ``en_RU`` -- response in English, Russian map features; - ``en_US`` -- response in English, American map features; - ``ru_RU`` -- Russian (default); - ``uk_UA`` -- Ukrainian; - ``be_BY`` -- Belarusian. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'geocode': query, 'format': 'json' } params['apikey'] = self.api_key if lang: params['lang'] = lang if exactly_one: params['results'] = 1 url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/yandex.py#L70-L116
31
[ 0 ]
2.12766
[ 34, 38, 39, 40, 41, 42, 43, 44, 45, 46 ]
21.276596
false
20.967742
47
3
78.723404
24
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, lang=None ): params = { 'geocode': query, 'format': 'json' } params['apikey'] = self.api_key if lang: params['lang'] = lang if exactly_one: params['results'] = 1 url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,164
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/yandex.py
Yandex.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, kind=None, lang=None )
return self._call_geocoder(url, callback, timeout=timeout)
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"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str kind: Type of toponym. Allowed values: `house`, `street`, `metro`, `district`, `locality`. :param str lang: Language of the response and regional settings of the map. List of supported values: - ``tr_TR`` -- Turkish (only for maps of Turkey); - ``en_RU`` -- response in English, Russian map features; - ``en_US`` -- response in English, American map features; - ``ru_RU`` -- Russian (default); - ``uk_UA`` -- Ukrainian; - ``be_BY`` -- Belarusian. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
118
176
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, kind=None, lang=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"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str kind: Type of toponym. Allowed values: `house`, `street`, `metro`, `district`, `locality`. :param str lang: Language of the response and regional settings of the map. List of supported values: - ``tr_TR`` -- Turkish (only for maps of Turkey); - ``en_RU`` -- response in English, Russian map features; - ``en_US`` -- response in English, American map features; - ``ru_RU`` -- Russian (default); - ``uk_UA`` -- Ukrainian; - ``be_BY`` -- Belarusian. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ try: point = self._coerce_point_to_string(query, "%(lon)s,%(lat)s") except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'geocode': point, 'format': 'json' } params['apikey'] = self.api_key if lang: params['lang'] = lang if kind: params['kind'] = kind url = "?".join((self.api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/yandex.py#L118-L176
31
[ 0 ]
1.694915
[ 42, 43, 44, 45, 46, 50, 51, 52, 53, 54, 55, 56, 57, 58 ]
23.728814
false
20.967742
59
4
76.271186
30
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, kind=None, lang=None ): try: point = self._coerce_point_to_string(query, "%(lon)s,%(lat)s") except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'geocode': point, 'format': 'json' } params['apikey'] = self.api_key if lang: params['lang'] = lang if kind: params['kind'] = kind url = "?".join((self.api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,165
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/yandex.py
Yandex._parse_json
(self, doc, exactly_one)
Parse JSON response body.
Parse JSON response body.
178
214
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: raise GeocoderParseError('Failed to parse server response') def parse_code(place): """ Parse each record. """ try: place = place['GeoObject'] except KeyError: raise GeocoderParseError('Failed to parse server response') longitude, latitude = ( float(_) for _ in place['Point']['pos'].split(' ') ) name_elements = ['name', 'description'] location = ', '.join([place[k] for k in name_elements if place.get(k)]) return Location(location, (latitude, longitude), place) if exactly_one: try: return parse_code(places[0]) except IndexError: return None else: return [parse_code(place) for place in places]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/yandex.py#L178-L214
31
[ 0, 1, 2, 3 ]
10.810811
[ 4, 5, 7, 8, 9, 10, 12, 16, 17, 18, 19, 21, 25, 26, 28, 30, 31, 32, 33, 34, 36 ]
56.756757
false
20.967742
37
9
43.243243
1
def _parse_json(self, doc, exactly_one): if doc.get('error'): raise GeocoderServiceError(doc['error']['message']) try: places = doc['response']['GeoObjectCollection']['featureMember'] except KeyError: raise GeocoderParseError('Failed to parse server response') def parse_code(place): try: place = place['GeoObject'] except KeyError: raise GeocoderParseError('Failed to parse server response') longitude, latitude = ( float(_) for _ in place['Point']['pos'].split(' ') ) name_elements = ['name', 'description'] location = ', '.join([place[k] for k in name_elements if place.get(k)]) return Location(location, (latitude, longitude), place) if exactly_one: try: return parse_code(places[0]) except IndexError: return None else: return [parse_code(place) for place in places]
21,166
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/pelias.py
Pelias.__init__
( self, domain, api_key=None, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, scheme=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None # Make sure to synchronize the changes of this signature in the # inheriting classes (e.g. GeocodeEarth). )
:param str domain: Specify a domain for Pelias API. :param str api_key: Pelias API key, optional. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
:param str domain: Specify a domain for Pelias API.
25
83
def __init__( self, domain, api_key=None, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, scheme=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None # Make sure to synchronize the changes of this signature in the # inheriting classes (e.g. GeocodeEarth). ): """ :param str domain: Specify a domain for Pelias API. :param str api_key: Pelias API key, optional. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.geocode_api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/pelias.py#L25-L83
31
[ 0 ]
1.694915
[ 41, 50, 51, 53, 56 ]
8.474576
false
23.076923
59
1
91.525424
24
def __init__( self, domain, api_key=None, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, scheme=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None # Make sure to synchronize the changes of this signature in the # inheriting classes (e.g. GeocodeEarth). ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.geocode_api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) )
21,167
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/pelias.py
Pelias.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, boundary_rect=None, countries=None, country_bias=None, language=None )
return self._call_geocoder(url, callback, timeout=timeout)
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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :type boundary_rect: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param boundary_rect: Coordinates to restrict search within. Example: ``[Point(22, 180), Point(-22, -180)]``. :param list countries: A list of country codes specified in `ISO 3166-1 alpha-2 or alpha-3 <https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3>`_ format, e.g. ``['USA', 'CAN']``. This is a hard filter. .. versionadded:: 2.3 :param str country_bias: Bias results to this country (ISO alpha-3). .. deprecated:: 2.3 Use ``countries`` instead. This option behaves the same way, i.e. it's not a soft filter as the name suggests. This parameter is scheduled for removal in geopy 3.0. :param str language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
85
173
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, boundary_rect=None, countries=None, country_bias=None, language=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 available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :type boundary_rect: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param boundary_rect: Coordinates to restrict search within. Example: ``[Point(22, 180), Point(-22, -180)]``. :param list countries: A list of country codes specified in `ISO 3166-1 alpha-2 or alpha-3 <https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3>`_ format, e.g. ``['USA', 'CAN']``. This is a hard filter. .. versionadded:: 2.3 :param str country_bias: Bias results to this country (ISO alpha-3). .. deprecated:: 2.3 Use ``countries`` instead. This option behaves the same way, i.e. it's not a soft filter as the name suggests. This parameter is scheduled for removal in geopy 3.0. :param str language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {'text': query} if self.api_key: params.update({ 'api_key': self.api_key }) if boundary_rect: lon1, lat1, lon2, lat2 = self._format_bounding_box( boundary_rect, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s").split(',') params['boundary.rect.min_lon'] = lon1 params['boundary.rect.min_lat'] = lat1 params['boundary.rect.max_lon'] = lon2 params['boundary.rect.max_lat'] = lat2 if country_bias: warnings.warn( "`country_bias` is deprecated, because it's not " "a soft filter as the name suggests. Pass a list to the " "`countries` option instead, which behaves the same " "way. In geopy 3 the `country_bias` option will be removed.", DeprecationWarning, stacklevel=2, ) params['boundary.country'] = country_bias if countries: params['boundary.country'] = ",".join(countries) if language: params["lang"] = language url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode_api: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/pelias.py#L85-L173
31
[ 0 ]
1.123596
[ 53, 55, 56, 60, 61, 63, 64, 65, 66, 68, 69, 77, 79, 80, 82, 83, 85, 86, 87, 88 ]
22.47191
false
23.076923
89
6
77.52809
40
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, boundary_rect=None, countries=None, country_bias=None, language=None ): params = {'text': query} if self.api_key: params.update({ 'api_key': self.api_key }) if boundary_rect: lon1, lat1, lon2, lat2 = self._format_bounding_box( boundary_rect, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s").split(',') params['boundary.rect.min_lon'] = lon1 params['boundary.rect.min_lat'] = lat1 params['boundary.rect.max_lon'] = lon2 params['boundary.rect.max_lat'] = lat2 if country_bias: warnings.warn( "`country_bias` is deprecated, because it's not " "a soft filter as the name suggests. Pass a list to the " "`countries` option instead, which behaves the same " "way. In geopy 3 the `country_bias` option will be removed.", DeprecationWarning, stacklevel=2, ) params['boundary.country'] = country_bias if countries: params['boundary.country'] = ",".join(countries) if language: params["lang"] = language url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode_api: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,168
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/pelias.py
Pelias.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None )
return self._call_geocoder(url, callback, timeout=timeout)
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"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
175
228
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 addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ try: lat, lon = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'point.lat': lat, 'point.lon': lon, } if language: params['lang'] = language if self.api_key: params.update({ 'api_key': self.api_key }) url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/pelias.py#L175-L228
31
[ 0 ]
1.851852
[ 33, 34, 35, 36, 37, 42, 43, 45, 46, 50, 51, 52, 53 ]
24.074074
false
23.076923
54
4
75.925926
23
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None ): try: lat, lon = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'point.lat': lat, 'point.lon': lon, } if language: params['lang'] = language if self.api_key: params.update({ 'api_key': self.api_key }) url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,169
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/pelias.py
Pelias._parse_code
(self, feature)
return Location(placename, (latitude, longitude), feature)
230
235
def _parse_code(self, feature): # Parse each resource. latitude = feature.get('geometry', {}).get('coordinates', [])[1] longitude = feature.get('geometry', {}).get('coordinates', [])[0] placename = feature.get('properties', {}).get('name') return Location(placename, (latitude, longitude), feature)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/pelias.py#L230-L235
31
[ 0, 1 ]
33.333333
[ 2, 3, 4, 5 ]
66.666667
false
23.076923
6
1
33.333333
0
def _parse_code(self, feature): # Parse each resource. latitude = feature.get('geometry', {}).get('coordinates', [])[1] longitude = feature.get('geometry', {}).get('coordinates', [])[0] placename = feature.get('properties', {}).get('name') return Location(placename, (latitude, longitude), feature)
21,170
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/pelias.py
Pelias._parse_json
(self, response, exactly_one)
237
246
def _parse_json(self, response, exactly_one): if response is None: return None features = response['features'] if not len(features): return None if exactly_one: return self._parse_code(features[0]) else: return [self._parse_code(feature) for feature in features]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/pelias.py#L237-L246
31
[ 0 ]
10
[ 1, 2, 3, 4, 5, 6, 7, 9 ]
80
false
23.076923
10
5
20
0
def _parse_json(self, response, exactly_one): if response is None: return None features = response['features'] if not len(features): return None if exactly_one: return self._parse_code(features[0]) else: return [self._parse_code(feature) for feature in features]
21,171
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/algolia.py
AlgoliaPlaces.__init__
( self, *, app_id=None, api_key=None, domain='places-dsn.algolia.net', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str app_id: Unique application identifier. It's used to identify you when using Algolia's API. See https://www.algolia.com/dashboard. :param str api_key: Algolia's user API key. :param str domain: Currently it is ``'places-dsn.algolia.net'``, can be changed for testing purposes. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
:param str app_id: Unique application identifier. It's used to identify you when using Algolia's API. See https://www.algolia.com/dashboard.
23
85
def __init__( self, *, app_id=None, api_key=None, domain='places-dsn.algolia.net', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str app_id: Unique application identifier. It's used to identify you when using Algolia's API. See https://www.algolia.com/dashboard. :param str api_key: Algolia's user API key. :param str domain: Currently it is ``'places-dsn.algolia.net'``, can be changed for testing purposes. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.domain = domain.strip('/') self.app_id = app_id self.api_key = api_key self.geocode_api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/algolia.py#L23-L85
31
[ 0 ]
1.587302
[ 44, 52, 54, 55, 57, 60 ]
9.52381
false
19.512195
63
1
90.47619
29
def __init__( self, *, app_id=None, api_key=None, domain='places-dsn.algolia.net', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.domain = domain.strip('/') self.app_id = app_id self.api_key = api_key self.geocode_api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) )
21,172
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/algolia.py
AlgoliaPlaces.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, type=None, restrict_searchable_attributes=None, limit=None, language=None, countries=None, around=None, around_via_ip=None, around_radius=None, x_forwarded_for=None )
return self._call_geocoder(url, callback, headers=headers, timeout=timeout)
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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str type: Restrict the search results to a specific type. Available types are defined in documentation: https://community.algolia.com/places/api-clients.html#api-options-type :param str restrict_searchable_attributes: Restrict the fields in which the search is done. :param int limit: Limit the maximum number of items in the response. If not provided and there are multiple results Algolia API will return 20 results by default. This will be reset to one if ``exactly_one`` is True. :param str language: If specified, restrict the search results to a single language. You can pass two letters country codes (ISO 639-1). :param list countries: If specified, restrict the search results to a specific list of countries. You can pass two letters country codes (ISO 3166-1). :param around: Force to first search around a specific latitude longitude. :type around: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool around_via_ip: Whether or not to first search around the geolocation of the user found via his IP address. This is true by default. :param int around_radius: Radius in meters to search around the latitude/longitude. Otherwise a default radius is automatically computed given the area density. :param str x_forwarded_for: Override the HTTP header X-Forwarded-For. With this you can control the source IP address used to resolve the geo-location of the user. This is particularly useful when you want to use the API from your backend as if it was from your end-users' locations. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
87
206
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, type=None, restrict_searchable_attributes=None, limit=None, language=None, countries=None, around=None, around_via_ip=None, around_radius=None, x_forwarded_for=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 available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str type: Restrict the search results to a specific type. Available types are defined in documentation: https://community.algolia.com/places/api-clients.html#api-options-type :param str restrict_searchable_attributes: Restrict the fields in which the search is done. :param int limit: Limit the maximum number of items in the response. If not provided and there are multiple results Algolia API will return 20 results by default. This will be reset to one if ``exactly_one`` is True. :param str language: If specified, restrict the search results to a single language. You can pass two letters country codes (ISO 639-1). :param list countries: If specified, restrict the search results to a specific list of countries. You can pass two letters country codes (ISO 3166-1). :param around: Force to first search around a specific latitude longitude. :type around: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool around_via_ip: Whether or not to first search around the geolocation of the user found via his IP address. This is true by default. :param int around_radius: Radius in meters to search around the latitude/longitude. Otherwise a default radius is automatically computed given the area density. :param str x_forwarded_for: Override the HTTP header X-Forwarded-For. With this you can control the source IP address used to resolve the geo-location of the user. This is particularly useful when you want to use the API from your backend as if it was from your end-users' locations. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'query': query, } if type is not None: params['type'] = type if restrict_searchable_attributes is not None: params['restrictSearchableAttributes'] = restrict_searchable_attributes if limit is not None: params['hitsPerPage'] = limit if exactly_one: params["hitsPerPage"] = 1 if language is not None: params['language'] = language.lower() if countries is not None: params['countries'] = ','.join([c.lower() for c in countries]) if around is not None: p = Point(around) params['aroundLatLng'] = "%s,%s" % (p.latitude, p.longitude) if around_via_ip is not None: params['aroundLatLngViaIP'] = \ 'true' if around_via_ip else 'false' if around_radius is not None: params['aroundRadius'] = around_radius url = '?'.join((self.geocode_api, urlencode(params))) headers = {} if x_forwarded_for is not None: headers['X-Forwarded-For'] = x_forwarded_for if self.app_id is not None and self.api_key is not None: headers['X-Algolia-Application-Id'] = self.app_id headers['X-Algolia-API-Key'] = self.api_key logger.debug('%s.geocode: %s', self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one, language=language) return self._call_geocoder(url, callback, headers=headers, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/algolia.py#L87-L206
31
[ 0 ]
0.833333
[ 74, 78, 79, 81, 82, 84, 85, 87, 88, 90, 91, 93, 94, 96, 97, 98, 100, 101, 104, 105, 107, 108, 110, 111, 113, 114, 115, 117, 118, 119 ]
25
false
19.512195
120
14
75
54
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, type=None, restrict_searchable_attributes=None, limit=None, language=None, countries=None, around=None, around_via_ip=None, around_radius=None, x_forwarded_for=None ): params = { 'query': query, } if type is not None: params['type'] = type if restrict_searchable_attributes is not None: params['restrictSearchableAttributes'] = restrict_searchable_attributes if limit is not None: params['hitsPerPage'] = limit if exactly_one: params["hitsPerPage"] = 1 if language is not None: params['language'] = language.lower() if countries is not None: params['countries'] = ','.join([c.lower() for c in countries]) if around is not None: p = Point(around) params['aroundLatLng'] = "%s,%s" % (p.latitude, p.longitude) if around_via_ip is not None: params['aroundLatLngViaIP'] = \ 'true' if around_via_ip else 'false' if around_radius is not None: params['aroundRadius'] = around_radius url = '?'.join((self.geocode_api, urlencode(params))) headers = {} if x_forwarded_for is not None: headers['X-Forwarded-For'] = x_forwarded_for if self.app_id is not None and self.api_key is not None: headers['X-Algolia-Application-Id'] = self.app_id headers['X-Algolia-API-Key'] = self.api_key logger.debug('%s.geocode: %s', self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one, language=language) return self._call_geocoder(url, callback, headers=headers, timeout=timeout)
21,173
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/algolia.py
AlgoliaPlaces.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, language=None )
return self._call_geocoder(url, callback, headers=headers, timeout=timeout)
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"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: Limit the maximum number of items in the response. If not provided and there are multiple results Algolia API will return 20 results by default. This will be reset to one if ``exactly_one`` is True. :param str language: If specified, restrict the search results to a single language. You can pass two letters country codes (ISO 639-1). :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
208
266
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, language=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"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: Limit the maximum number of items in the response. If not provided and there are multiple results Algolia API will return 20 results by default. This will be reset to one if ``exactly_one`` is True. :param str language: If specified, restrict the search results to a single language. You can pass two letters country codes (ISO 639-1). :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ location = self._coerce_point_to_string(query) params = { 'aroundLatLng': location, } if limit is not None: params['hitsPerPage'] = limit if language is not None: params['language'] = language url = '?'.join((self.reverse_api, urlencode(params))) headers = {} if self.app_id is not None and self.api_key is not None: headers['X-Algolia-Application-Id'] = self.app_id headers['X-Algolia-API-Key'] = self.api_key logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one, language=language) return self._call_geocoder(url, callback, headers=headers, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/algolia.py#L208-L266
31
[ 0 ]
1.694915
[ 37, 39, 43, 44, 46, 47, 49, 50, 52, 53, 54, 56, 57, 58 ]
23.728814
false
19.512195
59
5
76.271186
26
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, language=None ): location = self._coerce_point_to_string(query) params = { 'aroundLatLng': location, } if limit is not None: params['hitsPerPage'] = limit if language is not None: params['language'] = language url = '?'.join((self.reverse_api, urlencode(params))) headers = {} if self.app_id is not None and self.api_key is not None: headers['X-Algolia-Application-Id'] = self.app_id headers['X-Algolia-API-Key'] = self.api_key logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one, language=language) return self._call_geocoder(url, callback, headers=headers, timeout=timeout)
21,174
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/algolia.py
AlgoliaPlaces._parse_feature
(self, feature, language)
return Location(placename, (latitude, longitude), feature)
268
281
def _parse_feature(self, feature, language): # Parse each resource. latitude = feature.get('_geoloc', {}).get('lat') longitude = feature.get('_geoloc', {}).get('lng') if isinstance(feature['locale_names'], collections.abc.Mapping): if language in feature['locale_names']: placename = feature['locale_names'][language][0] else: placename = feature['locale_names']["default"][0] else: placename = feature['locale_names'][0] return Location(placename, (latitude, longitude), feature)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/algolia.py#L268-L281
31
[ 0, 1 ]
14.285714
[ 2, 3, 5, 6, 7, 9, 11, 13 ]
57.142857
false
19.512195
14
3
42.857143
0
def _parse_feature(self, feature, language): # Parse each resource. latitude = feature.get('_geoloc', {}).get('lat') longitude = feature.get('_geoloc', {}).get('lng') if isinstance(feature['locale_names'], collections.abc.Mapping): if language in feature['locale_names']: placename = feature['locale_names'][language][0] else: placename = feature['locale_names']["default"][0] else: placename = feature['locale_names'][0] return Location(placename, (latitude, longitude), feature)
21,175
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/algolia.py
AlgoliaPlaces._parse_json
(self, response, exactly_one, language)
283
294
def _parse_json(self, response, exactly_one, language): if response is None or 'hits' not in response: return None features = response['hits'] if not len(features): return None if exactly_one: return self._parse_feature(features[0], language=language) else: return [ self._parse_feature(feature, language=language) for feature in features ]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/algolia.py#L283-L294
31
[ 0 ]
8.333333
[ 1, 2, 3, 4, 5, 6, 7, 9 ]
66.666667
false
19.512195
12
6
33.333333
0
def _parse_json(self, response, exactly_one, language): if response is None or 'hits' not in response: return None features = response['hits'] if not len(features): return None if exactly_one: return self._parse_feature(features[0], language=language) else: return [ self._parse_feature(feature, language=language) for feature in features ]
21,176
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/nominatim.py
Nominatim.__init__
( self, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain=_DEFAULT_NOMINATIM_DOMAIN, scheme=None, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None # Make sure to synchronize the changes of this signature in the # inheriting classes (e.g. PickPoint). )
:param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str domain: Domain where the target Nominatim service is hosted. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
53
118
def __init__( self, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain=_DEFAULT_NOMINATIM_DOMAIN, scheme=None, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None # Make sure to synchronize the changes of this signature in the # inheriting classes (e.g. PickPoint). ): """ :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str domain: Domain where the target Nominatim service is hosted. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.domain = domain.strip('/') if (self.domain == _DEFAULT_NOMINATIM_DOMAIN and self.headers['User-Agent'] in _REJECTED_USER_AGENTS): raise ConfigurationError( 'Using Nominatim with default or sample `user_agent` "%s" is ' 'strongly discouraged, as it violates Nominatim\'s ToS ' 'https://operations.osmfoundation.org/policies/nominatim/ ' 'and may possibly cause 403 and 429 HTTP errors. ' 'Please specify a custom `user_agent` with ' '`Nominatim(user_agent="my-application")` or by ' 'overriding the default `user_agent`: ' '`geopy.geocoders.options.default_user_agent = "my-application"`.' % self.headers['User-Agent'] ) self.api = "%s://%s%s" % (self.scheme, self.domain, self.geocode_path) self.reverse_api = "%s://%s%s" % (self.scheme, self.domain, self.reverse_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/nominatim.py#L53-L118
31
[ 0, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 63, 64, 65 ]
27.272727
[ 52 ]
1.515152
false
23.364486
66
3
98.484848
23
def __init__( self, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain=_DEFAULT_NOMINATIM_DOMAIN, scheme=None, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None # Make sure to synchronize the changes of this signature in the # inheriting classes (e.g. PickPoint). ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.domain = domain.strip('/') if (self.domain == _DEFAULT_NOMINATIM_DOMAIN and self.headers['User-Agent'] in _REJECTED_USER_AGENTS): raise ConfigurationError( 'Using Nominatim with default or sample `user_agent` "%s" is ' 'strongly discouraged, as it violates Nominatim\'s ToS ' 'https://operations.osmfoundation.org/policies/nominatim/ ' 'and may possibly cause 403 and 429 HTTP errors. ' 'Please specify a custom `user_agent` with ' '`Nominatim(user_agent="my-application")` or by ' 'overriding the default `user_agent`: ' '`geopy.geocoders.options.default_user_agent = "my-application"`.' % self.headers['User-Agent'] ) self.api = "%s://%s%s" % (self.scheme, self.domain, self.geocode_path) self.reverse_api = "%s://%s%s" % (self.scheme, self.domain, self.reverse_path)
21,177
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/nominatim.py
Nominatim._construct_url
(self, base_api, params)
return "?".join((base_api, urlencode(params)))
Construct geocoding request url. The method can be overridden in Nominatim-based geocoders in order to extend URL parameters. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL.
Construct geocoding request url. The method can be overridden in Nominatim-based geocoders in order to extend URL parameters.
120
133
def _construct_url(self, base_api, params): """ Construct geocoding request url. The method can be overridden in Nominatim-based geocoders in order to extend URL parameters. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL. """ return "?".join((base_api, urlencode(params)))
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/nominatim.py#L120-L133
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
92.857143
[ 13 ]
7.142857
false
23.364486
14
1
92.857143
10
def _construct_url(self, base_api, params): return "?".join((base_api, urlencode(params)))
21,178
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/nominatim.py
Nominatim.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, addressdetails=False, language=False, geometry=None, extratags=False, country_codes=None, viewbox=None, bounded=False, featuretype=None, namedetails=False )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param query: The address, query or a structured query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `street`, `city`, `county`, `state`, `country`, or `postalcode`. For more information, see Nominatim's documentation for `structured requests`: https://nominatim.org/release-docs/develop/api/Search :type query: dict or str :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: Maximum amount of results to return from Nominatim. Unless exactly_one is set to False, limit will always be 1. :param bool addressdetails: If you want in *Location.raw* to include address details such as house_number, city_district, postcode, etc (in a structured form) set it to True :param str language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :param str geometry: If present, specifies whether the geocoding service should return the result's geometry in `wkt`, `svg`, `kml`, or `geojson` formats. This is available via the `raw` attribute on the returned :class:`geopy.location.Location` object. :param bool extratags: Include additional information in the result if available, e.g. wikipedia link, opening hours. :param country_codes: Limit search results to a specific country (or a list of countries). A country_code should be the ISO 3166-1alpha2 code, e.g. ``gb`` for the United Kingdom, ``de`` for Germany, etc. :type country_codes: str or list :type viewbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param viewbox: Prefer this area to find search results. By default this is treated as a hint, if you want to restrict results to this area, specify ``bounded=True`` as well. Example: ``[Point(22, 180), Point(-22, -180)]``. :param bool bounded: Restrict the results to only items contained within the bounding ``viewbox``. :param str featuretype: If present, restrict results to certain type of features. Allowed values: `country`, `state`, `city`, `settlement`. :param bool namedetails: If you want in *Location.raw* to include namedetails, set it to True. This will be a list of alternative names, including language variants, etc. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
135
297
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, bounded=False, featuretype=None, namedetails=False ): """ Return a location point by address. :param query: The address, query or a structured query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `street`, `city`, `county`, `state`, `country`, or `postalcode`. For more information, see Nominatim's documentation for `structured requests`: https://nominatim.org/release-docs/develop/api/Search :type query: dict or str :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: Maximum amount of results to return from Nominatim. Unless exactly_one is set to False, limit will always be 1. :param bool addressdetails: If you want in *Location.raw* to include address details such as house_number, city_district, postcode, etc (in a structured form) set it to True :param str language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :param str geometry: If present, specifies whether the geocoding service should return the result's geometry in `wkt`, `svg`, `kml`, or `geojson` formats. This is available via the `raw` attribute on the returned :class:`geopy.location.Location` object. :param bool extratags: Include additional information in the result if available, e.g. wikipedia link, opening hours. :param country_codes: Limit search results to a specific country (or a list of countries). A country_code should be the ISO 3166-1alpha2 code, e.g. ``gb`` for the United Kingdom, ``de`` for Germany, etc. :type country_codes: str or list :type viewbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param viewbox: Prefer this area to find search results. By default this is treated as a hint, if you want to restrict results to this area, specify ``bounded=True`` as well. Example: ``[Point(22, 180), Point(-22, -180)]``. :param bool bounded: Restrict the results to only items contained within the bounding ``viewbox``. :param str featuretype: If present, restrict results to certain type of features. Allowed values: `country`, `state`, `city`, `settlement`. :param bool namedetails: If you want in *Location.raw* to include namedetails, set it to True. This will be a list of alternative names, including language variants, etc. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } else: params = {'q': query} params.update({ 'format': 'json' }) if exactly_one: params['limit'] = 1 elif limit is not None: limit = int(limit) if limit < 1: raise ValueError("Limit cannot be less than 1") params['limit'] = limit if viewbox: params['viewbox'] = self._format_bounding_box( viewbox, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if bounded: params['bounded'] = 1 if not country_codes: country_codes = [] if isinstance(country_codes, str): country_codes = [country_codes] if country_codes: params['countrycodes'] = ",".join(country_codes) if addressdetails: params['addressdetails'] = 1 if namedetails: params['namedetails'] = 1 if language: params['accept-language'] = language if extratags: params['extratags'] = True if geometry is not None: geometry = geometry.lower() if geometry == 'wkt': params['polygon_text'] = 1 elif geometry == 'svg': params['polygon_svg'] = 1 elif geometry == 'kml': params['polygon_kml'] = 1 elif geometry == 'geojson': params['polygon_geojson'] = 1 else: raise GeocoderQueryError( "Invalid geometry format. Must be one of: " "wkt, svg, kml, geojson." ) if featuretype: params['featuretype'] = featuretype url = self._construct_url(self.api, params) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/nominatim.py#L135-L297
31
[ 0 ]
0.613497
[ 92, 93, 100, 102, 106, 107, 108, 109, 110, 111, 112, 114, 115, 118, 119, 121, 122, 123, 124, 125, 126, 128, 129, 131, 132, 134, 135, 137, 138, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 151, 156, 157, 159, 160, 161, 162 ]
28.220859
false
23.364486
163
20
71.779141
71
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, bounded=False, featuretype=None, namedetails=False ): if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } else: params = {'q': query} params.update({ 'format': 'json' }) if exactly_one: params['limit'] = 1 elif limit is not None: limit = int(limit) if limit < 1: raise ValueError("Limit cannot be less than 1") params['limit'] = limit if viewbox: params['viewbox'] = self._format_bounding_box( viewbox, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if bounded: params['bounded'] = 1 if not country_codes: country_codes = [] if isinstance(country_codes, str): country_codes = [country_codes] if country_codes: params['countrycodes'] = ",".join(country_codes) if addressdetails: params['addressdetails'] = 1 if namedetails: params['namedetails'] = 1 if language: params['accept-language'] = language if extratags: params['extratags'] = True if geometry is not None: geometry = geometry.lower() if geometry == 'wkt': params['polygon_text'] = 1 elif geometry == 'svg': params['polygon_svg'] = 1 elif geometry == 'kml': params['polygon_kml'] = 1 elif geometry == 'geojson': params['polygon_geojson'] = 1 else: raise GeocoderQueryError( "Invalid geometry format. Must be one of: " "wkt, svg, kml, geojson." ) if featuretype: params['featuretype'] = featuretype url = self._construct_url(self.api, params) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,179
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/nominatim.py
Nominatim.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=False, addressdetails=True, zoom=None, namedetails=False, )
return self._call_geocoder(url, callback, timeout=timeout)
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"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :param bool addressdetails: Whether or not to include address details, such as city, county, state, etc. in *Location.raw* :param int zoom: Level of detail required for the address, an integer in range from 0 (country level) to 18 (building level), default is 18. :param bool namedetails: If you want in *Location.raw* to include namedetails, set it to True. This will be a list of alternative names, including language variants, etc. .. versionadded:: 2.3 :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
299
372
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=False, addressdetails=True, zoom=None, namedetails=False, ): """ 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"``. :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 raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: Preferred language in which to return results. Either uses standard `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`_ accept-language string or a simple comma-separated list of language codes. :param bool addressdetails: Whether or not to include address details, such as city, county, state, etc. in *Location.raw* :param int zoom: Level of detail required for the address, an integer in range from 0 (country level) to 18 (building level), default is 18. :param bool namedetails: If you want in *Location.raw* to include namedetails, set it to True. This will be a list of alternative names, including language variants, etc. .. versionadded:: 2.3 :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ try: lat, lon = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'lat': lat, 'lon': lon, 'format': 'json', } if language: params['accept-language'] = language params['addressdetails'] = 1 if addressdetails else 0 if zoom is not None: params['zoom'] = zoom if namedetails: params['namedetails'] = 1 url = self._construct_url(self.reverse_api, params) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/nominatim.py#L299-L372
31
[ 0 ]
1.351351
[ 50, 51, 52, 53, 54, 59, 60, 62, 64, 65, 67, 68, 70, 71, 72, 73 ]
21.621622
false
23.364486
74
5
78.378378
36
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=False, addressdetails=True, zoom=None, namedetails=False, ): try: lat, lon = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'lat': lat, 'lon': lon, 'format': 'json', } if language: params['accept-language'] = language params['addressdetails'] = 1 if addressdetails else 0 if zoom is not None: params['zoom'] = zoom if namedetails: params['namedetails'] = 1 url = self._construct_url(self.reverse_api, params) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,180
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/nominatim.py
Nominatim._parse_code
(self, place)
return Location(placename, (latitude, longitude), place)
374
382
def _parse_code(self, place): # Parse each resource. latitude = place.get('lat', None) longitude = place.get('lon', None) placename = place.get('display_name', None) if latitude is not None and longitude is not None: latitude = float(latitude) longitude = float(longitude) return Location(placename, (latitude, longitude), place)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/nominatim.py#L374-L382
31
[ 0, 1 ]
22.222222
[ 2, 3, 4, 5, 6, 7, 8 ]
77.777778
false
23.364486
9
3
22.222222
0
def _parse_code(self, place): # Parse each resource. latitude = place.get('lat', None) longitude = place.get('lon', None) placename = place.get('display_name', None) if latitude is not None and longitude is not None: latitude = float(latitude) longitude = float(longitude) return Location(placename, (latitude, longitude), place)
21,181
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/nominatim.py
Nominatim._parse_json
(self, places, exactly_one)
384
400
def _parse_json(self, places, exactly_one): if not places: return None if isinstance(places, collections.abc.Mapping) and 'error' in places: if places['error'] == 'Unable to geocode': # no results in reverse return None else: raise GeocoderQueryError(places['error']) if not isinstance(places, collections.abc.Sequence): places = [places] if exactly_one: return self._parse_code(places[0]) else: return [self._parse_code(place) for place in places]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/nominatim.py#L384-L400
31
[ 0 ]
5.882353
[ 1, 2, 4, 5, 7, 9, 11, 12, 13, 14, 16 ]
64.705882
false
23.364486
17
8
35.294118
0
def _parse_json(self, places, exactly_one): if not places: return None if isinstance(places, collections.abc.Mapping) and 'error' in places: if places['error'] == 'Unable to geocode': # no results in reverse return None else: raise GeocoderQueryError(places['error']) if not isinstance(places, collections.abc.Sequence): places = [places] if exactly_one: return self._parse_code(places[0]) else: return [self._parse_code(place) for place in places]
21,182
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
_is_last_gen
(count)
return chain((False for _ in range(count)), [True])
list(_is_last_gen(2)) -> [False, False, True]
list(_is_last_gen(2)) -> [False, False, True]
64
66
def _is_last_gen(count): """list(_is_last_gen(2)) -> [False, False, True]""" return chain((False for _ in range(count)), [True])
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L64-L66
31
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
26.086957
3
1
66.666667
1
def _is_last_gen(count): return chain((False for _ in range(count)), [True])
21,183
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
BaseRateLimiter.__init__
( self, *, min_delay_seconds, max_retries, swallow_exceptions, return_value_on_exception )
74
90
def __init__( self, *, min_delay_seconds, max_retries, swallow_exceptions, return_value_on_exception ): self.min_delay_seconds = min_delay_seconds self.max_retries = max_retries self.swallow_exceptions = swallow_exceptions self.return_value_on_exception = return_value_on_exception assert max_retries >= 0 # State: self._lock = threading.Lock() self._last_call = None
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L74-L90
31
[ 0 ]
5.882353
[ 8, 9, 10, 11, 12, 15, 16 ]
41.176471
false
26.086957
17
2
58.823529
0
def __init__( self, *, min_delay_seconds, max_retries, swallow_exceptions, return_value_on_exception ): self.min_delay_seconds = min_delay_seconds self.max_retries = max_retries self.swallow_exceptions = swallow_exceptions self.return_value_on_exception = return_value_on_exception assert max_retries >= 0 # State: self._lock = threading.Lock() self._last_call = None
21,184
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
BaseRateLimiter._clock
(self)
return default_timer()
92
93
def _clock(self): # pragma: no cover return default_timer()
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L92-L93
31
[]
0
[]
0
false
26.086957
2
1
100
0
def _clock(self): # pragma: no cover return default_timer()
21,185
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
BaseRateLimiter._acquire_request_slot_gen
(self)
95
131
def _acquire_request_slot_gen(self): # Requests rate is limited by `min_delay_seconds` interval. # # Imagine the time axis as a grid with `min_delay_seconds` step, # where we would call each step as a "request slot". RateLimiter # guarantees that each "request slot" contains at most 1 request. # # Note that actual requests might take longer time than # `min_delay_seconds`. In that case you might want to consider # parallelizing requests (with a ThreadPool for sync mode and # asyncio tasks for async), to keep the requests rate closer # to `min_delay_seconds`. # # This generator thread-safely acquires a "request slot", and # if it fails to do that at this time, it yields the amount # of seconds to sleep until the next attempt. The generator # stops only when the "request slot" has been successfully # acquired. # # There's no ordering between the concurrent requests. The first # request to acquire the lock wins the next "request slot". while True: with self._lock: clock = self._clock() if self._last_call is None: # A first iteration -- start immediately. self._last_call = clock return seconds_since_last_call = clock - self._last_call wait = self.min_delay_seconds - seconds_since_last_call if wait <= 0: # A successfully acquired request slot. self._last_call = clock return # Couldn't acquire a request slot. Wait until the beginning # of the next slot to try again. yield wait
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L95-L131
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
56.756757
[ 21, 22, 23, 24, 26, 27, 28, 29, 30, 32, 33, 36 ]
32.432432
false
26.086957
37
5
67.567568
0
def _acquire_request_slot_gen(self): # Requests rate is limited by `min_delay_seconds` interval. # # Imagine the time axis as a grid with `min_delay_seconds` step, # where we would call each step as a "request slot". RateLimiter # guarantees that each "request slot" contains at most 1 request. # # Note that actual requests might take longer time than # `min_delay_seconds`. In that case you might want to consider # parallelizing requests (with a ThreadPool for sync mode and # asyncio tasks for async), to keep the requests rate closer # to `min_delay_seconds`. # # This generator thread-safely acquires a "request slot", and # if it fails to do that at this time, it yields the amount # of seconds to sleep until the next attempt. The generator # stops only when the "request slot" has been successfully # acquired. # # There's no ordering between the concurrent requests. The first # request to acquire the lock wins the next "request slot". while True: with self._lock: clock = self._clock() if self._last_call is None: # A first iteration -- start immediately. self._last_call = clock return seconds_since_last_call = clock - self._last_call wait = self.min_delay_seconds - seconds_since_last_call if wait <= 0: # A successfully acquired request slot. self._last_call = clock return # Couldn't acquire a request slot. Wait until the beginning # of the next slot to try again. yield wait
21,186
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
BaseRateLimiter._retries_gen
(self, args, kwargs)
133
154
def _retries_gen(self, args, kwargs): for i, is_last_try in zip(count(), _is_last_gen(self.max_retries)): try: yield i # Run the function. except self._retry_exceptions: if is_last_try: yield True # The exception should be raised else: logger.warning( type(self).__name__ + " caught an error, retrying " "(%s/%s tries). Called with (*%r, **%r).", i, self.max_retries, args, kwargs, exc_info=True, ) yield False # The exception has been swallowed. continue else: # A successful run -- stop retrying: return
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L133-L154
31
[ 0 ]
4.761905
[ 1, 2, 3, 4, 5, 6, 8, 17, 18 ]
42.857143
false
26.086957
22
4
57.142857
0
def _retries_gen(self, args, kwargs): for i, is_last_try in zip(count(), _is_last_gen(self.max_retries)): try: yield i # Run the function. except self._retry_exceptions: if is_last_try: yield True # The exception should be raised else: logger.warning( type(self).__name__ + " caught an error, retrying " "(%s/%s tries). Called with (*%r, **%r).", i, self.max_retries, args, kwargs, exc_info=True, ) yield False # The exception has been swallowed. continue else: # A successful run -- stop retrying: return
21,187
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
BaseRateLimiter._handle_exc
(self, args, kwargs)
156
168
def _handle_exc(self, args, kwargs): if self.swallow_exceptions: logger.warning( type(self).__name__ + " swallowed an error after %r retries. " "Called with (*%r, **%r).", self.max_retries, args, kwargs, exc_info=True, ) return self.return_value_on_exception else: raise
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L156-L168
31
[ 0 ]
7.692308
[ 1, 2, 10, 12 ]
30.769231
false
26.086957
13
2
69.230769
0
def _handle_exc(self, args, kwargs): if self.swallow_exceptions: logger.warning( type(self).__name__ + " swallowed an error after %r retries. " "Called with (*%r, **%r).", self.max_retries, args, kwargs, exc_info=True, ) return self.return_value_on_exception else: raise
21,188
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
RateLimiter.__init__
( self, func, *, min_delay_seconds=0.0, max_retries=2, error_wait_seconds=5.0, swallow_exceptions=True, return_value_on_exception=None )
:param callable func: A function which should be wrapped by the rate limiter. :param float min_delay_seconds: Minimum delay in seconds between the wrapped ``func`` calls. To convert :abbr:`RPS (Requests Per Second)` rate to ``min_delay_seconds`` you need to divide 1 by RPS. For example, if you need to keep the rate at 20 RPS, you can use ``min_delay_seconds=1/20``. :param int max_retries: Number of retries on exceptions. Only :class:`geopy.exc.GeocoderServiceError` exceptions are retried -- others are always re-raised. ``max_retries + 1`` requests would be performed at max per query. Set ``max_retries=0`` to disable retries. :param float error_wait_seconds: Time to wait between retries after errors. Must be greater or equal to ``min_delay_seconds``. :param bool swallow_exceptions: Should an exception be swallowed after retries? If not, it will be re-raised. If yes, the ``return_value_on_exception`` will be returned. :param return_value_on_exception: Value to return on failure when ``swallow_exceptions=True``.
:param callable func: A function which should be wrapped by the rate limiter.
209
259
def __init__( self, func, *, min_delay_seconds=0.0, max_retries=2, error_wait_seconds=5.0, swallow_exceptions=True, return_value_on_exception=None ): """ :param callable func: A function which should be wrapped by the rate limiter. :param float min_delay_seconds: Minimum delay in seconds between the wrapped ``func`` calls. To convert :abbr:`RPS (Requests Per Second)` rate to ``min_delay_seconds`` you need to divide 1 by RPS. For example, if you need to keep the rate at 20 RPS, you can use ``min_delay_seconds=1/20``. :param int max_retries: Number of retries on exceptions. Only :class:`geopy.exc.GeocoderServiceError` exceptions are retried -- others are always re-raised. ``max_retries + 1`` requests would be performed at max per query. Set ``max_retries=0`` to disable retries. :param float error_wait_seconds: Time to wait between retries after errors. Must be greater or equal to ``min_delay_seconds``. :param bool swallow_exceptions: Should an exception be swallowed after retries? If not, it will be re-raised. If yes, the ``return_value_on_exception`` will be returned. :param return_value_on_exception: Value to return on failure when ``swallow_exceptions=True``. """ super().__init__( min_delay_seconds=min_delay_seconds, max_retries=max_retries, swallow_exceptions=swallow_exceptions, return_value_on_exception=return_value_on_exception, ) self.func = func self.error_wait_seconds = error_wait_seconds assert error_wait_seconds >= min_delay_seconds assert max_retries >= 0
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L209-L259
31
[ 0 ]
1.960784
[ 41, 47, 48, 49, 50 ]
9.803922
false
26.086957
51
3
90.196078
28
def __init__( self, func, *, min_delay_seconds=0.0, max_retries=2, error_wait_seconds=5.0, swallow_exceptions=True, return_value_on_exception=None ): super().__init__( min_delay_seconds=min_delay_seconds, max_retries=max_retries, swallow_exceptions=swallow_exceptions, return_value_on_exception=return_value_on_exception, ) self.func = func self.error_wait_seconds = error_wait_seconds assert error_wait_seconds >= min_delay_seconds assert max_retries >= 0
21,189
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
RateLimiter._sleep
(self, seconds)
261
263
def _sleep(self, seconds): # pragma: no cover logger.debug(type(self).__name__ + " sleep(%r)", seconds) sleep(seconds)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L261-L263
31
[]
0
[]
0
false
26.086957
3
1
100
0
def _sleep(self, seconds): # pragma: no cover logger.debug(type(self).__name__ + " sleep(%r)", seconds) sleep(seconds)
21,190
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
RateLimiter._acquire_request_slot
(self)
265
267
def _acquire_request_slot(self): for wait in self._acquire_request_slot_gen(): self._sleep(wait)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L265-L267
31
[ 0 ]
33.333333
[ 1, 2 ]
66.666667
false
26.086957
3
2
33.333333
0
def _acquire_request_slot(self): for wait in self._acquire_request_slot_gen(): self._sleep(wait)
21,191
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
RateLimiter.__call__
(self, *args, **kwargs)
269
287
def __call__(self, *args, **kwargs): gen = self._retries_gen(args, kwargs) for _ in gen: self._acquire_request_slot() try: res = self.func(*args, **kwargs) if inspect.isawaitable(res): raise ValueError( "An async awaitable has been passed to `RateLimiter`. " "Use `AsyncRateLimiter` instead, which supports awaitables." ) return res except self._retry_exceptions as e: if gen.throw(e): # A final try return self._handle_exc(args, kwargs) self._sleep(self.error_wait_seconds) raise RuntimeError("Should not have been reached")
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L269-L287
31
[ 0 ]
5.555556
[ 1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 15, 16 ]
66.666667
false
26.086957
19
5
33.333333
0
def __call__(self, *args, **kwargs): gen = self._retries_gen(args, kwargs) for _ in gen: self._acquire_request_slot() try: res = self.func(*args, **kwargs) if inspect.isawaitable(res): raise ValueError( "An async awaitable has been passed to `RateLimiter`. " "Use `AsyncRateLimiter` instead, which supports awaitables." ) return res except self._retry_exceptions as e: if gen.throw(e): # A final try return self._handle_exc(args, kwargs) self._sleep(self.error_wait_seconds) raise RuntimeError("Should not have been reached")
21,192
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
AsyncRateLimiter.__init__
( self, func, *, min_delay_seconds=0.0, max_retries=2, error_wait_seconds=5.0, swallow_exceptions=True, return_value_on_exception=None )
:param callable func: A function which should be wrapped by the rate limiter. :param float min_delay_seconds: Minimum delay in seconds between the wrapped ``func`` calls. To convert :abbr:`RPS (Requests Per Second)` rate to ``min_delay_seconds`` you need to divide 1 by RPS. For example, if you need to keep the rate at 20 RPS, you can use ``min_delay_seconds=1/20``. :param int max_retries: Number of retries on exceptions. Only :class:`geopy.exc.GeocoderServiceError` exceptions are retried -- others are always re-raised. ``max_retries + 1`` requests would be performed at max per query. Set ``max_retries=0`` to disable retries. :param float error_wait_seconds: Time to wait between retries after errors. Must be greater or equal to ``min_delay_seconds``. :param bool swallow_exceptions: Should an exception be swallowed after retries? If not, it will be re-raised. If yes, the ``return_value_on_exception`` will be returned. :param return_value_on_exception: Value to return on failure when ``swallow_exceptions=True``.
:param callable func: A function which should be wrapped by the rate limiter.
332
382
def __init__( self, func, *, min_delay_seconds=0.0, max_retries=2, error_wait_seconds=5.0, swallow_exceptions=True, return_value_on_exception=None ): """ :param callable func: A function which should be wrapped by the rate limiter. :param float min_delay_seconds: Minimum delay in seconds between the wrapped ``func`` calls. To convert :abbr:`RPS (Requests Per Second)` rate to ``min_delay_seconds`` you need to divide 1 by RPS. For example, if you need to keep the rate at 20 RPS, you can use ``min_delay_seconds=1/20``. :param int max_retries: Number of retries on exceptions. Only :class:`geopy.exc.GeocoderServiceError` exceptions are retried -- others are always re-raised. ``max_retries + 1`` requests would be performed at max per query. Set ``max_retries=0`` to disable retries. :param float error_wait_seconds: Time to wait between retries after errors. Must be greater or equal to ``min_delay_seconds``. :param bool swallow_exceptions: Should an exception be swallowed after retries? If not, it will be re-raised. If yes, the ``return_value_on_exception`` will be returned. :param return_value_on_exception: Value to return on failure when ``swallow_exceptions=True``. """ super().__init__( min_delay_seconds=min_delay_seconds, max_retries=max_retries, swallow_exceptions=swallow_exceptions, return_value_on_exception=return_value_on_exception, ) self.func = func self.error_wait_seconds = error_wait_seconds assert error_wait_seconds >= min_delay_seconds assert max_retries >= 0
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L332-L382
31
[ 0 ]
1.960784
[ 41, 47, 48, 49, 50 ]
9.803922
false
26.086957
51
3
90.196078
28
def __init__( self, func, *, min_delay_seconds=0.0, max_retries=2, error_wait_seconds=5.0, swallow_exceptions=True, return_value_on_exception=None ): super().__init__( min_delay_seconds=min_delay_seconds, max_retries=max_retries, swallow_exceptions=swallow_exceptions, return_value_on_exception=return_value_on_exception, ) self.func = func self.error_wait_seconds = error_wait_seconds assert error_wait_seconds >= min_delay_seconds assert max_retries >= 0
21,193
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
AsyncRateLimiter._sleep
(self, seconds)
384
386
async def _sleep(self, seconds): # pragma: no cover logger.debug(type(self).__name__ + " sleep(%r)", seconds) await asyncio.sleep(seconds)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L384-L386
31
[]
0
[]
0
false
26.086957
3
1
100
0
async def _sleep(self, seconds): # pragma: no cover logger.debug(type(self).__name__ + " sleep(%r)", seconds) await asyncio.sleep(seconds)
21,194
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
AsyncRateLimiter._acquire_request_slot
(self)
388
390
async def _acquire_request_slot(self): for wait in self._acquire_request_slot_gen(): await self._sleep(wait)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L388-L390
31
[ 0 ]
33.333333
[ 1, 2 ]
66.666667
false
26.086957
3
2
33.333333
0
async def _acquire_request_slot(self): for wait in self._acquire_request_slot_gen(): await self._sleep(wait)
21,195
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/extra/rate_limiter.py
AsyncRateLimiter.__call__
(self, *args, **kwargs)
392
404
async def __call__(self, *args, **kwargs): gen = self._retries_gen(args, kwargs) for _ in gen: await self._acquire_request_slot() try: return await self.func(*args, **kwargs) except self._retry_exceptions as e: if gen.throw(e): # A final try return self._handle_exc(args, kwargs) await self._sleep(self.error_wait_seconds) raise RuntimeError("Should not have been reached")
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/extra/rate_limiter.py#L392-L404
31
[ 0 ]
8.333333
[ 1, 2, 3, 4, 5, 6, 7, 9, 10 ]
75
false
26.086957
13
4
25
0
async def __call__(self, *args, **kwargs): gen = self._retries_gen(args, kwargs) for _ in gen: await self._acquire_request_slot() try: return await self.func(*args, **kwargs) except self._retry_exceptions as e: if gen.throw(e): # A final try return self._handle_exc(args, kwargs) await self._sleep(self.error_wait_seconds) raise RuntimeError("Should not have been reached")
21,196
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/openers.py
_query
(url, method, kwargs)
return url, data
21
39
def _query(url, method, kwargs): data = None if 'data' in kwargs: data = kwargs.pop('data') if type(data) in (dict, list, tuple): data = urlencode(data) if isinstance(method, basestring) and \ method.lower() == 'get' and data: if '?' not in url: url += '?' elif url[-1] not in ('?', '&'): url += '&' url += data data = None if data: data = data.encode('utf-8') return url, data
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/openers.py#L21-L39
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 13, 14, 15, 16, 17, 18 ]
84.210526
[ 11, 12 ]
10.526316
false
58.181818
19
9
89.473684
0
def _query(url, method, kwargs): data = None if 'data' in kwargs: data = kwargs.pop('data') if type(data) in (dict, list, tuple): data = urlencode(data) if isinstance(method, basestring) and \ method.lower() == 'get' and data: if '?' not in url: url += '?' elif url[-1] not in ('?', '&'): url += '&' url += data data = None if data: data = data.encode('utf-8') return url, data
21,645
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/openers.py
_requests
(url, kwargs)
return html
42
64
def _requests(url, kwargs): encoding = kwargs.get('encoding') method = kwargs.get('method', 'get').lower() session = kwargs.get('session') if session: meth = getattr(session, str(method)) else: meth = getattr(requests, str(method)) if method == 'get': url, data = _query(url, method, kwargs) kw = {} for k in allowed_args: if k in kwargs: kw[k] = kwargs[k] resp = meth(url=url, timeout=kwargs.get('timeout', DEFAULT_TIMEOUT), **kw) if not (200 <= resp.status_code < 300): raise HTTPError(resp.url, resp.status_code, resp.reason, resp.headers, None) if encoding: resp.encoding = encoding html = resp.text return html
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/openers.py#L42-L64
32
[ 0, 1 ]
8.695652
[ 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22 ]
82.608696
false
58.181818
23
7
17.391304
0
def _requests(url, kwargs): encoding = kwargs.get('encoding') method = kwargs.get('method', 'get').lower() session = kwargs.get('session') if session: meth = getattr(session, str(method)) else: meth = getattr(requests, str(method)) if method == 'get': url, data = _query(url, method, kwargs) kw = {} for k in allowed_args: if k in kwargs: kw[k] = kwargs[k] resp = meth(url=url, timeout=kwargs.get('timeout', DEFAULT_TIMEOUT), **kw) if not (200 <= resp.status_code < 300): raise HTTPError(resp.url, resp.status_code, resp.reason, resp.headers, None) if encoding: resp.encoding = encoding html = resp.text return html
21,646
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/openers.py
_urllib
(url, kwargs)
return urlopen(url, data, timeout=kwargs.get('timeout', DEFAULT_TIMEOUT))
67
70
def _urllib(url, kwargs): method = kwargs.get('method') url, data = _query(url, method, kwargs) return urlopen(url, data, timeout=kwargs.get('timeout', DEFAULT_TIMEOUT))
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/openers.py#L67-L70
32
[ 0, 1, 2, 3 ]
100
[]
0
true
58.181818
4
1
100
0
def _urllib(url, kwargs): method = kwargs.get('method') url, data = _query(url, method, kwargs) return urlopen(url, data, timeout=kwargs.get('timeout', DEFAULT_TIMEOUT))
21,647
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/openers.py
url_opener
(url, kwargs)
return _urllib(url, kwargs)
73
76
def url_opener(url, kwargs): if HAS_REQUEST: return _requests(url, kwargs) return _urllib(url, kwargs)
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/openers.py#L73-L76
32
[ 0, 1, 3 ]
75
[ 2 ]
25
false
58.181818
4
2
75
0
def url_opener(url, kwargs): if HAS_REQUEST: return _requests(url, kwargs) return _urllib(url, kwargs)
21,648
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/text.py
squash_html_whitespace
(text)
return WHITESPACE_RE.sub(' ', text)
20
24
def squash_html_whitespace(text): # use raw extract_text for preformatted content (like <pre> content or set # by CSS rules) # apply this function on top of return WHITESPACE_RE.sub(' ', text)
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/text.py#L20-L24
32
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
98.591549
5
1
100
0
def squash_html_whitespace(text): # use raw extract_text for preformatted content (like <pre> content or set # by CSS rules) # apply this function on top of return WHITESPACE_RE.sub(' ', text)
21,649
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/text.py
_squash_artifical_nl
(parts)
return output
27
36
def _squash_artifical_nl(parts): output, last_nl = [], False for x in parts: if x is not None: output.append(x) last_nl = False elif not last_nl: output.append(None) last_nl = True return output
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/text.py#L27-L36
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
98.591549
10
4
100
0
def _squash_artifical_nl(parts): output, last_nl = [], False for x in parts: if x is not None: output.append(x) last_nl = False elif not last_nl: output.append(None) last_nl = True return output
21,650
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/text.py
_strip_artifical_nl
(parts)
return parts[start_idx:-end_idx if end_idx > 0 else None]
39
50
def _strip_artifical_nl(parts): if not parts: return parts for start_idx, pt in enumerate(parts): if isinstance(pt, str): # 0, 1, 2, index of first string [start_idx:... break iterator = enumerate(parts[:start_idx - 1 if start_idx > 0 else None:-1]) for end_idx, pt in iterator: if isinstance(pt, str): # 0=None, 1=-1, 2=-2, index of last string break return parts[start_idx:-end_idx if end_idx > 0 else None]
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/text.py#L39-L50
32
[ 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
91.666667
[ 2 ]
8.333333
false
98.591549
12
6
91.666667
0
def _strip_artifical_nl(parts): if not parts: return parts for start_idx, pt in enumerate(parts): if isinstance(pt, str): # 0, 1, 2, index of first string [start_idx:... break iterator = enumerate(parts[:start_idx - 1 if start_idx > 0 else None:-1]) for end_idx, pt in iterator: if isinstance(pt, str): # 0=None, 1=-1, 2=-2, index of last string break return parts[start_idx:-end_idx if end_idx > 0 else None]
21,651
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/text.py
_merge_original_parts
(parts)
return output
53
70
def _merge_original_parts(parts): output, orp_buf = [], [] def flush(): if orp_buf: item = squash_html_whitespace(''.join(orp_buf)).strip() if item: output.append(item) orp_buf[:] = [] for x in parts: if not isinstance(x, str): flush() output.append(x) else: orp_buf.append(x) flush() return output
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/text.py#L53-L70
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17 ]
94.444444
[]
0
false
98.591549
18
6
100
0
def _merge_original_parts(parts): output, orp_buf = [], [] def flush(): if orp_buf: item = squash_html_whitespace(''.join(orp_buf)).strip() if item: output.append(item) orp_buf[:] = [] for x in parts: if not isinstance(x, str): flush() output.append(x) else: orp_buf.append(x) flush() return output
21,652
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/text.py
extract_text_array
(dom, squash_artifical_nl=True, strip_artifical_nl=True)
return r
73
96
def extract_text_array(dom, squash_artifical_nl=True, strip_artifical_nl=True): if callable(dom.tag): return '' r = [] if dom.tag in SEPARATORS: r.append(True) # equivalent of '\n' used to designate separators elif dom.tag not in INLINE_TAGS: # equivalent of '\n' used to designate artificially inserted newlines r.append(None) if dom.text is not None: r.append(dom.text) for child in dom.getchildren(): r.extend(extract_text_array(child, squash_artifical_nl=False, strip_artifical_nl=False)) if child.tail is not None: r.append(child.tail) if dom.tag not in INLINE_TAGS and dom.tag not in SEPARATORS: # equivalent of '\n' used to designate artificially inserted newlines r.append(None) if squash_artifical_nl: r = _squash_artifical_nl(r) if strip_artifical_nl: r = _strip_artifical_nl(r) return r
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/text.py#L73-L96
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ]
95.833333
[]
0
false
98.591549
24
11
100
0
def extract_text_array(dom, squash_artifical_nl=True, strip_artifical_nl=True): if callable(dom.tag): return '' r = [] if dom.tag in SEPARATORS: r.append(True) # equivalent of '\n' used to designate separators elif dom.tag not in INLINE_TAGS: # equivalent of '\n' used to designate artificially inserted newlines r.append(None) if dom.text is not None: r.append(dom.text) for child in dom.getchildren(): r.extend(extract_text_array(child, squash_artifical_nl=False, strip_artifical_nl=False)) if child.tail is not None: r.append(child.tail) if dom.tag not in INLINE_TAGS and dom.tag not in SEPARATORS: # equivalent of '\n' used to designate artificially inserted newlines r.append(None) if squash_artifical_nl: r = _squash_artifical_nl(r) if strip_artifical_nl: r = _strip_artifical_nl(r) return r
21,653
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/text.py
extract_text
(dom, block_symbol='\n', sep_symbol='\n', squash_space=True)
return result
99
111
def extract_text(dom, block_symbol='\n', sep_symbol='\n', squash_space=True): a = extract_text_array(dom, squash_artifical_nl=squash_space) if squash_space: a = _strip_artifical_nl(_squash_artifical_nl(_merge_original_parts(a))) result = ''.join( block_symbol if x is None else ( sep_symbol if x is True else x ) for x in a ) if squash_space: result = result.strip() return result
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/text.py#L99-L111
32
[ 0, 1, 2, 3, 4, 10, 11, 12 ]
61.538462
[]
0
false
98.591549
13
3
100
0
def extract_text(dom, block_symbol='\n', sep_symbol='\n', squash_space=True): a = extract_text_array(dom, squash_artifical_nl=squash_space) if squash_space: a = _strip_artifical_nl(_squash_artifical_nl(_merge_original_parts(a))) result = ''.join( block_symbol if x is None else ( sep_symbol if x is True else x ) for x in a ) if squash_space: result = result.strip() return result
21,654
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/cssselectpatch.py
XPathExpr.__init__
(self, path='', element='*', condition='', star_prefix=False)
13
17
def __init__(self, path='', element='*', condition='', star_prefix=False): self.path = path self.element = element self.condition = condition self.post_condition = None
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/cssselectpatch.py#L13-L17
32
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
80.645161
5
1
100
0
def __init__(self, path='', element='*', condition='', star_prefix=False): self.path = path self.element = element self.condition = condition self.post_condition = None
21,655
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/cssselectpatch.py
XPathExpr.add_post_condition
(self, post_condition)
19
24
def add_post_condition(self, post_condition): if self.post_condition: self.post_condition = '%s and (%s)' % (self.post_condition, post_condition) else: self.post_condition = post_condition
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/cssselectpatch.py#L19-L24
32
[ 0, 1, 5 ]
50
[ 2 ]
16.666667
false
80.645161
6
2
83.333333
0
def add_post_condition(self, post_condition): if self.post_condition: self.post_condition = '%s and (%s)' % (self.post_condition, post_condition) else: self.post_condition = post_condition
21,656
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/cssselectpatch.py
XPathExpr.__str__
(self)
return path
26
30
def __str__(self): path = XPathExprOrig.__str__(self) if self.post_condition: path = '%s[%s]' % (path, self.post_condition) return path
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/cssselectpatch.py#L26-L30
32
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
80.645161
5
2
100
0
def __str__(self): path = XPathExprOrig.__str__(self) if self.post_condition: path = '%s[%s]' % (path, self.post_condition) return path
21,657
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/cssselectpatch.py
XPathExpr.join
(self, combiner, other, closing_combiner=None, has_inner_condition=False)
return res
32
38
def join(self, combiner, other, closing_combiner=None, has_inner_condition=False): res = XPathExprOrig.join(self, combiner, other, closing_combiner=closing_combiner, has_inner_condition=has_inner_condition) self.post_condition = other.post_condition return res
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/cssselectpatch.py#L32-L38
32
[ 0, 2, 5, 6 ]
57.142857
[]
0
false
80.645161
7
1
100
0
def join(self, combiner, other, closing_combiner=None, has_inner_condition=False): res = XPathExprOrig.join(self, combiner, other, closing_combiner=closing_combiner, has_inner_condition=has_inner_condition) self.post_condition = other.post_condition return res
21,658
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/cssselectpatch.py
JQueryTranslator.xpath_first_pseudo
(self, xpath)
return xpath
Matches the first selected element:: >>> from pyquery import PyQuery >>> d = PyQuery('<div><p class="first"></p><p></p></div>') >>> d('p:first') [<p.first>] ..
Matches the first selected element::
52
63
def xpath_first_pseudo(self, xpath): """Matches the first selected element:: >>> from pyquery import PyQuery >>> d = PyQuery('<div><p class="first"></p><p></p></div>') >>> d('p:first') [<p.first>] .. """ xpath.add_post_condition('position() = 1') return xpath
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/cssselectpatch.py#L52-L63
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
80.645161
12
1
100
8
def xpath_first_pseudo(self, xpath): xpath.add_post_condition('position() = 1') return xpath
21,659
gawel/pyquery
ca860115ee15ad30367b6386ed6abc8f8801600e
pyquery/cssselectpatch.py
JQueryTranslator.xpath_last_pseudo
(self, xpath)
return xpath
Matches the last selected element:: >>> from pyquery import PyQuery >>> d = PyQuery('<div><p></p><p class="last"></p></div>') >>> d('p:last') [<p.last>] ..
Matches the last selected element::
65
76
def xpath_last_pseudo(self, xpath): """Matches the last selected element:: >>> from pyquery import PyQuery >>> d = PyQuery('<div><p></p><p class="last"></p></div>') >>> d('p:last') [<p.last>] .. """ xpath.add_post_condition('position() = last()') return xpath
https://github.com/gawel/pyquery/blob/ca860115ee15ad30367b6386ed6abc8f8801600e/project32/pyquery/cssselectpatch.py#L65-L76
32
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
80.645161
12
1
100
8
def xpath_last_pseudo(self, xpath): xpath.add_post_condition('position() = last()') return xpath
21,660