response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Register a RequestHandler class | def register_rh(handler):
"""Register a RequestHandler class"""
assert issubclass(handler, RequestHandler), f'{handler} must be a subclass of RequestHandler'
assert handler.RH_KEY not in _REQUEST_HANDLERS, f'RequestHandler {handler.RH_KEY} already registered'
_REQUEST_HANDLERS[handler.RH_KEY] = handler
... |
Unified proxy selector for all backends | def select_proxy(url, proxies):
"""Unified proxy selector for all backends"""
url_components = urllib.parse.urlparse(url)
if 'no' in proxies:
hostport = url_components.hostname + format_field(url_components.port, None, ':%s')
if urllib.request.proxy_bypass_environment(hostport, {'no': proxi... |
Unified redirect method handling | def get_redirect_method(method, status):
"""Unified redirect method handling"""
# A 303 must either use GET or HEAD for subsequent request
# https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.4
if status == 303 and method != 'HEAD':
method = 'GET'
# 301 and 302 redirects are commonly... |
Get corresponding item from a mapping string like 'A>B/C>D/E'
@returns (target, error_message) | def resolve_mapping(source, mapping):
"""
Get corresponding item from a mapping string like 'A>B/C>D/E'
@returns (target, error_message)
"""
for pair in mapping.lower().split('/'):
kv = pair.split('>', 1)
if len(kv) == 1 or kv[0].strip() == source:
target = kv[-1].str... |
Escape non-ASCII characters as suggested by RFC 3986 | def escape_rfc3986(s):
"""Escape non-ASCII characters as suggested by RFC 3986"""
return urllib.parse.quote(s, b"%/;:@&=+$,!~*'()?#[]") |
Normalize URL as suggested by RFC 3986 | def normalize_url(url):
"""Normalize URL as suggested by RFC 3986"""
url_parsed = urllib.parse.urlparse(url)
return url_parsed._replace(
netloc=url_parsed.netloc.encode('idna').decode('ascii'),
path=escape_rfc3986(remove_dot_segments(url_parsed.path)),
params=escape_rfc3986(url_parse... |
Safely traverse nested `dict`s and `Iterable`s
>>> obj = [{}, {"key": "value"}]
>>> traverse_obj(obj, (1, "key"))
'value'
Each of the provided `paths` is tested and the first producing a valid result will be returned.
The next path will also be tested if the path branched but no results could be found.
Supported valu... | def traverse_obj(
obj, *paths, default=NO_DEFAULT, expected_type=None, get_all=True,
casesense=True, is_user_input=NO_DEFAULT, traverse_string=False):
"""
Safely traverse nested `dict`s and `Iterable`s
>>> obj = [{}, {"key": "value"}]
>>> traverse_obj(obj, (1, "key"))
'value'
E... |
Returns the platform name as a str | def platform_name():
""" Returns the platform name as a str """
return platform.platform() |
Get preferred encoding.
Returns the best encoding scheme for the system, based on
locale.getpreferredencoding() and some further tweaks. | def preferredencoding():
"""Get preferred encoding.
Returns the best encoding scheme for the system, based on
locale.getpreferredencoding() and some further tweaks.
"""
try:
pref = locale.getpreferredencoding()
'TEST'.encode(pref)
except Exception:
pref = 'UTF-8'
re... |
Encode obj as JSON and write it to fn, atomically if possible | def write_json_file(obj, fn):
""" Encode obj as JSON and write it to fn, atomically if possible """
tf = tempfile.NamedTemporaryFile(
prefix=f'{os.path.basename(fn)}.', dir=os.path.dirname(fn),
suffix='.tmp', delete=False, mode='w', encoding='utf-8')
try:
with tf:
json.... |
Find the xpath xpath[@key=val] | def find_xpath_attr(node, xpath, key, val=None):
""" Find the xpath xpath[@key=val] """
assert re.match(r'^[a-zA-Z_-]+$', key)
expr = xpath + ('[@%s]' % key if val is None else f"[@{key}='{val}']")
return node.find(expr) |
Return the content of the tag with the specified ID in the passed HTML document | def get_element_by_id(id, html, **kwargs):
"""Return the content of the tag with the specified ID in the passed HTML document"""
return get_element_by_attribute('id', id, html, **kwargs) |
Return the html of the tag with the specified ID in the passed HTML document | def get_element_html_by_id(id, html, **kwargs):
"""Return the html of the tag with the specified ID in the passed HTML document"""
return get_element_html_by_attribute('id', id, html, **kwargs) |
Return the content of the first tag with the specified class in the passed HTML document | def get_element_by_class(class_name, html):
"""Return the content of the first tag with the specified class in the passed HTML document"""
retval = get_elements_by_class(class_name, html)
return retval[0] if retval else None |
Return the html of the first tag with the specified class in the passed HTML document | def get_element_html_by_class(class_name, html):
"""Return the html of the first tag with the specified class in the passed HTML document"""
retval = get_elements_html_by_class(class_name, html)
return retval[0] if retval else None |
Return the content of all tags with the specified class in the passed HTML document as a list | def get_elements_by_class(class_name, html, **kargs):
"""Return the content of all tags with the specified class in the passed HTML document as a list"""
return get_elements_by_attribute(
'class', r'[^\'"]*(?<=[\'"\s])%s(?=[\'"\s])[^\'"]*' % re.escape(class_name),
html, escape_value=False) |
Return the html of all tags with the specified class in the passed HTML document as a list | def get_elements_html_by_class(class_name, html):
"""Return the html of all tags with the specified class in the passed HTML document as a list"""
return get_elements_html_by_attribute(
'class', r'[^\'"]*(?<=[\'"\s])%s(?=[\'"\s])[^\'"]*' % re.escape(class_name),
html, escape_value=False) |
Return the content of the tag with the specified attribute in the passed HTML document | def get_elements_by_attribute(*args, **kwargs):
"""Return the content of the tag with the specified attribute in the passed HTML document"""
return [content for content, _ in get_elements_text_and_html_by_attribute(*args, **kwargs)] |
Return the html of the tag with the specified attribute in the passed HTML document | def get_elements_html_by_attribute(*args, **kwargs):
"""Return the html of the tag with the specified attribute in the passed HTML document"""
return [whole for _, whole in get_elements_text_and_html_by_attribute(*args, **kwargs)] |
Return the text (content) and the html (whole) of the tag with the specified
attribute in the passed HTML document | def get_elements_text_and_html_by_attribute(attribute, value, html, *, tag=r'[\w:.-]+', escape_value=True):
"""
Return the text (content) and the html (whole) of the tag with the specified
attribute in the passed HTML document
"""
if not value:
return
quote = '' if re.match(r'''[\s"'`=<... |
For the first element with the specified tag in the passed HTML document
return its' content (text) and the whole element (html) | def get_element_text_and_html_by_tag(tag, html):
"""
For the first element with the specified tag in the passed HTML document
return its' content (text) and the whole element (html)
"""
def find_or_raise(haystack, needle, exc):
try:
return haystack.index(needle)
except Va... |
Given a string for an HTML element such as
<el
a="foo" B="bar" c="&98;az" d=boz
empty= noval entity="&"
sq='"' dq="'"
>
Decode and return a dictionary of attributes.
{
'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
'empty': '', 'noval': None, 'entity': '&',
'sq': '"', 'dq': '''
}. | def extract_attributes(html_element):
"""Given a string for an HTML element such as
<el
a="foo" B="bar" c="&98;az" d=boz
empty= noval entity="&"
sq='"' dq="'"
>
Decode and return a dictionary of attributes.
{
'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
... |
Given a string for an series of HTML <li> elements,
return a dictionary of their attributes | def parse_list(webpage):
"""Given a string for an series of HTML <li> elements,
return a dictionary of their attributes"""
parser = HTMLListAttrsParser()
parser.feed(webpage)
parser.close()
return parser.items |
Clean an HTML snippet into a readable string | def clean_html(html):
"""Clean an HTML snippet into a readable string"""
if html is None: # Convenience for sanitizing descriptions etc.
return html
html = re.sub(r'\s+', ' ', html)
html = re.sub(r'(?u)\s?<\s?br\s?/?\s?>\s?', '\n', html)
html = re.sub(r'(?u)<\s?/\s?p\s?>\s?<\s?p[^>]*>', '... |
Try to open the given filename, and slightly tweak it if this fails.
Attempts to open the given filename. If this fails, it tries to change
the filename slightly, step by step, until it's either able to open it
or it fails and raises a final exception, like the standard open()
function.
It returns the tuple (stream, ... | def sanitize_open(filename, open_mode):
"""Try to open the given filename, and slightly tweak it if this fails.
Attempts to open the given filename. If this fails, it tries to change
the filename slightly, step by step, until it's either able to open it
or it fails and raises a final exception, like th... |
Convert RFC 2822 defined time string into system timestamp | def timeconvert(timestr):
"""Convert RFC 2822 defined time string into system timestamp"""
timestamp = None
timetuple = email.utils.parsedate_tz(timestr)
if timetuple is not None:
timestamp = email.utils.mktime_tz(timetuple)
return timestamp |
Sanitizes a string so it could be used as part of a filename.
@param restricted Use a stricter subset of allowed characters
@param is_id Whether this is an ID that should be kept unchanged if possible.
If unset, yt-dlp's new sanitization rules are in effect | def sanitize_filename(s, restricted=False, is_id=NO_DEFAULT):
"""Sanitizes a string so it could be used as part of a filename.
@param restricted Use a stricter subset of allowed characters
@param is_id Whether this is an ID that should be kept unchanged if possible.
If unset... |
Sanitizes and normalizes path on Windows | def sanitize_path(s, force=False):
"""Sanitizes and normalizes path on Windows"""
# XXX: this handles drive relative paths (c:sth) incorrectly
if sys.platform == 'win32':
force = False
drive_or_unc, _ = os.path.splitdrive(s)
elif force:
drive_or_unc = ''
else:
retu... |
Expand shell variables and ~ | def expand_path(s):
"""Expand shell variables and ~"""
return os.path.expandvars(compat_expanduser(s)) |
Remove all duplicates from the input iterable | def orderedSet(iterable, *, lazy=False):
"""Remove all duplicates from the input iterable"""
def _iter():
seen = [] # Do not use set since the items can be unhashable
for x in iterable:
if x not in seen:
seen.append(x)
yield x
return _iter() if ... |
Transforms an HTML entity to a character. | def _htmlentity_transform(entity_with_semicolon):
"""Transforms an HTML entity to a character."""
entity = entity_with_semicolon[:-1]
# Known non-numeric HTML entity
if entity in html.entities.name2codepoint:
return chr(html.entities.name2codepoint[entity])
# TODO: HTML5 allows entities wi... |
Return a UNIX timestamp from the given date | def parse_iso8601(date_str, delimiter='T', timezone=None):
""" Return a UNIX timestamp from the given date """
if date_str is None:
return None
date_str = re.sub(r'\.[0-9]+', '', date_str)
if timezone is None:
timezone, date_str = extract_timezone(date_str)
with contextlib.suppre... |
Return a string with the date in the format YYYYMMDD | def unified_strdate(date_str, day_first=True):
"""Return a string with the date in the format YYYYMMDD"""
if date_str is None:
return None
upload_date = None
# Replace commas
date_str = date_str.replace(',', ' ')
# Remove AM/PM + timezone
date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A... |
Return a datetime object from a string.
Supported format:
(now|today|yesterday|DATE)([+-]\d+(microsecond|second|minute|hour|day|week|month|year)s?)?
@param format strftime format of DATE
@param precision Round the datetime object: auto|microsecond|second|minute|hour|day
auto: round to ... | def datetime_from_str(date_str, precision='auto', format='%Y%m%d'):
R"""
Return a datetime object from a string.
Supported format:
(now|today|yesterday|DATE)([+-]\d+(microsecond|second|minute|hour|day|week|month|year)s?)?
@param format strftime format of DATE
@param precision Round... |
Return a date object from a string using datetime_from_str
@param strict Restrict allowed patterns to "YYYYMMDD" and
(now|today|yesterday)(-\d+(day|week|month|year)s?)? | def date_from_str(date_str, format='%Y%m%d', strict=False):
R"""
Return a date object from a string using datetime_from_str
@param strict Restrict allowed patterns to "YYYYMMDD" and
(now|today|yesterday)(-\d+(day|week|month|year)s?)?
"""
if strict and not re.fullmatch(r'\d{8}|(n... |
Increment/Decrement a datetime object by months. | def datetime_add_months(dt_, months):
"""Increment/Decrement a datetime object by months."""
month = dt_.month + months - 1
year = dt_.year + month // 12
month = month % 12 + 1
day = min(dt_.day, calendar.monthrange(year, month)[1])
return dt_.replace(year, month, day) |
Round a datetime object's time to a specific precision | def datetime_round(dt_, precision='day'):
"""
Round a datetime object's time to a specific precision
"""
if precision == 'microsecond':
return dt_
unit_seconds = {
'day': 86400,
'hour': 3600,
'minute': 60,
'second': 1,
}
roundto = lambda x, n: ((x + n... |
Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format | def hyphenate_date(date_str):
"""
Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
if match is not None:
return '-'.join(match.groups())
else:
return date_str |
Get Windows version. returns () if it's not running on Windows | def get_windows_version():
''' Get Windows version. returns () if it's not running on Windows '''
if compat_os_name == 'nt':
return version_tuple(platform.win32_ver()[1])
else:
return () |
Pass additional data in a URL for internal use. | def smuggle_url(url, data):
""" Pass additional data in a URL for internal use. """
url, idata = unsmuggle_url(url, {})
data.update(idata)
sdata = urllib.parse.urlencode(
{'__youtubedl_smuggle': json.dumps(data)})
return url + '#' + sdata |
Formats numbers with decimal sufixes like K, M, etc | def format_decimal_suffix(num, fmt='%d%s', *, factor=1000):
""" Formats numbers with decimal sufixes like K, M, etc """
num, factor = float_or_none(num), float(factor)
if num is None or num < 0:
return None
POSSIBLE_SUFFIXES = 'kMGTPEZY'
exponent = 0 if num == 0 else min(int(math.log(num, fa... |
Parse a string indicating a byte quantity into an integer | def parse_bytes(s):
"""Parse a string indicating a byte quantity into an integer"""
return lookup_unit_table(
{u: 1024**i for i, u in enumerate(['', *'KMGTPEZY'])},
s.upper(), strict=True) |
Return the number of a month by (locale-independently) English name | def month_by_name(name, lang='en'):
""" Return the number of a month by (locale-independently) English name """
month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
try:
return month_names.index(name) + 1
except ValueError:
return None |
Return the number of a month by (locale-independently) English
abbreviations | def month_by_abbreviation(abbrev):
""" Return the number of a month by (locale-independently) English
abbreviations """
try:
return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
except ValueError:
return None |
Replace all the '&' by '&' in XML | def fix_xml_ampersands(xml_str):
"""Replace all the '&' by '&' in XML"""
return re.sub(
r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
'&',
xml_str) |
This implementation is inconsistent, but is kept for compatibility.
Use this only for "webpage_url_domain" | def get_domain(url):
"""
This implementation is inconsistent, but is kept for compatibility.
Use this only for "webpage_url_domain"
"""
return remove_start(urllib.parse.urlparse(url).netloc, 'www.') or None |
A more relaxed version of int_or_none | def str_to_int(int_str):
""" A more relaxed version of int_or_none """
if isinstance(int_str, int):
return int_str
elif isinstance(int_str, str):
int_str = re.sub(r'[,\.\+]', '', int_str)
return int_or_none(int_str) |
Checks if the given binary is installed somewhere in PATH, and returns its name.
args can be a list of arguments for a short output (like -version) | def check_executable(exe, args=[]):
""" Checks if the given binary is installed somewhere in PATH, and returns its name.
args can be a list of arguments for a short output (like -version) """
try:
Popen.run([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
ret... |
Returns the version of the specified executable,
or False if the executable is not present | def get_exe_version(exe, args=['--version'],
version_re=None, unrecognized=('present', 'broken')):
""" Returns the version of the specified executable,
or False if the executable is not present """
unrecognized = variadic(unrecognized)
assert len(unrecognized) in (1, 2)
out = _ge... |
Float range | def frange(start=0, stop=None, step=1):
"""Float range"""
if stop is None:
start, stop = 0, start
sign = [-1, 1][step > 0] if step else 0
while sign * start < sign * stop:
yield start
start += step |
Replace URL components specified by kwargs
@param url str or parse url tuple
@param query_update update query
@returns str | def update_url(url, *, query_update=None, **kwargs):
"""Replace URL components specified by kwargs
@param url str or parse url tuple
@param query_update update query
@returns str
"""
if isinstance(url, str):
if not kwargs and not query_update:
... |
Encode a dict to RFC 7578-compliant form-data
data:
A dict where keys and values can be either Unicode or bytes-like
objects.
boundary:
If specified a Unicode object, it's used as the boundary. Otherwise
a random boundary is generated.
Reference: https://tools.ietf.org/html/rfc7578 | def multipart_encode(data, boundary=None):
'''
Encode a dict to RFC 7578-compliant form-data
data:
A dict where keys and values can be either Unicode or bytes-like
objects.
boundary:
If specified a Unicode object, it's used as the boundary. Otherwise
a random boundary is... |
Get a numeric quality value out of a list of possible values | def qualities(quality_ids):
""" Get a numeric quality value out of a list of possible values """
def q(qid):
try:
return quality_ids.index(qid)
except ValueError:
return -1
return q |
Add ellipses to overly long strings | def limit_length(s, length):
""" Add ellipses to overly long strings """
if s is None:
return None
ELLIPSES = '...'
if len(s) > length:
return s[:length - len(ELLIPSES)] + ELLIPSES
return s |
Returns if yt-dlp can be updated with -U | def ytdl_is_updateable():
""" Returns if yt-dlp can be updated with -U """
from ..update import is_non_updateable
return not is_non_updateable() |
Returns True iff the content should be blocked | def age_restricted(content_limit, age_limit):
""" Returns True iff the content should be blocked """
if age_limit is None: # No limit set
return False
if content_limit is None:
return False # Content available for everyone
return age_limit < content_limit |
Detect whether a file contains HTML by examining its first bytes. | def is_html(first_bytes):
""" Detect whether a file contains HTML by examining its first bytes. """
encoding = 'utf-8'
for bom, enc in BOMS:
while first_bytes.startswith(bom):
encoding, first_bytes = enc, first_bytes[len(bom):]
return re.match(r'^\s*<', first_bytes.decode(encoding... |
Render a list of rows, each as a list of values.
Text after a will be right aligned | def render_table(header_row, data, delim=False, extra_gap=0, hide_empty=False):
""" Render a list of rows, each as a list of values.
Text after a \t will be right aligned """
def width(string):
return len(remove_terminal_sequences(string).replace('\t', ''))
def get_max_lens(table):
retu... |
Filter a dictionary with a simple string syntax.
@returns Whether the filter passes
@param incomplete Set of keys that is expected to be missing from dct.
Can be True/False to indicate all/none of the keys may be missing.
All conditions on incomplete keys pass if the key... | def match_str(filter_str, dct, incomplete=False):
""" Filter a dictionary with a simple string syntax.
@returns Whether the filter passes
@param incomplete Set of keys that is expected to be missing from dct.
Can be True/False to indicate all/none of the keys may be missing... |
@param dfxp_data A bytes-like object containing DFXP data
@returns A unicode object containing converted SRT data | def dfxp2srt(dfxp_data):
'''
@param dfxp_data A bytes-like object containing DFXP data
@returns A unicode object containing converted SRT data
'''
LEGACY_NAMESPACES = (
(b'http://www.w3.org/ns/ttml', [
b'http://www.w3.org/2004/11/ttaf1',
b'http://www.w3.org/2006/04/tt... |
long_to_bytes(n:long, blocksize:int) : string
Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front of the
byte string with binary zeros so that the length is a multiple of
blocksize. | def long_to_bytes(n, blocksize=0):
"""long_to_bytes(n:long, blocksize:int) : string
Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front of the
byte string with binary zeros so that the length is a multiple of
blocksize.
"""
# after mu... |
bytes_to_long(string) : long
Convert a byte string to a long integer.
This is (essentially) the inverse of long_to_bytes(). | def bytes_to_long(s):
"""bytes_to_long(string) : long
Convert a byte string to a long integer.
This is (essentially) the inverse of long_to_bytes().
"""
acc = 0
length = len(s)
if length % 4:
extra = (4 - length % 4)
s = b'\000' * extra + s
length = length + extra
... |
Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
Input:
data: data to encrypt, bytes-like object
exponent, modulus: parameter e and N of RSA algorithm, both integer
Output: hex string of encrypted data
Limitation: supports one block encryption only | def ohdave_rsa_encrypt(data, exponent, modulus):
'''
Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
Input:
data: data to encrypt, bytes-like object
exponent, modulus: parameter e and N of RSA algorithm, both integer
Output: hex string of encrypted data
Limitation:... |
Padding input data with PKCS#1 scheme
@param {int[]} data input data
@param {int} length target length
@returns {int[]} padded data | def pkcs1pad(data, length):
"""
Padding input data with PKCS#1 scheme
@param {int[]} data input data
@param {int} length target length
@returns {int[]} padded data
"""
if len(data) > length - 11:
raise ValueError('Input data too long for PKCS#1 padding')
... |
Convert given int to a base-n string | def encode_base_n(num, n=None, table=None):
"""Convert given int to a base-n string"""
table = _base_n_table(n, table)
if not num:
return table[0]
result, base = '', len(table)
while num:
result = table[num % base] + result
num = num // base
return result |
Convert given base-n string to int | def decode_base_n(string, n=None, table=None):
"""Convert given base-n string to int"""
table = {char: index for index, char in enumerate(_base_n_table(n, table))}
result, base = 0, len(table)
for char in string:
result = result * base + table[char]
return result |
Converts an IRI (Internationalized Resource Identifier, allowing Unicode characters) to a URI (Uniform Resource Identifier, ASCII-only).
The function doesn't add an additional layer of escaping; e.g., it doesn't escape `%3C` as `%253C`. Instead, it percent-escapes characters with an underlying UTF-8 encoding *besides*... | def iri_to_uri(iri):
"""
Converts an IRI (Internationalized Resource Identifier, allowing Unicode characters) to a URI (Uniform Resource Identifier, ASCII-only).
The function doesn't add an additional layer of escaping; e.g., it doesn't escape `%3C` as `%253C`. Instead, it percent-escapes characters with a... |
Returns TZ-aware time in seconds since the epoch (1970-01-01T00:00:00Z) | def time_seconds(**kwargs):
"""
Returns TZ-aware time in seconds since the epoch (1970-01-01T00:00:00Z)
"""
return time.time() + dt.timedelta(**kwargs).total_seconds() |
Ref: https://bugs.python.org/issue30075 | def windows_enable_vt_mode():
"""Ref: https://bugs.python.org/issue30075 """
if get_windows_version() < (10, 0, 10586):
return
import ctypes
import ctypes.wintypes
import msvcrt
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
dll = ctypes.WinDLL('kernel32', use_last_error=False)
h... |
Find the largest format dimensions in terms of video width and, for each thumbnail:
* Modify the URL: Match the width with the provided regex and replace with the former width
* Update dimensions
This function is useful with video services that scale the provided thumbnails on demand | def scale_thumbnails_to_max_format_width(formats, thumbnails, url_width_re):
"""
Find the largest format dimensions in terms of video width and, for each thumbnail:
* Modify the URL: Match the width with the provided regex and replace with the former width
* Update dimensions
This function is usefu... |
Parse value of "Range" or "Content-Range" HTTP header into tuple. | def parse_http_range(range):
""" Parse value of "Range" or "Content-Range" HTTP header into tuple. """
if not range:
return None, None, None
crg = re.search(r'bytes[ =](\d+)-(\d+)?(?:/(\d+))?', range)
if not crg:
return None, None, None
return int(crg.group(1)), int_or_none(crg.group... |
Detect the text encoding used
@returns (encoding, bytes to skip) | def determine_file_encoding(data):
"""
Detect the text encoding used
@returns (encoding, bytes to skip)
"""
# BOM marks are given priority over declarations
for bom, enc in BOMS:
if data.startswith(bom):
return enc, len(bom)
# Strip off all null bytes to match even whe... |
Merge dicts of http headers case insensitively, prioritizing the latter ones | def merge_headers(*dicts):
"""Merge dicts of http headers case insensitively, prioritizing the latter ones"""
return {k.title(): v for k, v in itertools.chain.from_iterable(map(dict.items, dicts))} |
Cache a method | def cached_method(f):
"""Cache a method"""
signature = inspect.signature(f)
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
bound_args = signature.bind(self, *args, **kwargs)
bound_args.apply_defaults()
key = tuple(bound_args.arguments.values())[1:]
cache = vars... |
@param tbr: Total bitrate in kbps (1000 bits/sec)
@param duration: Duration in seconds
@returns Filesize in bytes | def filesize_from_tbr(tbr, duration):
"""
@param tbr: Total bitrate in kbps (1000 bits/sec)
@param duration: Duration in seconds
@returns Filesize in bytes
"""
if tbr is None or duration is None:
return None
return int(duration * tbr * (1000 / 8)) |
Make an extension for an AdjustedArrayWindow specialization. | def window_specialization(typename):
"""Make an extension for an AdjustedArrayWindow specialization."""
return Extension(
'zipline.lib._{name}window'.format(name=typename),
['zipline/lib/_{name}window.pyx'.format(name=typename)],
depends=['zipline/lib/_windowtemplate.pxi'],
) |
Read a requirements file, expressed as a path relative to Zipline root. | def read_requirements(path,
conda_format=False,
filter_names=None):
"""
Read a requirements file, expressed as a path relative to Zipline root.
"""
real_path = join(dirname(abspath(__file__)), path)
with open(real_path) as f:
reqs = _filter_require... |
Generate test cases for the type of asset finder specific by
asset_finder_type for test_lookup_generic. | def build_lookup_generic_cases():
"""
Generate test cases for the type of asset finder specific by
asset_finder_type for test_lookup_generic.
"""
unique_start = pd.Timestamp('2013-01-01', tz='UTC')
unique_end = pd.Timestamp('2014-01-01', tz='UTC')
dupe_old_start = pd.Timestamp('2013-01-01',... |
Rotate a list of elements.
Pulls N elements off the end of the list and appends them to the front.
>>> rotN(['a', 'b', 'c', 'd'], 2)
['c', 'd', 'a', 'b']
>>> rotN(['a', 'b', 'c', 'd'], 3)
['d', 'a', 'b', 'c'] | def rotN(l, N):
"""
Rotate a list of elements.
Pulls N elements off the end of the list and appends them to the front.
>>> rotN(['a', 'b', 'c', 'd'], 2)
['c', 'd', 'a', 'b']
>>> rotN(['a', 'b', 'c', 'd'], 3)
['d', 'a', 'b', 'c']
"""
assert len(l) >= N, "Can't rotate list by longer ... |
500 randomly selected days.
This is used to make sure our test coverage is unbiased towards any rules.
We use a random sample because testing on all the trading days took
around 180 seconds on my laptop, which is far too much for normal unit
testing.
We manually set the seed so that this will be deterministic.
Results... | def minutes_for_days(cal, ordered_days=False):
"""
500 randomly selected days.
This is used to make sure our test coverage is unbiased towards any rules.
We use a random sample because testing on all the trading days took
around 180 seconds on my laptop, which is far too much for normal unit
tes... |
Utility method to generate fake minute-level CSV data.
:param first_day: first trading day
:param last_day: last trading day
:param starting_open: first open value, raw value.
:param starting_volume: first volume value, raw value.
:param multipliers_list: ordered list of pd.Timestamp -> float, one per day
in th... | def generate_minute_test_data(first_day,
last_day,
starting_open,
starting_volume,
multipliers_list,
path):
"""
Utility method to generate fake minute-level CSV d... |
Extract all of the fields from the portfolio as a new dictionary.
| def portfolio_snapshot(p):
"""Extract all of the fields from the portfolio as a new dictionary.
"""
fields = (
'cash_flow',
'starting_cash',
'portfolio_value',
'pnl',
'returns',
'cash',
'positions',
'positions_value',
'positions_exposur... |
Decorator for providing dynamic default values for a method.
Usages:
@with_defaults(foo=lambda self: self.x + self.y)
def func(self, foo):
...
If a value is passed for `foo`, it will be used. Otherwise the function
supplied to `with_defaults` will be called with `self` as an argument. | def with_defaults(**default_funcs):
"""
Decorator for providing dynamic default values for a method.
Usages:
@with_defaults(foo=lambda self: self.x + self.y)
def func(self, foo):
...
If a value is passed for `foo`, it will be used. Otherwise the function
supplied to `with_defaults... |
Simple moving window generator over a 2D numpy array. | def moving_window(array, nrows):
"""
Simple moving window generator over a 2D numpy array.
"""
count = num_windows_of_length_M_on_buffers_of_length_N(nrows, len(array))
for i in range(count):
yield array[i:i + nrows] |
For a window of length M rolling over a buffer of length N,
there are (N - M) + 1 legal windows.
Example:
If my array has N=4 rows, and I want windows of length M=2, there are
3 legal windows: data[0:2], data[1:3], and data[2:4]. | def num_windows_of_length_M_on_buffers_of_length_N(M, N):
"""
For a window of length M rolling over a buffer of length N,
there are (N - M) + 1 legal windows.
Example:
If my array has N=4 rows, and I want windows of length M=2, there are
3 legal windows: data[0:2], data[1:3], and data[2:4].
... |
An iterator of all legal window lengths on a buffer of a given length.
Returns values from 1 to underlying_buffer_length. | def valid_window_lengths(underlying_buffer_length):
"""
An iterator of all legal window lengths on a buffer of a given length.
Returns values from 1 to underlying_buffer_length.
"""
return iter(range(1, underlying_buffer_length + 1)) |
Curried wrapper around array.astype for when you have the dtype before you
have the data. | def as_dtype(dtype, data):
"""
Curried wrapper around array.astype for when you have the dtype before you
have the data.
"""
return asarray(data).astype(dtype) |
Curried wrapper around LabelArray, that round-trips the input data through
`initial_dtype` first. | def as_labelarray(initial_dtype, missing_value, array):
"""
Curried wrapper around LabelArray, that round-trips the input data through
`initial_dtype` first.
"""
return LabelArray(
array.astype(initial_dtype),
missing_value=initial_dtype.type(missing_value),
) |
Generate expected moving windows on a buffer with adjustments.
We proceed by constructing, at each row, the view of the array we expect in
in all windows anchored on that row.
In general, if we have an adjustment to be applied once we process the row
at index N, should see that adjustment applied to the underlying bu... | def _gen_multiplicative_adjustment_cases(dtype):
"""
Generate expected moving windows on a buffer with adjustments.
We proceed by constructing, at each row, the view of the array we expect in
in all windows anchored on that row.
In general, if we have an adjustment to be applied once we process th... |
Generate test cases for overwrite adjustments.
The algorithm used here is the same as the one used above for
multiplicative adjustments. The only difference is the semantics of how
the adjustments are expected to modify the arrays.
This is parameterized on `make_input` and `make_expected_output` functions,
which tak... | def _gen_overwrite_adjustment_cases(dtype):
"""
Generate test cases for overwrite adjustments.
The algorithm used here is the same as the one used above for
multiplicative adjustments. The only difference is the semantics of how
the adjustments are expected to modify the arrays.
This is param... |
Generate test cases for overwrite adjustments.
The algorithm used here is the same as the one used above for
multiplicative adjustments. The only difference is the semantics of how
the adjustments are expected to modify the arrays.
This is parameterized on `make_input` and `make_expected_output` functions,
which tak... | def _gen_overwrite_1d_array_adjustment_case(dtype):
"""
Generate test cases for overwrite adjustments.
The algorithm used here is the same as the one used above for
multiplicative adjustments. The only difference is the semantics of how
the adjustments are expected to modify the arrays.
This ... |
Assert that a MultiIndex contains the product of `*levels`. | def assert_multi_index_is_product(testcase, index, *levels):
"""Assert that a MultiIndex contains the product of `*levels`."""
testcase.assertIsInstance(
index, MultiIndex, "%s is not a MultiIndex" % index
)
testcase.assertEqual(set(index), set(product(*levels))) |
Make an event with a null event_date for all sids.
Used to test that EventsLoaders filter out null events. | def make_null_event_date_events(all_sids, timestamp):
"""
Make an event with a null event_date for all sids.
Used to test that EventsLoaders filter out null events.
"""
return pd.DataFrame({
'sid': all_sids,
'timestamp': timestamp,
'event_date': pd.Timestamp('NaT'),
... |
Every event has at least three pieces of data associated with it:
1. sid : The ID of the asset associated with the event.
2. event_date : The date on which an event occurred.
3. timestamp : The date on which we learned about the event.
This can be before the occurence_date in the case of an
... | def make_events(add_nulls):
"""
Every event has at least three pieces of data associated with it:
1. sid : The ID of the asset associated with the event.
2. event_date : The date on which an event occurred.
3. timestamp : The date on which we learned about the event.
This can be ... |
Wrapper around scipy.stats.mstats.winsorize that handles NaNs correctly.
scipy's winsorize sorts NaNs to the end of the array when calculating
percentiles. | def scipy_winsorize_with_nan_handling(array, limits):
"""
Wrapper around scipy.stats.mstats.winsorize that handles NaNs correctly.
scipy's winsorize sorts NaNs to the end of the array when calculating
percentiles.
"""
# The basic idea of this function is to do the following:
# 1. Sort the i... |
Take a 2D array and return the 0-indexed sorted position of each element in
the array for each row.
Examples
--------
In [5]: data
Out[5]:
array([[-0.141, -1.103, -1.0171, 0.7812, 0.07 ],
[ 0.926, 0.235, -0.7698, 1.4552, 0.2061],
[ 1.579, 0.929, -0.557 , 0.7896, -1.6279],
[-1.362, -2.411, ... | def rowwise_rank(array, mask=None):
"""
Take a 2D array and return the 0-indexed sorted position of each element in
the array for each row.
Examples
--------
In [5]: data
Out[5]:
array([[-0.141, -1.103, -1.0171, 0.7812, 0.07 ],
[ 0.926, 0.235, -0.7698, 1.4552, 0.2061],
... |
Iterate over ``it``, two elements at a time.
``it`` must yield an even number of times.
Examples
--------
>>> list(two_at_a_time([1, 2, 3, 4]))
[(1, 2), (3, 4)] | def two_at_a_time(it):
"""Iterate over ``it``, two elements at a time.
``it`` must yield an even number of times.
Examples
--------
>>> list(two_at_a_time([1, 2, 3, 4]))
[(1, 2), (3, 4)]
"""
return toolz.partition(2, it, pad=None) |
Check if an asset was alive in the range from start to end.
Parameters
----------
asset : Asset
The asset to check
start : pd.Timestamp
Start of the interval.
end : pd.Timestamp
End of the interval.
include_asset_start_date : bool
Whether to include the start date of the asset when checking liveness.
... | def alive_in_range(asset, start, end, include_asset_start_date=False):
"""
Check if an asset was alive in the range from start to end.
Parameters
----------
asset : Asset
The asset to check
start : pd.Timestamp
Start of the interval.
end : pd.Timestamp
End of the int... |
Check whether a pair of datetime intervals overlap.
Parameters
----------
a : (pd.Timestamp, pd.Timestamp)
b : (pd.Timestamp, pd.Timestamp)
Returns
-------
have_overlap : bool
Bool indicating whether there there is a non-empty intersection between
the intervals. | def intervals_overlap(a, b):
"""
Check whether a pair of datetime intervals overlap.
Parameters
----------
a : (pd.Timestamp, pd.Timestamp)
b : (pd.Timestamp, pd.Timestamp)
Returns
-------
have_overlap : bool
Bool indicating whether there there is a non-empty intersection b... |
Simple rolling vwap implementation for testing | def rolling_vwap(df, length):
"Simple rolling vwap implementation for testing"
closes = df['close'].values
volumes = df['volume'].values
product = closes * volumes
out = full_like(closes, nan)
for upper_bound in range(length, len(closes) + 1):
bounds = slice(upper_bound - length, upper_b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.