code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Use globals to load CJK tokenizers on demand, so that we can still run # in environments that lack the CJK dependencies global _mecab_tokenize, _jieba_tokenize language = langcodes.get(lang) info = get_language_info(language) text = preprocess_text(text, language) if info['tokenizer...
def tokenize(text, lang, include_punctuation=False, external_wordlist=False)
Tokenize this text in a way that's relatively simple but appropriate for the language. Strings that are looked up in wordfreq will be run through this function first, so that they can be expected to match the data. The text will be run through a number of pre-processing steps that vary by language; see...
3.72763
3.515698
1.060282
global _simplify_chinese info = get_language_info(lang) tokens = tokenize(text, lang, include_punctuation, external_wordlist) if info['lookup_transliteration'] == 'zh-Hans': from wordfreq.chinese import simplify_chinese as _simplify_chinese tokens = [_simplify_chinese(token) for t...
def lossy_tokenize(text, lang, include_punctuation=False, external_wordlist=False)
Get a list of tokens for this text, with largely the same results and options as `tokenize`, but aggressively normalize some text in a lossy way that's good for counting word frequencies. In particular: - Any sequence of 2 or more adjacent digits, possibly with intervening punctuation such as a ...
6.000307
5.39549
1.112097
with gzip.open(filename, 'rb') as infile: data = msgpack.load(infile, raw=False) header = data[0] if ( not isinstance(header, dict) or header.get('format') != 'cB' or header.get('version') != 1 ): raise ValueError("Unexpected header: %r" % header) return data[1:]
def read_cBpack(filename)
Read a file from an idiosyncratic format that we use for storing approximate word frequencies, called "cBpack". The cBpack format is as follows: - The file on disk is a gzipped file in msgpack format, which decodes to a list whose first element is a header, and whose remaining elements are lis...
3.163114
3.264735
0.968873
if wordlist == 'best': available = available_languages('small') available.update(available_languages('large')) return available elif wordlist == 'combined': logger.warning( "The 'combined' wordlists have been renamed to 'small'." ) wordlist = 'sma...
def available_languages(wordlist='best')
Given a wordlist name, return a dictionary of language codes to filenames, representing all the languages in which that wordlist is available.
3.565268
3.510666
1.015553
available = available_languages(wordlist) best, score = langcodes.best_match(lang, list(available), min_score=match_cutoff) if score == 0: raise LookupError("No wordlist %r available for language %r" % (wordlist, lang)) if be...
def get_frequency_list(lang, wordlist='best', match_cutoff=30)
Read the raw data from a wordlist file, returning it as a list of lists. (See `read_cBpack` for what this represents.) Because we use the `langcodes` module, we can handle slight variations in language codes. For example, looking for 'pt-BR', 'pt_br', or even 'PT_BR' will get you the 'pt' (Portuguese) ...
6.917068
5.336514
1.296177
freqs = {} pack = get_frequency_list(lang, wordlist, match_cutoff) for index, bucket in enumerate(pack): freq = cB_to_freq(-index) for word in bucket: freqs[word] = freq return freqs
def get_frequency_dict(lang, wordlist='best', match_cutoff=30)
Get a word frequency list as a dictionary, mapping tokens to frequencies as floating-point probabilities.
5.59791
5.57875
1.003435
args = (word, lang, wordlist, minimum) try: return _wf_cache[args] except KeyError: if len(_wf_cache) >= CACHE_SIZE: _wf_cache.clear() _wf_cache[args] = _word_frequency(*args) return _wf_cache[args]
def word_frequency(word, lang, wordlist='best', minimum=0.)
Get the frequency of `word` in the language with code `lang`, from the specified `wordlist`. These wordlists can be specified: - 'large': a wordlist built from at least 5 sources, containing word frequencies of 10^-8 and higher - 'small': a wordlist built from at least 3 sources, containing word...
2.214803
2.615117
0.846923
freq_min = zipf_to_freq(minimum) freq = word_frequency(word, lang, wordlist, freq_min) return round(freq_to_zipf(freq), 2)
def zipf_frequency(word, lang, wordlist='best', minimum=0.)
Get the frequency of `word`, in the language with code `lang`, on the Zipf scale. The Zipf scale is a logarithmic frequency scale proposed by Marc Brysbaert, who compiled the SUBTLEX data. The goal of the Zipf scale is to map reasonable word frequencies to understandable, small positive numbers. A...
3.977384
5.505508
0.722437
results = [] for word in iter_wordlist(lang, wordlist): if (not ascii_only) or max(word) <= '~': results.append(word) if len(results) >= n: break return results
def top_n_list(lang, n, wordlist='best', ascii_only=False)
Return a frequency list of length `n` in descending order of frequency. This list contains words from `wordlist`, of the given language. If `ascii_only`, then only ascii words are considered.
3.610487
3.694591
0.977236
n_choices = 2 ** bits_per_word choices = top_n_list(lang, n_choices, wordlist, ascii_only=ascii_only) if len(choices) < n_choices: raise ValueError( "There aren't enough words in the wordlist to provide %d bits of " "entropy per word." % bits_per_word ) retur...
def random_words(lang='en', wordlist='best', nwords=5, bits_per_word=12, ascii_only=False)
Returns a string of random, space separated words. These words are of the given language and from the given wordlist. There will be `nwords` words in the string. `bits_per_word` determines the amount of entropy provided by each word; when it's higher, this function will choose from a larger list of ...
3.293526
3.210435
1.025882
return random_words(lang, wordlist, nwords, bits_per_word, ascii_only=True)
def random_ascii_words(lang='en', wordlist='best', nwords=5, bits_per_word=12)
Returns a string of random, space separated, ASCII words. These words are of the given language and from the given wordlist. There will be `nwords` words in the string. `bits_per_word` determines the amount of entropy provided by each word; when it's higher, this function will choose from a larger lis...
2.792948
4.850792
0.575771
global jieba_tokenizer, jieba_orig_tokenizer if external_wordlist: if jieba_orig_tokenizer is None: jieba_orig_tokenizer = jieba.Tokenizer(dictionary=ORIG_DICT_FILENAME) return jieba_orig_tokenizer.lcut(text) else: if jieba_tokenizer is None: jieba_tokeni...
def jieba_tokenize(text, external_wordlist=False)
Tokenize the given text into tokens whose word frequencies can probably be looked up. This uses Jieba, a word-frequency-based tokenizer. If `external_wordlist` is False, we tell Jieba to default to using wordfreq's own Chinese wordlist, and not to infer unknown words using a hidden Markov model. This e...
3.78261
3.967599
0.953375
text = unicodedata.normalize('NFC', text).replace('İ', 'i').replace('I', 'ı') return text.casefold()
def casefold_with_i_dots(text)
Convert capital I's and capital dotted İ's to lowercase in the way that's appropriate for Turkish and related languages, then case-fold the rest of the letters.
3.642746
3.659752
0.995353
matched = best_match(language, targets, min_score=min_score) return matched[1] > 0
def _language_in_list(language, targets, min_score=80)
A helper function to determine whether this language matches one of the target languages, with a match score above a certain threshold. The languages can be given as strings (language tags) or as Language objects. `targets` can be any iterable of such languages.
6.189904
9.854833
0.628108
suggested_pkg = names[0] paths = [ os.path.expanduser('~/.local/lib/mecab/dic'), '/var/lib/mecab/dic', '/var/local/lib/mecab/dic', '/usr/lib/mecab/dic', '/usr/local/lib/mecab/dic', '/usr/lib/x86_64-linux-gnu/mecab/dic', ] full_paths = [os.path.join(pa...
def find_mecab_dictionary(names)
Find a MeCab dictionary with a given name. The dictionary has to be installed separately -- see wordfreq's README for instructions.
2.539567
2.499767
1.015922
if lang not in MECAB_DICTIONARY_NAMES: raise ValueError("Can't run MeCab on language %r" % lang) if lang not in MECAB_ANALYZERS: MECAB_ANALYZERS[lang] = make_mecab_analyzer(MECAB_DICTIONARY_NAMES[lang]) analyzer = MECAB_ANALYZERS[lang] text = unicodedata.normalize('NFKC', text.stri...
def mecab_tokenize(text, lang)
Use the mecab-python3 package to tokenize the given text. The `lang` must be 'ja' for Japanese or 'ko' for Korean. The simplest output from mecab-python3 is the single-string form, which contains the same table that the command-line version of MeCab would output. We find the tokens in the first column ...
2.761717
2.972903
0.928963
if table == 'sr-Latn': return text.translate(SR_LATN_TABLE) elif table == 'az-Latn': return text.translate(AZ_LATN_TABLE) else: raise ValueError("Unknown transliteration table: {!r}".format(table))
def transliterate(table, text)
Transliterate text according to one of the tables above. `table` chooses the table. It looks like a language code but comes from a very restricted set: - 'sr-Latn' means to convert Serbian, which may be in Cyrillic, into the Latin alphabet. - 'az-Latn' means the same for Azerbaijani Cyrillic to ...
2.682949
2.277372
1.17809
'''Set the current exit code based on the Statistics.''' for error_type in statistics.errors: exit_code = app.ERROR_CODE_MAP.get(error_type) if exit_code: app.update_exit_code(exit_code)
def _update_exit_code_from_stats(cls, statistics: Statistics, app: Application)
Set the current exit code based on the Statistics.
5.04246
3.528266
1.429161
'''Return whether the document is likely to be a Sitemap.''' if response.body: if cls.is_file(response.body): return True
def is_response(cls, response)
Return whether the document is likely to be a Sitemap.
12.576195
5.007771
2.511336
'''Return whether the file is likely a Sitemap.''' peeked_data = wpull.util.peek_file(file) if is_gzip(peeked_data): try: peeked_data = wpull.decompression.gzip_uncompress( peeked_data, truncated=True ) except zlib.erro...
def is_file(cls, file)
Return whether the file is likely a Sitemap.
4.923816
4.01192
1.227296
'''Parse and return a URLInfo. This function logs a warning if the URL cannot be parsed and returns None. ''' try: url_info = URLInfo.parse(url, encoding=encoding) except ValueError as error: _logger.warning(__( _('Unable to parse URL ‘{url}’: {error}.'), ...
def parse_url_or_log(url, encoding='utf-8')
Parse and return a URLInfo. This function logs a warning if the URL cannot be parsed and returns None.
5.919345
4.03636
1.466506
'''Normalizes a hostname so that it is ASCII and valid domain name.''' try: new_hostname = hostname.encode('idna').decode('ascii').lower() except UnicodeError as error: raise UnicodeError('Hostname {} rejected: {}'.format(hostname, error)) from error if hostname != new_hostname: ...
def normalize_hostname(hostname)
Normalizes a hostname so that it is ASCII and valid domain name.
4.892896
4.225237
1.158017
'''Normalize a path string. Flattens a path by removing dot parts, percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' if not path.startswith('/'): path = '/' + path path = percent_encode(flatten_path(path, flatten_slashes=True), encoding=encoding)...
def normalize_path(path, encoding='utf-8')
Normalize a path string. Flattens a path by removing dot parts, percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
8.786017
3.219705
2.728827
'''Normalize a query string. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode_plus(text, encoding=encoding) return uppercase_percent_encoding(path)
def normalize_query(text, encoding='utf-8')
Normalize a query string. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
11.021081
4.553272
2.420475
'''Normalize a fragment. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=FRAGMENT_ENCODE_SET) return uppercase_percent_encoding(path)
def normalize_fragment(text, encoding='utf-8')
Normalize a fragment. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
10.680976
4.665184
2.289508
'''Normalize a username Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=USERNAME_ENCODE_SET) return uppercase_percent_encoding(path)
def normalize_username(text, encoding='utf-8')
Normalize a username Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
11.180542
5.325304
2.099513
'''Normalize a password Percent-encodes unacceptable characters and ensures percent-encoding is uppercase. ''' path = percent_encode(text, encoding=encoding, encode_set=PASSWORD_ENCODE_SET) return uppercase_percent_encoding(path)
def normalize_password(text, encoding='utf-8')
Normalize a password Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
12.06625
5.753571
2.097176
'''Percent encode text. Unlike Python's ``quote``, this function accepts a blacklist instead of a whitelist of safe characters. ''' byte_string = text.encode(encoding) try: mapping = _percent_encoder_map_cache[encode_set] except KeyError: mapping = _percent_encoder_map_cach...
def percent_encode(text, encode_set=DEFAULT_ENCODE_SET, encoding='utf-8')
Percent encode text. Unlike Python's ``quote``, this function accepts a blacklist instead of a whitelist of safe characters.
4.822957
3.020801
1.596582
'''Percent encode text for query strings. Unlike Python's ``quote_plus``, this function accepts a blacklist instead of a whitelist of safe characters. ''' if ' ' not in text: return percent_encode(text, encode_set, encoding) else: result = percent_encode(text, encode_set, encodi...
def percent_encode_plus(text, encode_set=QUERY_ENCODE_SET, encoding='utf-8')
Percent encode text for query strings. Unlike Python's ``quote_plus``, this function accepts a blacklist instead of a whitelist of safe characters.
4.605263
2.479007
1.857705
'''Return whether URL schemes are similar. This function considers the following schemes to be similar: * HTTP and HTTPS ''' if scheme1 == scheme2: return True if scheme1 in ('http', 'https') and scheme2 in ('http', 'https'): return True return False
def schemes_similar(scheme1, scheme2)
Return whether URL schemes are similar. This function considers the following schemes to be similar: * HTTP and HTTPS
3.470663
2.38799
1.453383
'''Return whether the a path is a subpath of another. Args: base_path: The base path test_path: The path which we are testing trailing_slash: If True, the trailing slash is treated with importance. For example, ``/images/`` is a directory while ``/images`` is a f...
def is_subdir(base_path, test_path, trailing_slash=False, wildcards=False)
Return whether the a path is a subpath of another. Args: base_path: The base path test_path: The path which we are testing trailing_slash: If True, the trailing slash is treated with importance. For example, ``/images/`` is a directory while ``/images`` is a file. ...
2.735394
1.487866
1.838469
'''Uppercases percent-encoded sequences.''' if '%' not in text: return text return re.sub( r'%[a-f0-9][a-f0-9]', lambda match: match.group(0).upper(), text)
def uppercase_percent_encoding(text)
Uppercases percent-encoded sequences.
3.48162
3.520421
0.988979
'''Split the query string. Note for empty values: If an equal sign (``=``) is present, the value will be an empty string (``''``). Otherwise, the value will be ``None``:: >>> list(split_query('a=&b', keep_blank_values=True)) [('a', ''), ('b', None)] No processing is done on the actual...
def split_query(qs, keep_blank_values=False)
Split the query string. Note for empty values: If an equal sign (``=``) is present, the value will be an empty string (``''``). Otherwise, the value will be ``None``:: >>> list(split_query('a=&b', keep_blank_values=True)) [('a', ''), ('b', None)] No processing is done on the actual values...
3.60736
1.802721
2.001064
'''Return a key-values mapping from a query string. Plus symbols are replaced with spaces. ''' dict_obj = {} for key, value in split_query(text, True): if key not in dict_obj: dict_obj[key] = [] if value: dict_obj[key].append(value.replace('+', ' ')) ...
def query_to_map(text)
Return a key-values mapping from a query string. Plus symbols are replaced with spaces.
4.363529
2.768111
1.576356
'''Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.''' if url.startswith('//') and len(url) > 2: scheme = base_url.partition(':')[0] if scheme: return urllib.parse.urljoin( base_url, '{0}:{1}'.format(scheme, url), ...
def urljoin(base_url, url, allow_fragments=True)
Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.
3.35728
2.662867
1.260776
'''Flatten an absolute URL path by removing the dot segments. :func:`urllib.parse.urljoin` has some support for removing dot segments, but it is conservative and only removes them as needed. Arguments: path (str): The URL path. flatten_slashes (bool): If True, consecutive slashes are r...
def flatten_path(path, flatten_slashes=False)
Flatten an absolute URL path by removing the dot segments. :func:`urllib.parse.urljoin` has some support for removing dot segments, but it is conservative and only removes them as needed. Arguments: path (str): The URL path. flatten_slashes (bool): If True, consecutive slashes are removed....
3.989214
2.418833
1.649231
'''Parse a URL and return a URLInfo.''' if url is None: return None url = url.strip() if frozenset(url) & C0_CONTROL_SET: raise ValueError('URL contains control codes: {}'.format(ascii(url))) scheme, sep, remaining = url.partition(':') if not sc...
def parse(cls, url, default_scheme='http', encoding='utf-8')
Parse a URL and return a URLInfo.
2.533142
2.52003
1.005203
'''Parse the authority part and return userinfo and host.''' userinfo, sep, host = authority.partition('@') if not sep: return '', userinfo else: return userinfo, host
def parse_authority(cls, authority)
Parse the authority part and return userinfo and host.
6.191607
3.902547
1.586556
'''Parse the userinfo and return username and password.''' username, sep, password = userinfo.partition(':') return username, password
def parse_userinfo(cls, userinfo)
Parse the userinfo and return username and password.
7.264726
4.846736
1.49889
'''Parse the host and return hostname and port.''' if host.endswith(']'): return cls.parse_hostname(host), None else: hostname, sep, port = host.rpartition(':') if sep: port = int(port) if port < 0 or port > 65535: raise Va...
def parse_host(cls, host)
Parse the host and return hostname and port.
3.219844
2.937485
1.096123
'''Parse the hostname and normalize.''' if hostname.startswith('['): return cls.parse_ipv6_hostname(hostname) else: try: new_hostname = normalize_ipv4_address(hostname) except ValueError: # _logger.debug('', exc_info=True) ...
def parse_hostname(cls, hostname)
Parse the hostname and normalize.
3.88736
3.689328
1.053677
'''Parse and normalize a IPv6 address.''' if not hostname.startswith('[') or not hostname.endswith(']'): raise ValueError('Invalid IPv6 address: {}' .format(ascii(hostname))) hostname = ipaddress.IPv6Address(hostname[1:-1]).compressed return hos...
def parse_ipv6_hostname(cls, hostname)
Parse and normalize a IPv6 address.
4.768398
4.137809
1.152397
'''Return a dict of the attributes.''' return dict( raw=self.raw, scheme=self.scheme, authority=self.authority, netloc=self.authority, path=self.path, query=self.query, fragment=self.fragment, userinfo=self.u...
def to_dict(self)
Return a dict of the attributes.
2.425935
2.227289
1.089187
'''Return whether the URL is using the default port.''' if self.scheme in RELATIVE_SCHEME_DEFAULT_PORTS: return RELATIVE_SCHEME_DEFAULT_PORTS[self.scheme] == self.port
def is_port_default(self)
Return whether the URL is using the default port.
6.418642
4.641787
1.382795
'''Return the host portion but omit default port if needed.''' default_port = RELATIVE_SCHEME_DEFAULT_PORTS.get(self.scheme) if not default_port: return '' assert '[' not in self.hostname assert ']' not in self.hostname if self.is_ipv6(): hostnam...
def hostname_with_port(self)
Return the host portion but omit default port if needed.
3.731959
2.803531
1.331164
'''Return new empty URLRecord.''' url_record = URLRecord() url_record.url = request.url_info.url url_record.status = Status.in_progress url_record.try_count = 0 url_record.level = 0 return url_record
def _new_url_record(cls, request: Request) -> URLRecord
Return new empty URLRecord.
4.406719
3.942846
1.117649
'''Request callback handler.''' self._item_session = self._new_item_session(request) self._item_session.request = request if self._cookie_jar: self._cookie_jar.add_cookie_header(request) verdict, reason = self._fetch_rule.check_subsequent_web_request(self._item_sess...
def _client_request_callback(self, request: Request)
Request callback handler.
7.757873
7.380856
1.05108
'''Pre-response callback handler.''' self._item_session.response = response if self._cookie_jar: self._cookie_jar.extract_cookies(response, self._item_session.request) action = self._result_rule.handle_pre_response(self._item_session) self._file_writer_session.proce...
def _server_begin_response_callback(self, response: Response)
Pre-response callback handler.
8.527858
7.010046
1.216519
'''Response callback handler.''' request = self._item_session.request response = self._item_session.response _logger.info(__( _('Fetched ‘{url}’: {status_code} {reason}. ' 'Length: {content_length} [{content_type}].'), url=request.url, s...
def _server_end_response_callback(self, respoonse: Response)
Response callback handler.
3.282732
3.214109
1.02135
'''Create streams and commander. Coroutine. ''' assert not self._control_connection self._control_connection = yield from self._acquire_request_connection(self._request) self._control_stream = ControlStream(self._control_connection) self._commander = Commander(se...
def _init_stream(self)
Create streams and commander. Coroutine.
3.844867
3.110008
1.236289
'''Connect and login. Coroutine. ''' username = self._request.url_info.username or self._request.username or 'anonymous' password = self._request.url_info.password or self._request.password or '-wpull@' cached_login = self._login_table.get(self._control_connection) ...
def _log_in(self)
Connect and login. Coroutine.
5.385537
4.586727
1.174157
'''Start a file or directory listing download. Args: request: Request. Returns: A Response populated with the initial data connection reply. Once the response is received, call :meth:`download`. Coroutine. ''' if self._session_state != ...
def start(self, request: Request) -> Response
Start a file or directory listing download. Args: request: Request. Returns: A Response populated with the initial data connection reply. Once the response is received, call :meth:`download`. Coroutine.
6.579813
3.890371
1.691307
'''Fetch a file listing. Args: request: Request. Returns: A listing response populated with the initial data connection reply. Once the response is received, call :meth:`download_listing`. Coroutine. ''' if self._session_sta...
def start_listing(self, request: Request) -> ListingResponse
Fetch a file listing. Args: request: Request. Returns: A listing response populated with the initial data connection reply. Once the response is received, call :meth:`download_listing`. Coroutine.
5.424972
3.698614
1.466758
'''Prepare for a fetch. Coroutine. ''' self._request = request self._response = response yield from self._init_stream() connection_closed = self._control_connection.closed() if connection_closed: self._login_table.pop(self._control_connecti...
def _prepare_fetch(self, request: Request, response: Response)
Prepare for a fetch. Coroutine.
6.585885
5.751999
1.144973
'''Start data stream transfer.''' begin_reply = yield from self._commander.begin_stream(command) self._response.reply = begin_reply self.event_dispatcher.notify(self.Event.begin_transfer, self._response)
def _begin_stream(self, command: Command)
Start data stream transfer.
13.003174
10.076858
1.2904
'''Read the response content into file. Args: file: A file object or asyncio stream. rewind: Seek the given file back to its original offset after reading is finished. duration_timeout: Maximum time in seconds of which the entire file ...
def download(self, file: Optional[IO]=None, rewind: bool=True, duration_timeout: Optional[float]=None) -> Response
Read the response content into file. Args: file: A file object or asyncio stream. rewind: Seek the given file back to its original offset after reading is finished. duration_timeout: Maximum time in seconds of which the entire file must be rea...
4.987805
2.777398
1.795855
'''Read file listings. Args: file: A file object or asyncio stream. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: A Response populated the file listings Be sure to call :meth:`start_file_li...
def download_listing(self, file: Optional[IO], duration_timeout: Optional[float]=None) -> \ ListingResponse
Read file listings. Args: file: A file object or asyncio stream. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: A Response populated the file listings Be sure to call :meth:`start_file_listing` firs...
4.515748
3.230286
1.397941
'''Open the data stream connection. Coroutine. ''' @asyncio.coroutine def connection_factory(address: Tuple[int, int]): self._data_connection = yield from self._acquire_connection(address[0], address[1]) return self._data_connection self._data_st...
def _open_data_stream(self)
Open the data stream connection. Coroutine.
3.790362
3.504998
1.081416
'''Return size of file. Coroutine. ''' try: size = yield from self._commander.size(request.file_path) return size except FTPServerError: return
def _fetch_size(self, request: Request) -> int
Return size of file. Coroutine.
10.999022
7.067925
1.556188
'''Parses text for HTTP Refresh URL. Returns: str, None ''' match = re.search(r'url\s*=(.+)', text, re.IGNORECASE) if match: url = match.group(1) if url.startswith('"'): url = url.strip('"') elif url.startswith("'"): url = url.strip("'") ...
def parse_refresh(text)
Parses text for HTTP Refresh URL. Returns: str, None
3.863269
2.928662
1.319124
'''urljoin with warning log on error. Returns: str, None''' try: return wpull.url.urljoin( base_url, url, allow_fragments=allow_fragments ) except ValueError as error: _logger.warning(__( _('Unable to parse URL ‘{url}’: {error}.'), url...
def urljoin_safe(base_url, url, allow_fragments=True)
urljoin with warning log on error. Returns: str, None
7.255051
5.119178
1.41723
'''Return whether the link is likely to be inline.''' file_type = mimetypes.guess_type(link, strict=False)[0] if file_type: top_level_type, subtype = file_type.split('/', 1) return top_level_type in ('image', 'video', 'audio') or subtype == 'javascript'
def is_likely_inline(link)
Return whether the link is likely to be inline.
3.563092
3.539924
1.006545
'''Return whether the text is likely to be a link. This function assumes that leading/trailing whitespace has already been removed. Returns: bool ''' text = text.lower() # Check for absolute or relative URLs if ( text.startswith('http://') or text.startswith('h...
def is_likely_link(text)
Return whether the text is likely to be a link. This function assumes that leading/trailing whitespace has already been removed. Returns: bool
3.425267
3.094922
1.106738
'''Return whether the text is likely to cause false positives. This function assumes that leading/trailing whitespace has already been removed. Returns: bool ''' # Check for string concatenation in JavaScript if text[:1] in ',;+:' or text[-1:] in '.,;+:': return True #...
def is_unlikely_link(text)
Return whether the text is likely to cause false positives. This function assumes that leading/trailing whitespace has already been removed. Returns: bool
5.712247
4.824005
1.18413
'''Return link type guessed by filename extension. Returns: str: A value from :class:`.item.LinkType`. ''' mime_type = mimetypes.guess_type(filename)[0] if not mime_type: return if mime_type == 'text/css': return LinkType.css elif mime_type == 'application/javascri...
def identify_link_type(filename)
Return link type guessed by filename extension. Returns: str: A value from :class:`.item.LinkType`.
2.654921
1.986208
1.336678
'''Return a stream writer.''' if args.ascii_print: return wpull.util.ASCIIStreamWriter(stream) else: return stream
def new_encoded_stream(args, stream)
Return a stream writer.
15.625262
12.799896
1.220734
'''Schedule check function.''' if self._running: _logger.debug('Schedule check function.') self._call_later_handle = self._event_loop.call_later( self._timeout, self._check)
def _schedule(self)
Schedule check function.
6.853693
6.249079
1.096753
'''Check and close connection if needed.''' _logger.debug('Check if timeout.') self._call_later_handle = None if self._touch_time is not None: difference = self._event_loop.time() - self._touch_time _logger.debug('Time difference %s', difference) if ...
def _check(self)
Check and close connection if needed.
5.884392
5.113838
1.15068
'''Stop running timers.''' if self._call_later_handle: self._call_later_handle.cancel() self._running = False
def close(self)
Stop running timers.
9.346817
6.594716
1.417319
'''Return whether the connection is closed.''' return not self.writer or not self.reader or self.reader.at_eof()
def closed(self) -> bool
Return whether the connection is closed.
9.140193
6.993078
1.307034
'''Establish a connection.''' _logger.debug(__('Connecting to {0}.', self._address)) if self._state != ConnectionState.ready: raise Exception('Closed connection must be reset before reusing.') if self._sock: connection_future = asyncio.open_connection( ...
def connect(self)
Establish a connection.
4.856978
4.855966
1.000208
'''Close the connection.''' if self.writer: _logger.debug('Closing connection.') self.writer.close() self.writer = None self.reader = None if self._close_timer: self._close_timer.close() self._state = ConnectionState.dead
def close(self)
Close the connection.
5.17013
5.24565
0.985603
'''Write data.''' assert self._state == ConnectionState.created, \ 'Expect conn created. Got {}.'.format(self._state) self.writer.write(data) if drain: fut = self.writer.drain() if fut: yield from self.run_network_operation( ...
def write(self, data: bytes, drain: bool=True)
Write data.
9.10297
8.848121
1.028803
'''Read data.''' assert self._state == ConnectionState.created, \ 'Expect conn created. Got {}.'.format(self._state) data = yield from \ self.run_network_operation( self.reader.read(amount), close_timeout=self._timeout, nam...
def read(self, amount: int=-1) -> bytes
Read data.
11.208344
11.245153
0.996727
'''Read a line of data.''' assert self._state == ConnectionState.created, \ 'Expect conn created. Got {}.'.format(self._state) with self._close_timer.with_timeout(): data = yield from \ self.run_network_operation( self.reader.readline(...
def readline(self) -> bytes
Read a line of data.
9.776624
9.892412
0.988295
'''Run the task and raise appropriate exceptions. Coroutine. ''' if wait_timeout is not None and close_timeout is not None: raise Exception( 'Cannot use wait_timeout and close_timeout at the same time') try: if close_timeout is not None: ...
def run_network_operation(self, task, wait_timeout=None, close_timeout=None, name='Network operation')
Run the task and raise appropriate exceptions. Coroutine.
3.022807
2.879392
1.049807
'''Start client TLS on this connection and return SSLConnection. Coroutine ''' sock = self.writer.get_extra_info('socket') ssl_conn = SSLConnection( self._address, ssl_context=ssl_context, hostname=self._hostname, timeout=self._timeout, ...
def start_tls(self, ssl_context: Union[bool, dict, ssl.SSLContext]=True) \ -> 'SSLConnection'
Start client TLS on this connection and return SSLConnection. Coroutine
4.744287
3.753605
1.263928
'''Check if certificate matches hostname.''' # Based on tornado.iostream.SSLIOStream # Needed for older OpenSSL (<0.9.8f) versions verify_mode = self._ssl_context.verify_mode assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONA...
def _verify_cert(self, sock: ssl.SSLSocket)
Check if certificate matches hostname.
3.529789
3.234478
1.091301
'''Remove items that are expired or exceed the max size.''' now_time = time.time() while self._seq and self._seq[0].expire_time < now_time: item = self._seq.popleft() del self._map[item.key] if self._max_items: while self._seq and len(self._seq) > se...
def trim(self)
Remove items that are expired or exceed the max size.
3.342668
2.540171
1.315923
'''Strip session ID from URL path.''' for pattern in SESSION_ID_PATH_PATTERNS: match = pattern.match(path) if match: path = match.group(1) + match.group(3) return path
def strip_path_session_id(path)
Strip session ID from URL path.
3.42532
3.263795
1.04949
'''Rewrite the given URL.''' if url_info.scheme not in ('http', 'https'): return url_info if self._session_id_enabled: url = '{scheme}://{authority}{path}?{query}#{fragment}'.format( scheme=url_info.scheme, authority=url_info.authority, ...
def rewrite(self, url_info: URLInfo) -> URLInfo
Rewrite the given URL.
2.478719
2.476195
1.001019
'''Parse PASV address.''' match = re.search( r'\(' r'(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*,' r'\s*(\d{1,3})\s*' r'\)', text) if match: return ( '{0}.{1}.{2}.{3}...
def parse_address(text: str) -> Tuple[str, int]
Parse PASV address.
1.944897
1.802513
1.078992
'''Return the reply code as a tuple. Args: code: The reply code. Returns: Each item in the tuple is the digit. ''' return code // 100, code // 10 % 10, code % 10
def reply_code_tuple(code: int) -> Tuple[int, int, int]
Return the reply code as a tuple. Args: code: The reply code. Returns: Each item in the tuple is the digit.
3.409451
2.150044
1.585759
'''Parse machine listing. Args: text: The listing. convert: Convert sizes and dates. strict: Method of handling errors. ``True`` will raise ``ValueError``. ``False`` will ignore rows with errors. Returns: list: A list of dict of the facts defined in RFC 3659. ...
def parse_machine_listing(text: str, convert: bool=True, strict: bool=True) -> \ List[dict]
Parse machine listing. Args: text: The listing. convert: Convert sizes and dates. strict: Method of handling errors. ``True`` will raise ``ValueError``. ``False`` will ignore rows with errors. Returns: list: A list of dict of the facts defined in RFC 3659. T...
4.067794
2.20325
1.84627
'''Convert sizes and time values. Size will be ``int`` while time value will be :class:`datetime.datetime`. ''' if name == 'modify': return convert_machine_list_time_val(value) elif name == 'size': return int(value) else: return value
def convert_machine_list_value(name: str, value: str) -> \ Union[datetime.datetime, str, int]
Convert sizes and time values. Size will be ``int`` while time value will be :class:`datetime.datetime`.
5.756972
3.173718
1.813952
'''Convert RFC 3659 time-val to datetime objects.''' # TODO: implement fractional seconds text = text[:14] if len(text) != 14: raise ValueError('Time value not 14 chars') year = int(text[0:4]) month = int(text[4:6]) day = int(text[6:8]) hour = int(text[8:10]) minute = int(t...
def convert_machine_list_time_val(text: str) -> datetime.datetime
Convert RFC 3659 time-val to datetime objects.
2.4284
2.024275
1.199639
'''Convert results from parsing machine listings to FileEntry list.''' for listing in listings: yield FileEntry( listing['name'], type=listing.get('type'), size=listing.get('size'), date=listing.get('modify') )
def machine_listings_to_file_entries(listings: Iterable[dict]) -> \ Iterable[FileEntry]
Convert results from parsing machine listings to FileEntry list.
4.765667
3.618038
1.317196
'''Return reply code.''' if len(self.args) >= 2 and isinstance(self.args[1], int): return self.args[1]
def reply_code(self)
Return reply code.
4.612545
4.190355
1.100753
'''Run the producer, if exception, stop engine.''' try: yield from self._producer.process() except Exception as error: if not isinstance(error, StopIteration): # Stop the workers so the producer exception will be handled # when we finally y...
def _run_producer_wrapper(self)
Run the producer, if exception, stop engine.
8.398386
6.107337
1.375131
'''Iterate CDX file. Args: file (str): A file object. encoding (str): The encoding of the file. Returns: iterator: Each item is a dict that maps from field key to value. ''' with codecs.getreader(encoding)(file) as stream: header_line = stream.readline() sep...
def read_cdx(file, encoding='utf8')
Iterate CDX file. Args: file (str): A file object. encoding (str): The encoding of the file. Returns: iterator: Each item is a dict that maps from field key to value.
3.102074
2.237926
1.386138
'''Set the required fields for the record.''' self.fields[self.WARC_TYPE] = warc_type self.fields[self.CONTENT_TYPE] = content_type self.fields[self.WARC_DATE] = wpull.util.datetime_str() self.fields[self.WARC_RECORD_ID] = '<{0}>'.format(uuid.uuid4().urn)
def set_common_fields(self, warc_type: str, content_type: str)
Set the required fields for the record.
3.463691
2.981565
1.161702
'''Find and set the content length. .. seealso:: :meth:`compute_checksum`. ''' if not self.block_file: self.fields['Content-Length'] = '0' return with wpull.util.reset_file_offset(self.block_file): wpull.util.seek_file_end(self.block_file) ...
def set_content_length(self)
Find and set the content length. .. seealso:: :meth:`compute_checksum`.
4.914501
3.766743
1.304708
'''Compute and add the checksum data to the record fields. This function also sets the content length. ''' if not self.block_file: self.fields['Content-Length'] = '0' return block_hasher = hashlib.sha1() payload_hasher = hashlib.sha1() w...
def compute_checksum(self, payload_offset: Optional[int]=None)
Compute and add the checksum data to the record fields. This function also sets the content length.
2.466726
2.079885
1.185991
'''Return the HTTP header. It only attempts to read the first 4 KiB of the payload. Returns: Response, None: Returns an instance of :class:`.http.request.Response` or None. ''' with wpull.util.reset_file_offset(self.block_file): data = self.b...
def get_http_header(self) -> Response
Return the HTTP header. It only attempts to read the first 4 KiB of the payload. Returns: Response, None: Returns an instance of :class:`.http.request.Response` or None.
4.711443
3.122276
1.508977
'''Write the parameters to a file for PhantomJS to read.''' param_dict = { 'url': self._params.url, 'snapshot_paths': self._params.snapshot_paths, 'wait_time': self._params.wait_time, 'num_scrolls': self._params.num_scrolls, 'smart_scroll': sel...
def _write_config(self)
Write the parameters to a file for PhantomJS to read.
2.396977
2.181736
1.098656
'''Clean closed connections. Args: force: Clean connected and idle connections too. Coroutine. ''' with (yield from self._lock): for connection in tuple(self.ready): if force or connection.closed(): connection.close() ...
def clean(self, force: bool=False)
Clean closed connections. Args: force: Clean connected and idle connections too. Coroutine.
7.11576
3.164496
2.248623
'''Forcibly close all connections. This instance will not be usable after calling this method. ''' for connection in self.ready: connection.close() for connection in self.busy: connection.close() self._closed = True
def close(self)
Forcibly close all connections. This instance will not be usable after calling this method.
5.388882
3.252485
1.656851
'''Register and return a connection. Coroutine. ''' assert not self._closed yield from self._condition.acquire() while True: if self.ready: connection = self.ready.pop() break elif len(self.busy) < self.max_connec...
def acquire(self) -> Connection
Register and return a connection. Coroutine.
3.958705
3.482425
1.136767
'''Unregister a connection. Args: connection: Connection instance returned from :meth:`acquire`. reuse: If True, the connection is made available for reuse. Coroutine. ''' yield from self._condition.acquire() self.busy.remove(connection) ...
def release(self, connection: Connection, reuse: bool=True)
Unregister a connection. Args: connection: Connection instance returned from :meth:`acquire`. reuse: If True, the connection is made available for reuse. Coroutine.
5.61726
2.88639
1.946119
'''Return an available connection. Args: host: A hostname or IP address. port: Port number. use_ssl: Whether to return a SSL connection. host_key: If provided, it overrides the key used for per-host connection pooling. This is useful for p...
def acquire(self, host: str, port: int, use_ssl: bool=False, host_key: Optional[Any]=None) \ -> Union[Connection, SSLConnection]
Return an available connection. Args: host: A hostname or IP address. port: Port number. use_ssl: Whether to return a SSL connection. host_key: If provided, it overrides the key used for per-host connection pooling. This is useful for proxies for ...
3.436715
2.76295
1.243857