INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns an list of tuples of the form ( word POS tag ). Example::: [ ( At ADP ) ( eight NUM ) ( o clock NOUN ) ( on ADP ) ( Thursday NOUN ) ( morning NOUN ) ]: rtype: list of tuples | def pos_tags(self):
"""Returns an list of tuples of the form (word, POS tag).
Example:
::
[('At', 'ADP'), ('eight', 'NUM'), ("o'clock", 'NOUN'), ('on', 'ADP'),
('Thursday', 'NOUN'), ('morning', 'NOUN')]
:rtype: list of tuples
"""
tagged_words = []
for word,t in self.pos_tagge... |
Returns an list of tuples of the form ( word POS tag ) using transfer POS tagger | def transfer_pos_tags(self):
"""Returns an list of tuples of the form (word, POS tag), using transfer POS tagger"""
tagged_words = []
for word,t in self.transfer_pos_tagger.annotate(self.words):
word.pos_tag = t
tagged_words.append((word, t))
return tagged_words |
Dictionary of word frequencies in this text. | def word_counts(self):
"""Dictionary of word frequencies in this text.
"""
counts = defaultdict(int)
for word in self.words:
counts[word] += 1
return counts |
Dictionary of noun phrase frequencies in this text. | def np_counts(self):
"""Dictionary of noun phrase frequencies in this text.
"""
counts = defaultdict(int)
for phrase in self.noun_phrases:
counts[phrase] += 1
return counts |
Return a list of n - grams ( tuples of n successive words ) for this blob.: rtype: List of: class: WordLists <WordList > | def ngrams(self, n=3):
"""Return a list of n-grams (tuples of n successive words) for this
blob.
:rtype: List of :class:`WordLists <WordList>`
"""
if n <= 0:
return []
grams = [WordList(self.words[i:i+n], parent=self)
for i in range(len(self.words) - n + 1)]
r... |
Attempt to correct the spelling of a blob... versionadded:: 0. 6. 0: rtype:: class: BaseBlob <BaseBlob > | def correct(self):
"""Attempt to correct the spelling of a blob.
.. versionadded:: 0.6.0
:rtype: :class:`BaseBlob <BaseBlob>`
"""
# regex matches: contraction or word or punctuation or whitespace
tokens = nltk.tokenize.regexp_tokenize(self.raw, "\w*('\w*)+|\w+|[^\w\s]|\s")
corrected = (Word(... |
Behaves like the built - in str. split () except returns a WordList.: rtype:: class: WordList <WordList > | def split(self, sep=None, maxsplit=sys.maxsize):
"""Behaves like the built-in str.split() except returns a
WordList.
:rtype: :class:`WordList <WordList>`
"""
return WordList(self._strkey().split(sep, maxsplit), parent=self) |
Transliterate the string to the target language. | def transliterate(self, target_language="en"):
"""Transliterate the string to the target language."""
t = Transliterator(source_lang=self.language,
target_lang=target_language)
return t.transliterate(self.string) |
Get the count of a word or phrase s within this WordList.: param strg: The string to count.: param case_sensitive: A boolean whether or not the search is case - sensitive. | def count(self, strg, case_sensitive=False, *args, **kwargs):
"""Get the count of a word or phrase `s` within this WordList.
:param strg: The string to count.
:param case_sensitive: A boolean, whether or not the search is case-sensitive.
"""
if not case_sensitive:
return [word.lower() for wo... |
Append an object to end. If the object is a string appends a: class: Word <Word > object. | def append(self, obj):
"""Append an object to end. If the object is a string, appends a
:class:`Word <Word>` object.
"""
if isinstance(obj, basestring):
return self._collection.append(Word(obj))
else:
return self._collection.append(obj) |
Extend WordList by appending elements from iterable. If an element is a string appends a: class: Word <Word > object. | def extend(self, iterable):
"""Extend WordList by appending elements from ``iterable``. If an element
is a string, appends a :class:`Word <Word>` object.
"""
[self._collection.append(Word(e) if isinstance(e, basestring) else e)
for e in iterable]
return self |
Calculates the sentiment of an entity as it appears in text. | def _sentiment(self, distance=True):
"""Calculates the sentiment of an entity as it appears in text."""
sum_pos = 0
sum_neg = 0
text = self.parent
entity_positions = range(self.start, self.end)
non_entity_positions = set(range(len(text.words))).difference(entity_positions)
if not distance:
... |
The dict representation of this sentence. | def dict(self):
'''The dict representation of this sentence.'''
return {
'raw': self.raw,
'start': self.start,
'end': self.end,
'entities': [(e.tag, e) for e in self.entities],
'tokens': self.tokens,
'words': self.words,
'pos_tags': self.pos_tags,
... |
Return a json representation ( str ) of this blob. Takes the same arguments as json. dumps... versionadded:: 0. 5. 1 | def to_json(self, *args, **kwargs):
'''Return a json representation (str) of this blob.
Takes the same arguments as json.dumps.
.. versionadded:: 0.5.1
'''
try:
import ujson as json
except ImportError:
import json
return json.dumps(self.serialized, *args, **kwargs) |
Returns a list of Sentence objects from the raw text. | def _create_sentence_objects(self):
'''Returns a list of Sentence objects from the raw text.
'''
sentence_objects = []
sent_tokenizer = SentenceTokenizer(locale=self.language.code)
seq = Sequence(self.raw)
seq = sent_tokenizer.transform(seq)
for start_index, end_index in zip(seq.idx[:-1], se... |
Decide which language is used to write the text. | def detect(self, text):
"""Decide which language is used to write the text.
The method tries first to detect the language with high reliability. If
that is not possible, the method switches to best effort strategy.
Args:
text (string): A snippet of text, the longer it is the more reliable we
... |
Return filename that contains specific language resource name. | def locate_resource(name, lang, filter=None):
"""Return filename that contains specific language resource name.
Args:
name (string): Name of the resource.
lang (string): language code to be loaded.
"""
task_dir = resource_dir.get(name, name)
package_id = u"{}.{}".format(task_dir, lang)
p = path.joi... |
Return a word embeddings object for lang and of type type | def load_embeddings(lang="en", task="embeddings", type="cw", normalize=False):
"""Return a word embeddings object for `lang` and of type `type`
Args:
lang (string): language code.
task (string): parameters that define task.
type (string): skipgram, cw, cbow ...
noramlized (boolean): returns noramli... |
Return a CountedVocabulary object. | def load_vocabulary(lang="en", type="wiki"):
"""Return a CountedVocabulary object.
Args:
lang (string): language code.
type (string): wiki,...
"""
src_dir = "{}_vocab".format(type)
p = locate_resource(src_dir, lang)
return CountedVocabulary.from_vocabfile(p) |
Return a named entity extractor parameters for lang and of version version | def load_ner_model(lang="en", version="2"):
"""Return a named entity extractor parameters for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used.
"""
src_dir = "ner{}".format(version)
p = locate_resource(src_dir, lang)
fh = _op... |
Return a part of speech tagger parameters for lang and of version version | def load_pos_model(lang="en", version="2"):
"""Return a part of speech tagger parameters for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used.
"""
src_dir = "pos{}".format(version)
p = locate_resource(src_dir, lang)
fh = _ope... |
Return a morfessor model for lang and of version version | def load_morfessor_model(lang="en", version="2"):
"""Return a morfessor model for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used.
"""
src_dir = "morph{}".format(version)
p = locate_resource(src_dir, lang)
file_handler = _op... |
Return a morfessor model for lang and of version version | def load_transliteration_table(lang="en", version="2"):
"""Return a morfessor model for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used.
"""
src_dir = "transliteration{}".format(version)
p = locate_resource(src_dir, lang)
fi... |
Calculate the vocabulary. | def vocab_counter(args):
"""Calculate the vocabulary."""
if isinstance(args.input, TextFiles):
v = CountedVocabulary.from_textfiles(args.input, workers=args.workers)
else:
v = CountedVocabulary.from_textfile(args.input, workers=args.workers)
if args.min_count > 1:
v = v.min_count(args.min_count)
... |
Detect the language of each line. | def detect(args):
""" Detect the language of each line."""
for l in args.input:
if l.strip():
_print("{:<20}{}".format(Detector(l).language.name, l.strip())) |
Chunk named entities. | def tag(tagger, args):
"""Chunk named entities."""
for l in args.input:
words = l.strip().split()
line_annotations = [u"{:<16}{:<5}".format(w,p) for w, p in tagger.annotate(words)]
_print(u"\n".join(line_annotations))
_print(u"") |
Transliterate words according to the target language. | def transliterate(args):
"""Transliterate words according to the target language."""
t = Transliterator(source_lang=args.lang,
target_lang=args.target)
for l in args.input:
words = l.strip().split()
line_annotations = [u"{:<16}{:<16}".format(w, t.transliterate(w)) for w in words]
... |
Segment words according to their morphemes. | def morphemes(args):
"""Segment words according to their morphemes."""
morfessor = load_morfessor_model(lang=args.lang)
for l in args.input:
words = l.strip().split()
morphemes = [(w, u"_".join(morfessor.viterbi_segment(w)[0])) for w in words]
line_annotations = [u"{:<16}{:<5}".format(w,p) for w, p in... |
Chunk named entities. | def ner_chunk(args):
"""Chunk named entities."""
chunker = NEChunker(lang=args.lang)
tag(chunker, args) |
Tag words with their part of speech. | def pos_tag(args):
"""Tag words with their part of speech."""
tagger = POSTagger(lang=args.lang)
tag(tagger, args) |
Download polyglot packages and models. | def download(args):
""" Download polyglot packages and models."""
downloader = Downloader(server_index_url = args.server_index_url)
if args.packages:
for pkg_id in args.packages:
rv = downloader.download(info_or_id=unicode(pkg_id), download_dir=args.dir,
quiet=args.quiet,... |
Open file object given filenames open files or even archives. | def _open(file_, mode='r'):
"""Open file object given filenames, open files or even archives."""
if isinstance(file_, string_types):
_, ext = path.splitext(file_)
if ext in {'.bz2', '.gz'}:
s = tarfile.open(file_)
return s.extractfile(s.next())
else:
return open(file_, mode)
return f... |
Unpickle methods properly including class methods. | def _unpickle_method(func_name, obj, cls):
"""Unpickle methods properly, including class methods."""
if obj is None:
return cls.__dict__[func_name].__get__(obj, cls)
for cls in cls.__mro__:
try:
func = cls.__dict__[func_name]
except KeyError:
pass
else:
break
return func.__get... |
Determine a link to online source for a class/ method/ function | def _linkcode_resolve(domain, info, package, url_fmt, revision):
"""Determine a link to online source for a class/method/function
This is called by sphinx.ext.linkcode
An example with a long-untouched module that everyone has
>>> _linkcode_resolve('py', {'module': 'tty',
... ... |
Returns a linkcode_resolve function for the given URL format | def make_linkcode_resolve(package, url_fmt):
"""Returns a linkcode_resolve function for the given URL format
revision is a git commit reference (hash or name)
package is the name of the root module of the package
url_fmt is along the lines of ('https://github.com/USER/PROJECT/'
... |
Counts the word frequences in a list of sentences. | def count(lines):
""" Counts the word frequences in a list of sentences.
Note:
This is a helper function for parallel execution of `Vocabulary.from_text`
method.
"""
words = [w for l in lines for w in l.strip().split()]
return Counter(words) |
Guarantees that all textual symbols are unicode. | def sanitize_words(self, words):
"""Guarantees that all textual symbols are unicode.
Note:
We do not convert numbers, only strings to unicode.
We assume that the strings are encoded in utf-8.
"""
_words = []
for w in words:
if isinstance(w, string_types) and not isinstance(w, unic... |
Construct a CountedVocabulary out of a vocabulary file. | def from_vocabfile(cls, filename):
""" Construct a CountedVocabulary out of a vocabulary file.
Note:
File has the following format word1
word2
"""
words = [x.strip() for x in _open(filename, 'r').read().splitlines()]
return cls(words=words) |
Count the set of words appeared in a text file. | def from_textfile(cls, textfile, workers=1, job_size=1000):
""" Count the set of words appeared in a text file.
Args:
textfile (string): The name of the text file or `TextFile` object.
min_count (integer): Minimum number of times a word/token appeared in the document
to be consider... |
Returns a vocabulary with the most frequent k words. | def most_frequent(self, k):
""" Returns a vocabulary with the most frequent `k` words.
Args:
k (integer): specifies the top k most frequent words to be returned.
"""
word_count = {w:self.word_count[w] for w in self.words[:k]}
return CountedVocabulary(word_count=word_count) |
Returns a vocabulary after eliminating the words that appear < n. | def min_count(self, n=1):
""" Returns a vocabulary after eliminating the words that appear < `n`.
Args:
n (integer): specifies the minimum word frequency allowed.
"""
word_count = {w:c for w,c in iteritems(self.word_count) if c >= n}
return CountedVocabulary(word_count=word_count) |
Construct a CountedVocabulary out of a vocabulary file. | def from_vocabfile(filename):
""" Construct a CountedVocabulary out of a vocabulary file.
Note:
File has the following format word1 count1
word2 count2
"""
word_count = [x.strip().split() for x in _open(filename, 'r').read().splitlines()]
word_count = {w:in... |
Split into subsequences according to sequence. | def split(self, sequence):
""" Split into subsequences according to `sequence`."""
major_idx = sequence.idx
idx2 = 0
for start, end in zip(major_idx[:-1], major_idx[1:]):
idx1 = self.idx.index(start, idx2)
idx2 = self.idx.index(end, idx2)
seq = Sequence(self.text[start:end])
seq... |
Generalization of the default iter file delimited by \ n. Note: The newline string can be arbitrarily long ; it need not be restricted to a single character. You can also set the read size and control whether or not the newline string is left on the end of the iterated lines. Setting newline to \ 0 is particularly good... | def iter_delimiter(self, byte_size=8192):
""" Generalization of the default iter file delimited by '\n'.
Note:
The newline string can be arbitrarily long; it need not be restricted to a
single character. You can also set the read size and control whether or not
the newline string is left on th... |
Read size of bytes. | def read(self, size=None):
""" Read `size` of bytes."""
if size is None:
return self.buf.read() + self.open_file.read()
contents = self.buf.read(size)
if len(contents) < size:
contents += self.open_file.read(size - len(contents))
return contents |
Apply func to lines of text in parallel or sequential. | def apply(self, func, workers=1, job_size=10000):
"""Apply `func` to lines of text in parallel or sequential.
Args:
func : a function that takes a list of lines.
"""
if workers == 1:
for lines in self.iter_chunks(job_size):
yield func(lines)
else:
with ProcessPoolExecutor(... |
Annotate a squence of words with entity tags. | def annotate(self, sent):
"""Annotate a squence of words with entity tags.
Args:
sent: sequence of strings/words.
"""
preds = []
words = []
for word, fv in self.sent2examples(sent):
probs = self.predictor(fv)
tags = probs.argsort()
tag = self.ID_TAG[tags[-1]]
word... |
Convert ngrams into feature vectors. | def sent2examples(self, sent):
""" Convert ngrams into feature vectors."""
# TODO(rmyeid): use expanders.
words = [w if w in self.embeddings else TaggerBase.UNK for w in sent]
ngrams = TaggerBase.ngrams(words, self.context, self.transfer)
fvs = []
for word, ngram in zip(sent, ngrams):
fv ... |
Building the predictor out of the model. | def _load_network(self):
""" Building the predictor out of the model."""
self.embeddings = load_embeddings(self.lang, type='cw', normalize=True)
self.model = load_ner_model(lang=self.lang, version=2)
first_layer, second_layer = self.model
def predict_proba(input_):
hidden = np.tanh(np.dot(fir... |
Building the predictor out of the model. | def _load_network(self):
""" Building the predictor out of the model."""
self.embeddings = load_embeddings(self.lang, type='cw')
self.model = load_pos_model(lang=self.lang, version=2)
def predict_proba(input_):
hidden = np.tanh(np.dot(input_, self.model["W1"]) + self.model["b1"])
output = ... |
Construct geocoding request url. Overridden. | def _construct_url(self, base_api, params):
"""
Construct geocoding request url. Overridden.
:param str base_api: Geocoding function base address - self.api
or self.reverse_api.
:param dict params: Geocoding params.
:return: string URL.
"""
params['... |
Return a location point by address. | def geocode(
self,
query,
limit=None,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
):
"""
Return a location point by address.
:param str query: The address or query you wish to geocode.
:param int limit: Defines the maximum... |
Wrap self. _call_geocoder handling tokens. | def _authenticated_call_geocoder(self, url, timeout=DEFAULT_SENTINEL):
"""
Wrap self._call_geocoder, handling tokens.
"""
if self.token is None or int(time()) > self.token_expiry:
self._refresh_authentication_token()
request = Request(
"&".join((url, urlen... |
Return a location point by address. | def geocode(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL,
out_fields=None):
"""
Return a location point by address.
:param str query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
ava... |
Return an address by location point. | def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL,
distance=None, wkid=DEFAULT_WKID):
"""
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :cla... |
POST to ArcGIS requesting a new token. | def _refresh_authentication_token(self):
"""
POST to ArcGIS requesting a new token.
"""
if self.retry == self._MAX_RETRIES:
raise GeocoderAuthenticationFailure(
'Too many retries for auth: %s' % self.retry
)
token_request_arguments = {
... |
Pair an iterable e. g. ( 1 2 3 4 ) - > (( 1 2 ) ( 2 3 ) ( 3 4 )) | def pairwise(seq):
"""
Pair an iterable, e.g., (1, 2, 3, 4) -> ((1, 2), (2, 3), (3, 4))
"""
for i in range(0, len(seq) - 1):
yield (seq[i], seq[i + 1]) |
Join with a filter. | def join_filter(sep, seq, pred=bool):
"""
Join with a filter.
"""
return sep.join([text_type(i) for i in seq if pred(i)]) |
Return unicode string of geocoder results. | def decode_page(page):
"""
Return unicode string of geocoder results.
Nearly all services use JSON, so assume UTF8 encoding unless the
response specifies otherwise.
"""
if hasattr(page, 'read'): # urllib
if py3k:
encoding = page.headers.get_param("charset") or "utf-8"
... |
TODO docs. | def destination(self, point, bearing, distance=None):
"""
TODO docs.
"""
point = Point(point)
lat1 = units.radians(degrees=point.latitude)
lng1 = units.radians(degrees=point.longitude)
bearing = units.radians(degrees=bearing)
if distance is None:
... |
TODO docs. | def destination(self, point, bearing, distance=None):
"""
TODO docs.
"""
point = Point(point)
lat1 = point.latitude
lon1 = point.longitude
azi1 = bearing
if distance is None:
distance = self
if isinstance(distance, Distance):
... |
Change the ellipsoid used in the calculation. | def set_ellipsoid(self, ellipsoid):
"""
Change the ellipsoid used in the calculation.
"""
if not isinstance(ellipsoid, (list, tuple)):
try:
self.ELLIPSOID = ELLIPSOIDS[ellipsoid]
self.ellipsoid_key = ellipsoid
except KeyError:
... |
TODO docs. | def destination(self, point, bearing, distance=None):
"""
TODO docs.
"""
point = Point(point)
lat1 = units.radians(degrees=point.latitude)
lng1 = units.radians(degrees=point.longitude)
bearing = units.radians(degrees=bearing)
if distance is None:
... |
Normalize angle x to be within [ - limit ; limit ) range. | def _normalize_angle(x, limit):
"""
Normalize angle `x` to be within `[-limit; limit)` range.
"""
double_limit = limit * 2.0
modulo = fmod(x, double_limit) or 0.0 # `or 0` is to turn -0 to +0.
if modulo < -limit:
return modulo + double_limit
if modulo >= limit:
return modulo... |
Format decimal degrees ( DD ) to degrees minutes seconds ( DMS ) | def format(self, altitude=None, deg_char='', min_char='m', sec_char='s'):
"""
Format decimal degrees (DD) to degrees minutes seconds (DMS)
"""
latitude = "%s %s" % (
format_degrees(abs(self.latitude), symbols={
'deg': deg_char, 'arcmin': min_char, 'arcsec': se... |
Format decimal degrees with altitude | def format_decimal(self, altitude=None):
"""
Format decimal degrees with altitude
"""
coordinates = [str(self.latitude), str(self.longitude)]
if altitude is None:
altitude = bool(self.altitude)
if altitude:
if not isinstance(altitude, string_compa... |
Parse degrees minutes seconds including direction ( N S E W ) | def parse_degrees(cls, degrees, arcminutes, arcseconds, direction=None):
"""
Parse degrees minutes seconds including direction (N, S, E, W)
"""
degrees = float(degrees)
negative = degrees < 0
arcminutes = float(arcminutes)
arcseconds = float(arcseconds)
i... |
Parse altitude managing units conversion | def parse_altitude(cls, distance, unit):
"""
Parse altitude managing units conversion
"""
if distance is not None:
distance = float(distance)
CONVERTERS = {
'km': lambda d: d,
'm': lambda d: units.kilometers(meters=d),
... |
Create and return a Point instance from a string containing latitude and longitude and optionally altitude. | def from_string(cls, string):
"""
Create and return a ``Point`` instance from a string containing
latitude and longitude, and optionally, altitude.
Latitude and longitude must be in degrees and may be in decimal form
or indicate arcminutes and arcseconds (labeled with Unicode pr... |
Create and return a new Point instance from any iterable with 0 to 3 elements. The elements if present must be latitude longitude and altitude respectively. | def from_sequence(cls, seq):
"""
Create and return a new ``Point`` instance from any iterable with 0 to
3 elements. The elements, if present, must be latitude, longitude,
and altitude, respectively.
"""
args = tuple(islice(seq, 4))
if len(args) > 3:
r... |
Create and return a new Point instance from another Point instance. | def from_point(cls, point):
"""
Create and return a new ``Point`` instance from another ``Point``
instance.
"""
return cls(point.latitude, point.longitude, point.altitude) |
Return a location point by address. | def geocode(
self,
query,
max_results=25,
set_back=0,
location_descriptor='any',
exactly_one=True,
timeout=DEFAULT_SENTINEL,
):
"""
Return a location point by address.
:param str query: The address or query ... |
Return an address by location point. | def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL):
"""
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitu... |
Raise any exceptions if there were problems reported in the api response. | def _check_for_api_errors(geocoding_results):
"""
Raise any exceptions if there were problems reported
in the api response.
"""
status_result = geocoding_results.get("STATUS", {})
if "NO_RESULTS" in status_result.get("status", ""):
return
api_call_succ... |
Return a location point by address. | def geocode(
self,
query,
exactly_one=True,
user_location=None,
timeout=DEFAULT_SENTINEL,
culture=None,
include_neighborhood=None,
include_country_code=False
):
"""
Return a location point by address.
... |
Return an address by location point. | def reverse(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
culture=None,
include_country_code=False
):
"""
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
... |
TODO docs. | def degrees(radians=0, arcminutes=0, arcseconds=0):
"""
TODO docs.
"""
deg = 0.
if radians:
deg = math.degrees(radians)
if arcminutes:
deg += arcminutes / arcmin(degrees=1.)
if arcseconds:
deg += arcseconds / arcsec(degrees=1.)
return deg |
TODO docs. | def radians(degrees=0, arcminutes=0, arcseconds=0):
"""
TODO docs.
"""
if arcminutes:
degrees += arcminutes / arcmin(degrees=1.)
if arcseconds:
degrees += arcseconds / arcsec(degrees=1.)
return math.radians(degrees) |
TODO docs. | def kilometers(meters=0, miles=0, feet=0, nautical=0):
"""
TODO docs.
"""
ret = 0.
if meters:
ret += meters / 1000.
if feet:
ret += feet / ft(1.)
if nautical:
ret += nautical / nm(1.)
ret += miles * 1.609344
return ret |
TODO docs. | def meters(kilometers=0, miles=0, feet=0, nautical=0):
"""
TODO docs.
"""
return (kilometers + km(nautical=nautical, miles=miles, feet=feet)) * 1000 |
TODO docs. | def miles(kilometers=0, meters=0, feet=0, nautical=0):
"""
TODO docs.
"""
ret = 0.
if nautical:
kilometers += nautical / nm(1.)
if feet:
kilometers += feet / ft(1.)
if meters:
kilometers += meters / 1000.
ret += kilometers / 1.609344
return ret |
TODO docs. | def feet(kilometers=0, meters=0, miles=0, nautical=0):
"""
TODO docs.
"""
ret = 0.
if nautical:
kilometers += nautical / nm(1.)
if meters:
kilometers += meters / 1000.
if kilometers:
miles += mi(kilometers=kilometers)
ret += miles * 5280
return ret |
TODO docs. | def nautical(kilometers=0, meters=0, miles=0, feet=0):
"""
TODO docs.
"""
ret = 0.
if feet:
kilometers += feet / ft(1.)
if miles:
kilometers += km(miles=miles)
if meters:
kilometers += meters / 1000.
ret += kilometers / 1.852
return ret |
Return a location point by address. | def geocode(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
candidates=None, # TODO: change default value to `1` in geopy 2.0
):
"""
Return a location point by address.
:param str query: The address or query you wish to ... |
Parse responses as JSON objects. | def _parse_json(self, response, exactly_one=True):
"""
Parse responses as JSON objects.
"""
if not len(response):
return None
if exactly_one:
return self._format_structured_address(response[0])
else:
return [self._format_structured_addr... |
Pretty - print address and return lat lon tuple. | def _format_structured_address(address):
"""
Pretty-print address and return lat, lon tuple.
"""
latitude = address['metadata'].get('latitude')
longitude = address['metadata'].get('longitude')
return Location(
", ".join((address['delivery_line_1'], address['la... |
Construct geocoding request url. Overridden. | def _construct_url(self, base_api, params):
"""
Construct geocoding request url. Overridden.
:param str base_api: Geocoding function base address - self.api
or self.reverse_api.
:param dict params: Geocoding params.
:return: string URL.
"""
params['... |
Returns a Premier account signed url. Docs on signature: https:// developers. google. com/ maps/ documentation/ business/ webservices/ auth#digital_signatures | def _get_signed_url(self, params):
"""
Returns a Premier account signed url. Docs on signature:
https://developers.google.com/maps/documentation/business/webservices/auth#digital_signatures
"""
params['client'] = self.client_id
if self.channel:
params['ch... |
Return a location point by address. | def geocode(
self,
query=None,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
bounds=None,
region=None,
components=None,
place_id=None,
language=None,
sensor=False,
):
"""
Return a lo... |
Find the timezone a location was in for a specified at_time and return a pytz timezone object. | def timezone(self, location, at_time=None, timeout=DEFAULT_SENTINEL):
"""
Find the timezone a `location` was in for a specified `at_time`,
and return a pytz timezone object.
.. versionadded:: 1.2.0
.. deprecated:: 1.18.0
Use :meth:`GoogleV3.reverse_timezone` instead.... |
Find the timezone a point in query was in for a specified at_time. | def reverse_timezone(self, query, at_time=None, timeout=DEFAULT_SENTINEL):
"""
Find the timezone a point in `query` was in for a specified `at_time`.
.. versionadded:: 1.18.0
.. versionchanged:: 1.18.1
Previously a :class:`KeyError` was raised for a point without
... |
Returns location ( latitude longitude ) from json feed. | def _parse_json(self, page, exactly_one=True):
'''Returns location, (latitude, longitude) from json feed.'''
places = page.get('results', [])
if not len(places):
self._check_status(page.get('status'))
return None
def parse_place(place):
'''Get the lo... |
Validates error statuses. | def _check_status(status):
"""
Validates error statuses.
"""
if status == 'ZERO_RESULTS':
# When there are no results, just return.
return
if status == 'OVER_QUERY_LIMIT':
raise GeocoderQuotaExceeded(
'The given key has gone ove... |
Return a location point by address. | def geocode(
self,
query,
bbox=None,
mapview=None,
exactly_one=True,
maxresults=None,
pageinformation=None,
language=None,
additional_data=False,
timeout=DEFAULT_SENTINEL
):
"""
Re... |
Return an address by location point. | def reverse(
self,
query,
radius=None,
exactly_one=True,
maxresults=None,
pageinformation=None,
language=None,
mode='retrieveAddresses',
timeout=DEFAULT_SENTINEL
):
"""
Return an address by lo... |
Parse a location name latitude and longitude from an JSON response. | def _parse_json(doc, exactly_one=True):
"""
Parse a location name, latitude, and longitude from an JSON response.
"""
status_code = doc.get("statusCode", 200)
if status_code != 200:
err = doc.get("errorDetails", "")
if status_code == 401:
r... |
Do the right thing on point input. For geocoders with reverse methods. | def _coerce_point_to_string(point, output_format="%(lat)s,%(lon)s"):
"""
Do the right thing on "point" input. For geocoders with reverse
methods.
"""
try:
if not isinstance(point, Point):
point = Point(point)
except ValueError as e:
... |
Transform bounding box boundaries to a string matching output_format from the following formats: | def _format_bounding_box(bbox, output_format="%(lat1)s,%(lon1)s,%(lat2)s,%(lon2)s"):
"""
Transform bounding box boundaries to a string matching
`output_format` from the following formats:
- [Point(lat1, lon1), Point(lat2, lon2)]
- [[lat1, lon1], [lat2, lon2]]
... |
For a generated query URL get the results. | def _call_geocoder(
self,
url,
timeout=DEFAULT_SENTINEL,
raw=False,
requester=None,
deserializer=json.loads,
**kwargs
):
"""
For a generated query URL, get the results.
"""
if requester:
... |
Return a location point by address. | def geocode(
self,
query,
bounds=None,
country=None,
language=None,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
):
"""
Return a location point by address.
:param str query: The address or query you wish to g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.