content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def base128Size(n):
""" Return the length in bytes of a UIntBase128-encoded sequence with value n.
>>> base128Size(0)
1
>>> base128Size(24567)
3
>>> base128Size(2**32-1)
5
"""
assert n >= 0
size = 1
while n >= 128:
size += 1
n >>= 7
return size | f6288ef3da20413f9949b47d61b8cb3bcd6f045c | 632,302 |
def reduced_chi_squared(yfit, y, sigma, degrees):
"""Given yfit, y, sigma, and (the number of) degrees of freedom,
return the reduced chi-squared value.
"""
error = yfit - y
return sum(error*error/sigma/sigma) / degrees | dc9f8a8cba69d7cca064c75dc2c7d88dccfe6b9c | 632,306 |
def find_no_text_pages(page_texts):
"""Find the pages in the page text list `page_texts` (created by make_page_corpus.py) that
contain no text
Returns: list of empty page numbers (page numbers start at zero)
"""
return [i for i, text in enumerate(page_texts) if not text] | 1ee3b751294d3512e0e727d723f96437b28a3b7a | 632,307 |
def remove_characters_without_dialog(screenplay):
"""
remove double 'character' instances from screenplay (happens when a character
does something, but doesn't actually speak, e.g. GEORGE: (gasps)
"""
redundant_indices_in_screenplay = []
for i in range(len(screenplay)-1):
if screenplay[i... | 831a2ee6e0d8ab1879e8b48dfe434c5d44b57649 | 632,308 |
from typing import List
import re
from textwrap import dedent
import textwrap
def wrap_paragraphs(text: str, ncols: int = 80) -> List[str]:
"""Wrap multiple paragraphs to fit a specified width.
This is equivalent to textwrap.wrap, but with support for multiple
paragraphs, as separated by empty lines.
... | 0c2953c86b0752b0e76eabfe479ad61980c76f4a | 632,310 |
from pathlib import Path
def match(path: Path) -> bool:
"""Return True if the path is a ZIP archive."""
return path.suffix.lower() == ".zip" and path.is_file() | 127c4ca25448db1cc732f22fe4e227f78b71c09e | 632,311 |
def _find_first_degree_branches(branch, branch_id):
"""Find all branches connected to a given branch.
:param pandas.DataFrame branch: branch DataFrame from Grid object.
:param int branch_id: index of branches to find neighbors of.
:return: (*set*) -- set of branch indexes (integers).
"""
from_b... | f86317bf9200ac8907661955ddfdf489457c87d8 | 632,313 |
import string
def fill_template_filename(template_string, substitution_dict):
"""
Replace variables in the template with the respective substitution dict entries.
Checks the `template_string` for variables (i.e., something like '${VAR_NAME}') that are listed as keys in `substitution_dict`. If such entrie... | 58afbd292d1de6aaa858fec1b0771dfcf8e095a7 | 632,321 |
def bulk_create_or_get(session, mapper, ids):
"""
For given model, return a list of entries with given primary keys.
Any entries that don't exist will be created.
"""
entries = list(
session.query(mapper)
.filter(mapper.id.in_(ids))
)
existing_ids = set([entry.id for entry i... | d067fcfe37305460ac0c730d17e1344fd9dddbd0 | 632,322 |
def delete_before(list, key):
"""
Return a list with the the item before the first occurrence of the
key (if any) deleted.
"""
if list == ():
return ()
else:
head1, tail1 = list
if tail1 == ():
return list
else:
head2, tail2 = tail1
... | cf3188c9955e5d8c04adc58ed65e9c5079d13d1a | 632,323 |
def get_stock_exchange(stock_code: str) -> str:
"""
Get the stock market according to the code rule.
:param stock_code: The stock code that need to check/
:return: Exchange. SSE - Shanghai, SZSE - Shenzhen. Empty string if not recognized.
"""
if len(stock_code) != 6:
return ''
if sto... | 71d0d388907e77f63f238903e98a2da0bca269cd | 632,324 |
def convert_gold_to_str_set(test_instance):
""" Helper method to convert the gold labels into readable text strings """
return {test_instance[0][x[0]:x[1]] + '_' + x[2] for x in test_instance[1]['entities']} | bee84d584c95a05f1c6515d63d7e73799e3b320b | 632,330 |
def charToString(charArray):
""" Takes an array of chars and returns the corresponding string."""
result = ""
for i in charArray:
result += i.decode("UTF-8")
return result | 63ac5dbe18d6e187bb44fcdb1eee86c48c8dbefb | 632,334 |
def snap_key_to_snapnum(snap_key):
"""
Given the name of a snapshot key, finds the associated snapshot number.
This is necessary because the 0th snapshot key may not be snapshot 000 and
there could be missing snapshots. This function searches backwards for a
group of digits that identify the snapsh... | 9b30f0efc978e50beaf50427eb4aac35dcb1f964 | 632,335 |
def ip_str_from4bytes(s: bytes) -> str: # b'\xc0\xa8\xfa\xe5' => 192.168.250.229
""" Convert bytestring to string representation of IPv4 address
Args:
s: source bytestring
Returns:
IPv4 address in traditional notation
"""
return str(s[0]) + "." + str(s[1]) + "." + str(s[2]) + "." ... | 0bac5deab1699eb01c2f93be9af6039eae68665f | 632,343 |
def suffix(num: int) -> str:
"""
Returns the suffix of an integer
"""
num = abs(num)
# Suffix only depends on last 2 digits
tens, units = divmod(num, 10)
tens %= 10
# suffix is always 'th' unless the tens digit
# is not 1 and the units is either 1, 2 or 3
if tens != 1:
... | f01226abef5b5e6ece3082e58d259b3f59a7ec6d | 632,346 |
def set_significant_digits(radar) -> None:
"""
Set _Least_significant_digit netcdf attribute.
"""
fieldnames = [
("VEL", 2),
("VEL_UNFOLDED", 2),
("DBZ", 2),
("DBZ_CORR", 2),
("DBZ_CORR_ORIG", 2),
("RHOHV_CORR", 2),
("ZDR", 2),
("ZDR_CORR_A... | 746fdc88fb1d3e09a59bec2e4e05e07defb70f2c | 632,349 |
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(fu... | 3abe07a3b24d82d391fcafbeba746470676f4312 | 632,352 |
def get_indexes_from_best_path(best_path):
"""Grab the reference and event index of the best path from the maximum_expected_accuracy_alignment function.
:param best_path: output from maximum_expected_accuracy_alignment
:return: list of events [[ref_pos, event_pos]...]
"""
path = []
while best_pa... | ffcfa377b48f02356b3ddad75b725baf22a096d8 | 632,354 |
def removesuffix(text, suffix):
"""Removes a suffix from a string.
If the string ends with the suffix string and the suffix is not empty,
returns string[:-len(suffix)]. Otherwise, returns the original string.
This function has been added in Python3.9 as the builtin
`str.removesuffix`, but is define... | d7c2f37b3012590c3d66911233abf6c4d7891205 | 632,357 |
def get_all_morph(df):
"""
Returns all morphemes and Part-of-Speech.
- input : dataframe
- output : string
"""
ret=''
for index, row in df.iterrows():
if row['type'] == 'Inflect' or row['type'] == 'Compound':
tag=row['expression']
ret+=tag.replace('+',' ... | c96516b7e6a07b2b3f45d0597f135aa11f7d12bf | 632,360 |
from typing import List
def filter_releases_by_channel(releases: List[dict], channel: str):
"""
Filter releases by channel (stable, beta, or alpha).
:param releases: a list of releases
:param channel: a software channel (
:return: a filtered list of releases
"""
if channel not in ["stabl... | 1d72ed0088e13b3dc50a53332413877ee9c75986 | 632,362 |
def parse_show_qos_cos_map(raw_result):
"""
Parse the show command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the 'show qos cos-map' command in a \
dictionary where each key is a code point in the cos map:
::
{
... | 3b02b3af0224aed923230680992eaabae85543cb | 632,367 |
def guess_band(filename):
""" Guess the passband using the image's filename"""
if '_B_' in filename:
passband = 'B'
elif '_V_' in filename:
passband = 'V'
elif '_R_' in filename:
passband = 'R'
elif '_I_' in filename:
passband = 'I'
else:
passband = 'clear... | 0b516d236cae8ea29d9043eaaa7a53a3d659b3a4 | 632,368 |
def indent(txt, indent_level):
"""
Indent a piece of text
>>> indent('foo', 2)
' foo'
"""
indent = " " * indent_level
return "\n".join(indent + x for x in txt.splitlines()) | b0b48e304cfafd65c8d8f7be6b056cf755951cdf | 632,369 |
def get_op_name(tensor_name):
"""
Given a tensor name, return the corresponding op name.
Args:
tensor_name: The name of a tensor.
Returns:
str: The op name
"""
return tensor_name.replace('^', '').split(':')[0] | 059f953771911370566505ff71e1a654148d2fc3 | 632,370 |
def is_number(number):
"""
Check whether this is a number (int, long, float, hex) .
Aruguments:
number: {string}, input string for number check.
"""
try:
float(number) # for int, long, float
except ValueError:
try:
int(number, 16) # for possible hex
... | 02c3d189eb1ac4f522601d55423dbd84af8ae79f | 632,379 |
from typing import Pattern
def parse_substring(full_string: str, rex: Pattern[str]) -> str | None:
"""Parse an url for substring matching the given regular expression.
Args:
url (str): String representation of the URL
rex (Pattern[str]): String represenation of a regular expression
Retur... | 9e1110badaf3d1d8d8527f4ff6db5de6be552641 | 632,384 |
def extensions(includes):
"""Formats a list of header files to include.
"""
return ["".join([i.split(".")[0], ".h"]) for i in includes if i.split(".")[0] != "types"] | 4a35a2383ca62d6f7d4cad25d2dc47e5ee179d41 | 632,385 |
def calc_delta_theta_int_inc_heating(bpr):
"""
Model of losses in the emission and control system for space heating and cooling.
Correction factor for the heating and cooling setpoints. Extracted from EN 15316-2
(see cea\databases\CH\Systems\emission_systems.xls for valid values for the heating and co... | 8a814d90cc27d53e19437cdc394ad3a472e8d023 | 632,389 |
import re
def matches(target, search_query):
"""
Uses a regex to match the header title with the desired title
:param target: The title to compare against
:param search_query: The field to compare with
:return: Boolean
"""
title_regex = re.compile(search_query, re.IGNORECASE)
res = tit... | 9fb66a03063c826108fd9f8c25526da63217327c | 632,392 |
def sievePath(fDB, path):
"""Recursively removes all files in path that are already in the fDB.
:param fDB: the information regarding files
:type fDB: FileDB
:param path: the path
:type path: str
:rtype: int
Returns the number of deleted files.
"""
return fDB.sievePath(path) | 48287383035e78a506f3460ebfd25f520c3612c0 | 632,394 |
def num2columnletters(num, power=0):
"""
Takes a column number and converts it to the equivalent excel column letters
:param int num: column number
:param int power: internal power multiplier for recursion
:return str: excel column letters
"""
if num <= 26:
return chr(num % 27 + 64)... | 39096fc9df99baba6ddbc1a7a48a7eb0068ddf44 | 632,398 |
def _APINameFromCollection(collection):
"""Get the API name from a collection name like 'api.parents.children'.
Args:
collection: str, The collection name.
Returns:
str: The API name.
"""
return collection.split('.')[0] | 484e57081f348ba39ce65ffbfe1c23c28519fe3f | 632,401 |
import random
def pick_from_distribution(input_map):
"""
Generates an item from a distribution map
:param input_map: The dictionary of items to their probabilities
:return: An item from the dictionary
"""
rand = random.random()
total = 0.0
for item, prob in input_map.iteritems():
... | 2ba62477bdc02c6f541d5f05100dee646d9b2f76 | 632,402 |
def get_line_by_offset(file_path: str, offset: int) -> str:
"""Get line by byte offset from the given file.
:param file_path: path to the file
:param offset: byte offset
:return: read line
"""
with open(file_path, "r") as data_file:
data_file.seek(offset)
line = data_file.readli... | aa6f2e50c1d493835d0be18391a37ea43011e915 | 632,409 |
def plot_raw(fig):
"""Set up the basic plotting paramaters"""
ax = fig.add_subplot(111, projection='3d')
ax.set_autoscale_on(False)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_xlim3d([0.0, 100.0])
ax.set_ylim3d([0.0, 100.0])
ax.set_zlim3d([0.0, 100.... | ed13f98ca0513b8067b6b3ebe93b988ad0b770fa | 632,410 |
import json
def get_end_stream_request(stream_id: str, request_id: int, api_version: str) -> str:
"""
Parameters
----------
stream_id:
ID of stream we want to stop
request_id:
ID of EndStreamRequest
Returns
-------
Serialized EndStreamRequest
"""
api_message = ... | 86265dd7cb7bef04eb9f1c5d876afa85bbac1a72 | 632,413 |
import time
def timer(f):
"""Calcule et affiche la durée d'exécution d'une fonction unaire"""
def wrapped(x):
start = time.time()
value = f(x)
end = time.time()
print(f"Durée {end - start} secs")
return value
return wrapped | 8c285774e0a0e85dffa6010487a122b5800f1afc | 632,414 |
def rendered_source_for_lang(page_pk, lang):
"""Create cache key for rendered page source based on current language"""
return 'powerpages:rendered_source_lang:{0}:{1}'.format(page_pk, lang) | 7ee0eb4e27c2f7274f6ae4ffeac9814fa3babf8c | 632,417 |
def render_comment(comment):
"""
Inclusion tag for rendering a comment.
Context::
Comment
Template::
questions/comment.html
"""
return dict(comment=comment) | 05310537d46ba55e9dd68f117fde3f73d85e968c | 632,418 |
def match(line, keyword):
""" If the first part of line (modulo blanks) matches keyword,
returns the end of that line. Otherwise checks if keyword is
anywhere in the line and returns that section, else returns None"""
line = line.lstrip()
length = len(keyword)
if line[:length] == keyword:
... | 8d629ebabe9c476670206c9758732b99d12d70a9 | 632,422 |
def convert_bool(column):
"""
Convert text into bool in given column.
- column: series to be converted
- return: converted column
"""
def _convert_bool(text):
if text in ["Y", "y", "1"]:
return True
else:
return False
if column.name in ["acti... | 92bd2a612bda3b1dfb9e5ea3f1ba7fda5fe1d334 | 632,425 |
def vec_dot_star(v1,v2):
""" Returns dot* (dot star) product of 2 2D vectors
the sign of the dot* shows if the v2 is to the left or to the right from the v1"""
dot_star = v1[0]*(v2[1])-v1[1]*v2[0]
return dot_star | 5204caee69af09edb0446a8432e201e293091ee8 | 632,426 |
def sum(x, y):
"""Sum x and y
>>> sum(10, 20)
30
>>> sum(-10, 20)
10
>>> sum('10', 20)
Traceback (most recent call last):
...
AssertionError: x needs to be in or float
"""
assert isinstance(x, (int, float)), 'x needs to be in or float'
assert isinstance(y, (int, float)), 'x needs to be in or float'
re... | 9b4691df287c1663aeff4bc001cc5291f1ceaf86 | 632,429 |
def SGD(lr=0.001, momentum=0):
"""SGD Optimiser.
:param lr: Learning rate
:type lr: float
:param momentum: Momentum
:type momentum: float
"""
return {
"optimiser": "SGD",
"opt_args": {
"lr": lr,
"momentum": momentum
}... | 612b06f1f8a6815d80ea4c425fd24922c067ed2b | 632,430 |
def get_event_log(isdsAppliance, check_mode=False, force=False):
"""
Get Event Log
"""
return isdsAppliance.invoke_get("Retrieving Event Log", "/events/system") | 63bf90481eb606da6ab0643d2fc60fc8c6d3b166 | 632,434 |
from typing import List
def generate_reason(total_points: int, message: str, recipients: List[str]) -> str:
"""
:param total_points: the amount of points that should be distributed
:param message: the message used when awarding points
:param recipients: a list of email addressed for users who should r... | 17185f706949bc92f04c66a65a734badb242d9dd | 632,438 |
def elapsed_time_format(seconds):
"""Returns human readable string for elapsed time"""
negative = seconds < 0
seconds = abs(int(seconds))
periods = [
('year', 60 * 60 * 24 * 365),
('month', 60 * 60 * 24 * 30),
('day', 60 * 60 * 24),
('hour', 60 * 60),
('minute', 6... | b70493048d540a99dc459d44ccdb5889ad4c2060 | 632,446 |
import hashlib
def get_bytes_hash(bytes, hash_function=hashlib.md5, chunk_size=4096):
"""
Return hash of byte stream.
Adapted from quantumSoup at https://stackoverflow.com/a/3431838.
"""
hash = hash_function()
for chunk in iter(lambda: bytes.read(chunk_size), b""):
hash.update(chunk)
... | 728f5f233d0f92f7e02003d5448e87b0e7fad0d0 | 632,455 |
import torch
from typing import Tuple
def tanh_warp_transform(
coords: torch.Tensor, matrix: torch.Tensor,
warp_factor: float, warped_shape: Tuple[int, int]):
""" Tanh-warp function.
Args:
coords (torch.Tensor): b x n x 2 (x, y). The original coordinates.
matrix: b x 3 x 3. A ... | fd72470444518c4191755fdb34f98e787abfd554 | 632,456 |
def _get_installed_version(name, installed_list):
"""Return installed version of package"""
try:
return [x for x in installed_list if x.name == name][0]
except IndexError:
return None | d3499eb511814907b6936c631a23c859041c45a7 | 632,460 |
def request(label, selection, blocklist=()):
"""
Request an input from the user against an allowlist and/or a blocklist.
Will continue to request user until an acceptable value is entered.
...
Parameters
---
label: string
a instruction for the user
... | f94b348b34ee00195072e35088102e45cba52b1e | 632,461 |
from typing import List
def parse_vector(text: str, count: int) -> List[float]:
"""Parse a space-delimited vector."""
parts = text.split()
if len(parts) != count:
raise ValueError(f'{text!r} is not a {count}-dimensional vector!')
return list(map(float, parts)) | c5b60afdb41768d17abacf375bc7e1e7893bedfb | 632,462 |
def screen(a, b, max_possible=255):
"""Blend two arrays together using the 'screen' mode.
Good for combining color-tinted fluorescence images with brightfield, for example.
Parameter 'max_possible' refers to the brightest-possible value in the array.
E.g. 1 for images scaled from 0 to 1, or 255 for ima... | bd971d4a26d5ad6690e1007f3a96ac171fb4bd29 | 632,463 |
def populated_attrs(lst):
"""Set with attr names which are not None in all objects in `lst`."""
attr_lists = [[name for name in obj.attr_lst \
if getattr(obj,name) is not None] for obj in lst]
return set.intersection(*(set(x) for x in attr_lists)) | 0003a6f0dc19aa85213709c853d5104a767ebe3e | 632,467 |
import random
def rand_byte(value=(0, 255)):
""" random byte """
if type(value) is int:
return value
elif type(value) is tuple:
return random.randint(value[0], value[1])
return random.randint(0, 255) | 2415a93f3b2ced4bcd027760350bc9c18b9dcd3a | 632,480 |
def _check_params(p, speciesDict,xb):
"""
Check to see if any of the parameters in p fall outside the range
given in speciesDict or on the boundaries
**Parameters**
:p: (3,) ndarray
array with form [[N1, b1, z1], ...]
:speciesDict: dictionary
dictionary with properties g... | cc9878194dda367f1d18984e4a77b7b3fabb4284 | 632,486 |
def to_bytes(object):
"""
Convert an object to bytes-like object.
:param object:<object> The object to be converted.
:return:<bytes> A bytes-like object.
"""
if type(object) is str:
return object.encode()
return bytes(object) | 78af9454a817961826a4fb132ae674b11216ceee | 632,490 |
def _path_is_under_fragments(path, path_fragments):
"""Helper for _ensure_asset_types().
Checks that the given path is under the given set of path fragments.
Args:
path: String of the path to check.
path_fragments: List of string to check for in the path (in order).
Returns:
True/Fa... | d267da755b733e815b8ac1bb65557f3b750ee828 | 632,496 |
def n_wise(iterable, n):
"""Use to separate an iterable by n-elements groups"""
a = iter(iterable)
return zip(*[a] * n) | b623d2da3ff5d1b6c1a01c362c0ed70137ed6c7f | 632,497 |
def _equalsIgnoreCase(a, b):
"""
Return true iff a and b have the same lowercase representation.
>>> _equalsIgnoreCase('dog', 'Dog')
True
>>> _equalsIgnoreCase('dOg', 'DOG')
True
"""
return a == b or a.lower() == b.lower() | 82aeac9c4bd7168f823d0b95541512b471893249 | 632,498 |
from operator import xor
def find_bezier_t_intersecting_with_closedpath(bezier_point_at_t, inside_closedpath,
t0=0., t1=1., tolerence=0.01):
""" Find a parameter t0 and t1 of the given bezier path which
bounds the intersecting points with a provided closed
pa... | 7a83732096e565281e8664fbdb02e7bf999ad9a1 | 632,507 |
import requests
def latest(session: requests.Session, package: str) -> str:
"""Find latest version of package on PyPI.
Args:
package: Python package name.
Returns:
Latest package version.
"""
endpoint = f"https://pypi.org/pypi/{package}/json"
with session.get(endpoint) as re... | bbf5301ac89d5a4d58d42dba98ee075d0bd894da | 632,510 |
def confirm(prompt, expected=('yes', 'y')):
""" Prompts the user to continue with the script
:param prompt: What to show the user
:param expected: Valid answers to continue
:return:
"""
response = input(prompt + f": ({'/'.join(expected)}) ")
if response.lower() not in expected:
print... | 229346036cd1dd026d52608df1ea77c64b66773c | 632,511 |
import base64
def load_bytes(storage: str, value: str) -> bytes:
"""
Given a storage, load bytes
Storage may be a 'raw', 'base64', 'base85', 'file'
Value is an encoded string or a path to local file
"""
if storage == 'raw':
return value.encode('utf-8')
if storage == 'base64':
... | b273df280db3e89677522fd9efa4c8c0f225b6a1 | 632,512 |
def handle_base_indices_arg(base_periods):
"""Converts arg to list if int, or raises error if not int or list."""
if not isinstance(base_periods, list):
if isinstance(base_periods, int):
return [base_periods]
else:
raise ValueError(
"base_periods must be i... | d0160143723f3bf1b8146837c88c20e1c9b1546c | 632,517 |
def to_hashable(obj):
"""
Convert nested data structure (e.g. with dicts and lists)
to something immutable and hashable (tuples, ...)
"""
if isinstance(obj, (int, float, str)):
return obj
elif isinstance(obj, (list, tuple)):
return tuple(to_hashable(x) for x in obj)
elif isin... | 6b1dd1bb517c90f9479574079f974ee14dc451a1 | 632,519 |
def parse_label_file(path_to_label_file):
"""Parses file with labels and converts into dict. For object detection."""
labels = open(path_to_label_file)
label_dict = {}
index = 0
for label in labels:
label_dict[str(label.strip())] = index
index = index + 1
return label_dict | 527339353d3c784378789eda47a3fb94c84597bc | 632,522 |
def customiseFor34120(process):
"""Ensure TrackerAdditionalParametersPerDetRcd ESProducer is run"""
process.load("Geometry.TrackerGeometryBuilder.TrackerAdditionalParametersPerDet_cfi")
return process | 812279d18922ad1b3130447697f1010ac85b035e | 632,523 |
import torch
def fake_image_batch(H: int, W: int, C: int) -> torch.Tensor:
"""Fake batch of images."""
return torch.rand(16, C, H, W) | 3fdba70af552a263d039008137329a1c5a031c9b | 632,525 |
def yes_or_no(question):
"""
Ask the user a question that can be answered with yes or no.
:question: str, The question
:returns: bool, True if the answer was yes, False otherwise
"""
answer = input("{} (y/n): ".format(question)).lower()
if answer == "y":
return True
return False | 1198ac7579f654e237c1f91882f0cb984816d8e8 | 632,529 |
from typing import Tuple
def _split_time_units_attr(units_attr: str) -> Tuple[str, str]:
"""Splits the time coordinates' units attr into units and reference date.
Parameters
----------
units_attr : str
The units attribute (e.g., "months since 1800-01-01").
Returns
-------
Tuple[s... | 95da70dadca4259cc3e536dc9802af40d1c5208f | 632,534 |
from typing import AsyncIterable
from typing import Set
async def contains_all(async_gen: AsyncIterable[str], keywords: Set[str]) -> bool:
"""
Check wether an ``AsyncIterable[str]`` contains all of the given keywords. The keywords
can be embedded in some larger string. Return ``True`` as soon as all keywo... | 77bea74eacd3f7f33d4ee5e52db2cc10d1e2dd27 | 632,536 |
import hashlib
def md5(filename):
"""Helper method to find the Md5 checksum of the file.
Args:
filename (str): Path to the file.
Returns:
str: Hexdigest of the file.
"""
try:
hash_md5 = hashlib.md5()
with open(filename, "rb") as in_file:
for chunk in... | b86d5e8a81e43c45a2a171b26d8d8914e031b95c | 632,538 |
def convert_list_of_link_ids_to_network_nodes(network, link_ids: list):
"""
Extracts nodes corresponding to link ids in the order of given link_ids list. Useful for extracting network routes.
:param network:
:param link_ids:
:return:
"""
paths = []
connected_path = []
for link_id in ... | 25f0c2a6a20a902627bca79fb6ed76b274ed50df | 632,542 |
from typing import Tuple
def _merge_points(
player: Tuple[int, ...], opponent: Tuple[int, ...]
) -> Tuple[int, ...]:
"""Merge player and opponent board positions and return the combined points."""
return tuple(
i + j for i, j in zip(player, tuple(map(lambda n: -n, opponent[::-1])))
) | dcc10f5763f3f8cec115992a5f96faab77d8c1d4 | 632,543 |
def median(values):
"""Returns the central (median) value of a list.
If the list has an even amount of numbers,
then the average of the two
central numbers shall be returned.
Args:
values (list)
Returns:
float: The central value"""
if len(values) == 0:
return None
... | d0ec6bbf2642fbd00623bc53d00992cb306f917e | 632,546 |
def norm_package_version(version):
"""Normalize a version by removing extra spaces and parentheses."""
if version:
version = ','.join(v.strip() for v in version.split(',')).strip()
if version.startswith('(') and version.endswith(')'):
version = version[1:-1]
version = ''.jo... | d6120f9500bb7be879929204938444341d3178e0 | 632,550 |
def batch_sum(x):
"""Sums a tensor long all non-batch dimensions"""
return x.sum(tuple(range(1, x.dim()))) | f62ae269a632b9b4ef95d8e9d0276e0fad16b203 | 632,551 |
import re
import json
def parse_json(filename):
""" Parse a JSON file
First remove comments and then use the json module package
Comments look like :
// ...
or
/*
...
*/
"""
# Regular expression for comments
comment_re = re.compil... | 68e159e33ae3c2001559e84e4bef4c10dbedfcdc | 632,552 |
def field_type(field):
"""
Retrieves the type of a given field.
:param DjangoField field: A reference to the given field.
:rtype: str
:returns: The type of the field.
"""
return field.get_internal_type() | b10b657f11a857224784f88e17f021333288a567 | 632,556 |
def base4Encode(n, d):
""" Convert decimal notation to quaternary notation
We will use division and modulus recursively
n = decimal number
d = number of digits for quaternary representation
>>> base4Encode(22, 4)
[0, 1, 1, 2]
"""
alphabet = [0, 1, 2, 3]
quat = []
base = len(alp... | 93dab051aeafeea0301cf6842f8108a9f92f6453 | 632,561 |
def normalize(df, data_params):
"""Apply data scales.
Applies data scaling factors to df using data_params.
Args:
df (pd.DataFrame): with columns 'ds', 'y', (and potentially more regressors)
data_params (OrderedDict): scaling values,as returned by init_data_params
with ShiftSca... | 3e84c8791317225e0225da744a32fe543d03b142 | 632,569 |
def get_phase_start_stop(data):
"""
Get start and stop for a phase or subphase from the input time series data where start is
indicated by a value of 1 and stop is indicated by a value of 0 in the time series data
:param data: the time series data list
:return: the indices in the data list for the s... | e27671bbff0b18e87f858bb304df33c6af94d0b4 | 632,570 |
import pickle
def read_pickle(filename):
"""Read object from pickle format.
Parameters
----------
filename : str
Input file.
Returns
-------
obj : object
Python object.
"""
with open(filename, "rb") as f:
return pickle.load(f) | 6852366add1352af3953279baf7c8d95085d6ea7 | 632,573 |
def kernel_file_name(ns):
"""Given kernel info namespace, return reasonable file name."""
assert hasattr(ns, 'length')
length = ns.length
if isinstance(length, (tuple, list)):
length = 'x'.join(str(x) for x in length)
postfix = ''
if ns.scheme == 'CS_KERNEL_STOCKHAM_BLOCK_CC':
... | 5f8f9a491c1ee84ccc1cacf58d1d557ea59a8239 | 632,574 |
import time
import random
import requests
def _get_page(url, s=None):
"""
Utility function to play nice when scraping.
This will also fetch a page according to a session or a simple get.
"""
if not url:
# What's a proper null requests object?
return None
# Play nice
time.s... | dd3899c7844c608128b34ab7e9ece03f7b6ad95d | 632,575 |
def only_first_4_patches(tensor, n_imgs=4):
"""
Batch truncation function
:param tensor: batch
:param n_imgs: number of patches to keep
:return: truncated batch
"""
return tensor[0:n_imgs] | b2ce39bda459392a7251f1ff3659be8064f6a68b | 632,578 |
def _add_dates_to_sections(schedule):
"""
Adds term start/end dates to sections that do not have them (ie non-PCE)
"""
for section in schedule.sections:
if section.start_date is None:
if section.summer_term == "B-term":
section.start_date = schedule.term.bterm_first_... | f167b9a28795fa14f9432cfe1a63f4ea770e049b | 632,582 |
def truncate_after(d, n):
"""Truncate first timestamp dictionary D after N entries."""
sorted_lst = sorted(d.items(), key=lambda a: a[1][0])
return dict(sorted_lst[:n]) | 8fb7695c72c9df481a5b72fda77ed76e283338d4 | 632,586 |
def round_off(value, digits=2):
"""
Rounding off the value
:param float value: Value to be rounded
:param digits: Digit to kept as after point
:return float: Rounded value
"""
return float(("{0:.%sf}" % digits).format(value)) | 5958e158aed07ab66923b215d93403a59f11b718 | 632,587 |
def hamming_distance(str_1: str, str_2: str) -> int:
"""Return the hamming distance between two strings of equal length
Arguments:
str_1 {str} -- first string
str_2 {str} -- second string
Returns:
int -- hamming distance
Example:
>>> hamming_distance("ATATACATACGCG... | a7fe6f340242c77084eb9aa72be656fdc965cf23 | 632,588 |
import base64
def DecodeWithKey(key, string):
"""
Decode with Key
Takes your encoded string and decodes it with another string(key)
string = "w5PDisOlw5fDlA=="
key = "key"
>> "Hello"
"""
dec = []
enc = base64.urlsafe_b64decode(string).decode()
for i in range(len(enc)):
... | 0b3ea70824ddf832b270d719d4d420f7a8a8fdeb | 632,589 |
import pyarrow
def deserialize(data):
"""
Deserialize bytes into an object using pyarrow
Args:
bytes: a bytes object containing serialized with pyarrow data.
Returns:
Returns a value deserialized from the bytes-like object.
"""
return pyarrow.deserialize(data) | 9b347cf5b7208934167e13d05c2ed16e48e8f926 | 632,590 |
def createTwoDimensionBoard(height=3, width=3):
"""
Create a array in 2 dimensions fill with ' '
"""
return [[' ' for i in range(width)] for j in range(height)] | 091a71244c89e8b918e0eeea5142511b589673d4 | 632,592 |
def apply(object, args=None, kwargs=None):
"""Call a callable object with positional arguments taken from the
tuple args, and keyword arguments taken from the optional dictionary
kwargs; return its results.
"""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
return ... | f80ff050e2d4ababf23d44bddb599e13bbc23353 | 632,595 |
def get_item_hrefs(result_collection):
"""
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of item hrefs.
'result_collection' a JSON object returned by a previous API
call.
Returns a list, which may be... | 0fd2921c1799571eb015cfdec94d27ed3c34e14b | 632,599 |
def Sign(number):
"""
Sign(number)
Return the mathematical sign of the given number.
"""
return number and (-1, 1)[number > 0] | 7a7c4dae06df05715c4d4dd0680b000bccb924d4 | 632,601 |
def get_img_url(img_src, url_base):
"""
Get an image url from the src attribute af an image, and the page base url
"""
if not img_src:
return None
if not "//" in img_src: ## it's not an absolute url
if img_src[0] == "/":
img_src = img_src[1:]
img_src = url_base + ... | 858222ab82e34615a6c57f175757b5708d7ded32 | 632,606 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.