content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def interpolate_zeros(x, f):
"""
For two float arrays of data, representing a 2d plot (x, f) in
order - determine all the locations of x at which f crosses zero
(using linear interpolation). Return as a list.
"""
assert len(x) == len(f)
xcross = []
for i in range(len(f) - 1):
x0... | 89f6da8616b21661d1fac8b6bbbc06d97ceea31d | 557,971 |
from torch import randperm
from torch._utils import _accumulate
def split_datasource(datasource, lengths):
"""
Split a datasource into non-overlapping new datasources of given lengths
"""
if sum(lengths) != len(datasource):
raise ValueError("Sum of input lengths does not equal the length of th... | 2bc5ab8cbc7677309545669ec136b70ae2e57fc9 | 120,962 |
def is_subclass(obj, superclass):
"""Safely check if obj is a subclass of superclass."""
try:
return issubclass(obj, superclass)
except Exception:
return False | 4812f0e245546446256d0d2e9a305167e87da08d | 649,515 |
def get_games(event_sets: list) -> list:
"""
gets games from a list of sets
"""
games = []
for event_set in event_sets:
set_id = event_set['id']
for game_number, game in enumerate(event_set['games']):
if game['selections'] is not None:
game['setId'] = set_... | 9ab6bc6a0f395496aad3e41ab4169ea0b9a0f467 | 472,870 |
from pathlib import Path
def pad_filename(filename):
"""
pyAudioAnalysis adds stuff like "131.700-132.850" and "14.200-26.500" to the output filenames
this doesn't sort properly because the numbers like 131 and 14 are not padded with zeros.
"""
time_range = Path(filename).stem.replace('2000-essent... | 2d2be8eb643c025bd2b691383190c6de33326d92 | 179,356 |
def argsort(seq):
"""
Same as NumPy's :func:`numpy.argsort` but for Python sequences.
:param seq: a sequence
:return: indices into `seq` that sort `seq`
"""
return sorted(range(len(seq)), key=seq.__getitem__) | f203643aa1dd78490a2cc9d817e7a9fa6b2c6542 | 550,289 |
def make_matrix(num_rows, num_cols, entry_fn):
"""构造一个第 [i, j] 个元素是 entry_fn(i, j) 的 num_rows * num_cols 矩阵"""
return [
[
entry_fn(i, j) # 根据 i 创建一个列表
for j in range(num_cols)
] # [entry_fn(i, 0), ... ]
for i in range(num_rows)
] | e76598f8b87a50b99da6214cd18f37479ef64724 | 686,033 |
import json
async def _stream_next_event(stream):
"""Read the stream for next event while ignoring ping."""
while True:
last_new_line = False
data = b""
while True:
dat = await stream.read(1)
if dat == b"\n" and last_new_line:
break
... | ef4b03788ca9b0943cb6f2f5ecea49f98f0f8d9b | 472,441 |
def divide(a, b):
"""
Divide two numbers
Parameters:
a (float): counter
b (float): denominator
Returns:
float: division of a and b
"""
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b | 1ad6d5f5b542e197140797c0cf1d80372547782c | 584,672 |
def expand_addrmask(addrmask):
"""Expands a masked memory address to a list of all the applicable memory
addresses it could refer to. That is, a string like "00X1010X" could stand
for the binary numbers 00010100, 00010101, 00110100, or 00110101, which
correspond to decimal values 20, 21, 52, or 53, resp... | 696f110de8066ae7da27d6d8dba06285c7bc44b7 | 56,902 |
def compute_fibonnaci(n: int):
"""
Compute the nth term in the fibonacci sequence.
"""
if n == 0:
return 0
if n == 1:
return 1
return compute_fibonnaci(n-2) + compute_fibonnaci(n-1) | 80011255abd2485bdc9e82651f63a274db7b319a | 452,925 |
from typing import OrderedDict
import math
def clean_anime_details(information_dict):
"""
Cleans raw extracted data
Parameters
----------
information_dict: dict
The dictionary holding extracted data
"""
# Creating final dictionary from dictionary passed since hard to account for ... | 596487db6c675aaa4a252e6cf0e2cb6a60f9f6b0 | 419,647 |
def _get_snapshot_id_and_previous_session_id(session_spec, data_store):
"""Retrieve the snapshot ID and previous session ID in a tuple.
Args:
session_spec: session_pb2.SessionSpec proto containing info about current
session to draw the previous session and snapshot from.
data_store: data_store.DataSt... | 85493e3fa6ab1cf24d289d6d70372fb79cd218b6 | 594,947 |
def _compare_across(collections, key):
"""Return whether all the collections return equal values when called with
`key`."""
if len(collections) < 2:
return True
c0 = key(collections[0])
return all(c0 == key(c) for c in collections[1:]) | 453335cea7303b5c16a52550af09eb64df1f0b2e | 95,849 |
def multivariate_regression_predict(X, w_opt):
"""Predict with multivariate regression.
Arguments:
X {DataFrame} -- Independent variables.
w_opt {ndarray} -- Parameter values.
Returns:
ndarray -- Predicted values.
"""
X = X.values
y_pred = X.dot(w_opt)
return y_pre... | 34a9d70dfc2a4a647184255413a792f5270004d0 | 649,986 |
def compute_direct_sort_map(lang):
""" Return a map from each sort s to a list of the objects that have s as their direct sort
(i.e. ignoring parent sorts). """
res = {s: [] for s in lang.sorts if not s.builtin}
_ = [res[o.sort].append(o) for o in lang.constants()]
return res | 6c3428842ddb7f414b5863b36a391f2ef9c27f56 | 229,702 |
def is_new_subscription(doc):
"""
Returns `True` if `Subscription` has never generated an invoice
"""
return len(doc.invoices) == 0 | b1359de9ff7233714354e7ce52348322c6d3f08f | 207,863 |
from typing import List
import random
def training_room_names(random_order: bool = True) -> List:
""" return training room names in (random) order """
names = ['Trainings']
if random_order:
random.shuffle(names)
return names | 57efe215ee1ae76e5e64271ee9f3c20913763f3e | 465,373 |
def check_month(month_number, month_list):
"""
Check if a month (as integer) is in a list of selected months (as strings).
Args:
month_number: The number of the month.
month_list: A list of months as defined by the configuration.
Returns:
Bool.
"""
month_map = {
... | 9ae09aa80536e37763efc7b6601c4c793e9afd3a | 266,570 |
def is_valid_variable_name(varname):
"""
Tests if a variable name is valid.
Variable names must:
- begin with an alphabetic character
Variable names can:
- contain arbitrarily many single quotes as their final characters
x or x' or x''' but not x''yz
- contain any se... | 11e5e4ae70cb801ba0da9847bb35363d48d61c4c | 530,715 |
def _get_indices_dataset_notexist(input_time_arrays):
"""
Build a list of [start,end] indices that match the input_time_arrays, starting at zero.
Parameters
----------
input_time_arrays
list of 1d xarray dataarrays or numpy arrays for the input time values
Returns
-------
list
... | f1a3f1946c972841eba01f2362a886b29d4250a1 | 82,387 |
from typing import Tuple
from pathlib import Path
def endswith(path, suffixes: Tuple[str, ...]) -> bool:
"""
Returns whether the path ends with one of the given suffixes.
If `path` is not actually a path, returns True. This is useful
for allowing interpreters to bypass inappropriate paths, but
alw... | 0feae633bede862ac839b95ebe0a9b3ffd16949d | 642,147 |
def group_by_with_aggregation(
df,
by,
agg_column_names,
aggregators = ('mean', 'std')
):
"""Group by with aggregation.
Args:
df: Dataframe to perform group by on.
by: Which column to group by.
agg_column_names: Which columns to aggregate over. Have to be columns
containing numeri... | cea86b5d7c9cbcbfaae9d26eb52e58ecb2e8eb47 | 563,064 |
from typing import Dict
from typing import Any
import pprint
def describe_item(data: Dict[str, Any], name: str) -> str:
"""
Function that takes in a data set (e.g. CREATURES, EQUIPMENT, etc.) and
the name of an item in that data set and returns detailed information about
that item in the form of a str... | 4df9e99f713effc00714342f54e2bd135b580675 | 20,777 |
def float_to_bin(num, length):
"""
Convert float number to binary systems
:param num: Number to change
:type num: float
:param length: The maximum length of the number in binary system
:type length: int
:return: Returns a number converted to the binary system
:rtype: string
"""
... | 0f6c0f404ff0abb8251bd5f9b9370ab639cbcaad | 436,566 |
def merge(left, right):
"""
再帰処理中で呼び出す、分割された配列を結合する関数
再帰処理中で呼び出すため、渡される配列はソート済み
:param left: 左側の配列
:param right: 右側の配列
:return: 結合された配列
"""
merged = []
l_i, r_i = 0, 0
# ソート済みの配列をマージするため、それぞれ左から見ていくだけで良い
while l_i < len(left) and r_i < len(right):
# ここで=をつけることで安定性を保っ... | 4c514ec29043b4fc0719d0fc110ef870fb7e9d4b | 216,019 |
def extract_crops(image, size, stride=1):
"""Extract crops of size size from image using stride. Careful! This function only works for a batch_size = 1.
Args:
image: torch tensor, dtype = torch.float32.
expected dimensions: C X W X H,
e.g. torch.Siz... | 01d65d79a26eb15c5c2144b1b72f3bbabb80bad7 | 193,590 |
def tmask_blocks(tmask, min_block=0, sample_time=1):
"""
Return a list containing the indices of each valid block of a temporal
mask.
Parameters
----------
tmask
The temporal mask, in which 1 denotes valid observations and 0
denotes invalid or missing observations.
min_block... | 70bcb706a3a2ac51c92e8248e9fccc65d0d298d0 | 555,700 |
def get_iou(bb1, bb2):
"""
Gets the Intersection Over Area, aka how much they cross over
Assumption 1: Each box is a dictionary with the following
{"x1":top left top corner x coord,"y1": top left top corner y coord,"x2": bottom right corner x coord,"y2":bottomr right corner y coord}
... | 36594d11635c33a153b210ee550b1ad170f30210 | 531,201 |
from typing import List
def comment_lines(lines: List[str]) -> List[str]:
"""
Adds a multi line comment to a List of source lines.
:param lines: The source lines to be commented.
:returns: The commented List of of source lines.
"""
lines[0] = f'"""{lines[0]}'
if not lines[-1].endswith("\... | dfa8425f810f40c5aea474a2543d88e9f151ee25 | 513,359 |
from typing import List
from typing import Counter
def _categorical_value_intersection(
all_chars: List
) -> bool:
"""
A method that finds if there are items that appear more than once in a list
:param all_chars: the list we want to check
:return: `True` if there is an intersection, `False` o... | 48f1caa737494314d41d0f074e69dc08cd7d47eb | 426,051 |
def project_list(d, ks):
"""Return a list of the values of `d` at `ks`."""
return [d[k] for k in ks] | 62b82429e4c8e18f3fb6b1f73de72b1163f460bf | 24,393 |
import hashlib
def getETag(data):
"""Gets the ETag for the specified data.
Args:
data: The data for which the ETag should be generated.
"""
md5 = hashlib.md5()
md5.update(data)
return md5.hexdigest()[-16:] | db7578c74551f5c507c3d7c0bcbf3cab2768ff1e | 625,474 |
def filter_terms(p, degree_limit):
"""
This function gets the n-variable polynomial p and the number degree_limit
and returns the polynomial which consists of terms of degree at most degree_limit
:param p: n-variable polynomial
:param degree_limit: boundary for degree
:return: n-variable polynom... | 0b50d00bd058464319325a003ea8878313d5315b | 109,824 |
import torch
def sig(x, a):
"""
Applies a sigmoid function on data in [0-1] range. Then rescales
the result so 0.5 will be mapped to itself.
"""
# Apply Sigmoid
y = 1. / (1 + torch.exp(-a * x)) - 0.5
# Re-scale
y05 = 1. / (1 + torch.exp(-torch.tensor(a * 0.5, dtype=torch.float32))) -... | 0d92c567963fccbfe086e6c3d91b8caa103038ee | 384,957 |
def rubygems_homepage_url(name, version=None):
"""
Return a Rubygems.org homepage URL given a ``name`` and optional
``version``, or None if ``name`` is empty.
For example:
>>> url = rubygems_homepage_url(name='mocha', version='1.7.0')
>>> assert url == 'https://rubygems.org/gems/mocha/versions/... | 424489bee6578c201ac84fa74aa09f5d1b5c7ef3 | 96,476 |
import random
def generate_password(length):
"""Generate a password of a desired length with numbers, symbols, upper
and lowercase letters"""
if length < 4:
raise ValueError('length must be 4 or greater')
lower_chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
... | 8fb47ef138f0cfc334edc9caf55cdc4cc3111559 | 612,096 |
def space_separated(value):
"""
Return a list of values from a `value` string using one or more whitespace
as list items delimiter. Empty values are NOT returned.
"""
if not value:
return []
return list(value.split()) | f24a2949cfec1ae41173834e61013a459aee0e77 | 532,002 |
def is_private(key):
"""
Returns whether or not an attribute is private.
A private attribute looks like: __private_attribute__.
:param key: The attribute key
:return: bool
"""
return key.startswith("__") and key.endswith("__") | 498e7522e95317dbb171961f0f5fe8350c29a69d | 709,345 |
import math
def lin_srgb(rgb):
"""
Convert an array of sRGB values in the range 0.0 - 1.0 to linear light (un-corrected) form.
https://en.wikipedia.org/wiki/SRGB
"""
result = []
for i in rgb:
# Mirror linear nature of algorithm on the negative axis
abs_i = abs(i)
if a... | b2698655f57c244db03d4980a89e58fa5290f1e9 | 469,948 |
from datetime import datetime
import requests
import zipfile
import io
def get_shares_file(date):
"""
Download the file with the number of shares and returns bytes
Args:
date: Timestamp
Returns: bytes
"""
file_date = datetime.strftime(date, "%y%m%d")
file_url = f'http://www.b3.com.... | f005d9ac2b8c31530f4c52d297b4982372023063 | 359,959 |
from typing import Any
from typing import Iterable
def is_iterable(obj: Any) -> bool:
"""check whether `x` is an iterable object but not string"""
return isinstance(obj, Iterable) and not isinstance(obj, str) | cfe091c3ab2a17703118f6db2e1f584a4ab3ebf5 | 223,131 |
def clan_url(clan_tag):
"""Return clan URL on CR-API."""
return 'http://cr-api.com/clan/{}'.format(clan_tag) | f2c05b8ecf71771e259874bd78d862356dc2b902 | 90,554 |
def broken_bond_keys(tra):
""" keys for bonds that are broken in the transformation
"""
_, _, brk_bnd_keys = tra
return brk_bnd_keys | f499a912e4b11bb4fd71e6bb1a9a8991e26f44bb | 684,363 |
def xyxy2xywh(bbox):
"""Convert ``xyxy`` style bounding boxes to ``xywh`` style for COCO
evaluation.
Args:
bbox (numpy.ndarray): The bounding boxes, shape (4, ), in
``xyxy`` order.
Returns:
list[float]: The converted bounding boxes, in ``xywh`` order.
"""
_bbox = bbo... | 1a14e0d608f8bac182e415634a456c83f54125f4 | 559,456 |
from typing import Optional
from datetime import datetime
def get_dttm(date_time: Optional[datetime] = None) -> str:
"""
Get DTTM from datetime or actual time.
Args:
date_time: The input datetime or None for use now()
Returns:
dttm - str
"""
return (date_time or datetime.now(... | a81f967cf0afa49069977562d336c562ac5d3f7a | 481,194 |
def convert_values_to_none(event, field_or_field_list, field_values=None):
""" Changes a field to None. If a field value is specified then only that value will be changed to None
:param event: A dictionary
:param field_or_field_list: A single field or list of fields to convert to None
:param field_val... | d809980ab66c986357e46d78f8e4c01b420781e1 | 423,736 |
def power_law(deg_sep, ALPHA=1.0):
"""
Applies a power law model.
WEIGHT = DEG_SEP^(-ALPHA)
ALPHA: Parameter to control power law decay rate.
"""
return (deg_sep + 1) ** (- ALPHA) | 92900eb12d87e6549f4ac2fb4fde85db5fcf1ab6 | 519,179 |
def swagger_escape(s): # pragma: no cover
"""
/ and ~ are special characters in JSON Pointers,
and need to be escaped when used literally (for example, in path names).
https://swagger.io/docs/specification/using-ref/#escape
"""
return s.replace('~', '~0').replace('/', '~1') | 8f6e7112a565a6840fd046446cff77e11ee8425a | 662,178 |
def open_r(filename):
"""Open a file for reading with encoding utf-8 in text mode."""
return open(filename, 'r', encoding='utf-8') | 08086625a9c05738a3536001a158eff3b0718ddf | 9,785 |
import signal
def convert_signal_name_to_signal(signal_name):
"""
>>> convert_signal_name_to_signal('-SIGUSR2')
<Signals.SIGUSR2: 12>
>>> convert_signal_name_to_signal('SIGUSR2')
<Signals.SIGUSR2: 12>
>>> convert_signal_name_to_signal('USR2')
<Signals.SIGUSR2: 12>
>>> convert_signal_na... | 8bef3693775b1e64cc13b5a753e2aa69fd87cc73 | 217,779 |
def add_new_user(network, user, games):
"""
Creates a new user profile and adds that user to the network, along with
any game preferences specified in games. Assumes that the user has no
connections to begin with.
Arguments:
network: the gamer network data structure.
user: a string containin... | 68cc614074e489a4db04e12c4facc8b7445c0bf4 | 289,242 |
def cookie_repr(c):
""" Return a pretty string-representation of a cookie. """
return f"[key]host=[/key][cyan3]{c['host_key']}[/cyan3] " +\
f"[key]name=[/key][cyan3]{c['name']}[/cyan3] " +\
f"[key]path=[/key][cyan3]{c['path']}[/cyan3]" | 26720d914481ec52c230be12602052ea61b736c0 | 73,195 |
def _transform_kwargs(kwargs):
"""
Replace underscores in the given dictionary's keys with dashes. Used to
convert keyword argument names (which cannot contain dashes) to HTML
attribute names, e.g. data-*.
"""
return {key.replace('_', '-'): kwargs[key] for key in kwargs.keys()} | 12446fe5824f898a4dd406c860b664a9c326d75a | 451,225 |
from typing import Union
def get_list_value(lst: Union[list, tuple], inds):
"""get value form index.
Args:
lst (Union[list, tuple]): target list.
inds (Any): value from index.
Returns:
list: result
"""
return [lst[i] for i in inds] | 9b57377011b792714aaa21b90016e04ef85f68d1 | 73,215 |
from typing import Reversible
from typing import Any
def last(it: Reversible[Any]) -> Any:
"""
Get end of iterable object
Args:
it: Reversible(Iterable)) object
Examples:
>>> fpsm.last([1, 2, 3])
3
>>> fpsm.last('hello world')
'd'
"""
return next(iter(... | 6af5359cc6fa1ee8e3bd30aa5e37cda0ba589359 | 508,837 |
def not_exonic(variant_class):
"""Check if SNV is exonic.
Args:
variant_class: the type of mutation
Returns:
True for not exonic, False otherwise.
"""
variant_classes = ["5'Flank", 'Intron', 'RNA', "3'Flank", "3'UTR", "5'UTR", 'IGR']
if variant_class in variant_classes:
... | 019fbd55b2fe34ab9954cfbf35429741addfb697 | 174,627 |
def strToFloatOrNone(str):
"""Returns float representation of str argument or None if empty string.
:param str: String to ne converted into float number
:return: Float representation of str or None.
>>> print strToFloatOrNone("36")
36.0
>>> print strToFloatOrNone("")
None
"""
if... | 44cfd02c9ab3263a48568ec51704146a1b4ae2e9 | 347,647 |
def _page_obj(json_object):
"""takes json input and returns a page object
Args:
json_object (dict): json data from api
Returns:
dict: json object for the 'pages' of an article
"""
query_object = json_object['query']
return(query_object['pages']) | b6fb7470ea394c2e230df2d6212e969cd75ea244 | 344,908 |
from typing import Dict
import binascii
import base64
import json
def _decode(encoded: bytes) -> Dict:
"""
Decode an dictionary (document) encoded as a base64-encoded string.
:param encoded: the base64-encoded string
:return: the dictionary (document) object
"""
dec_ascii: bytes = encoded
... | 3787955ff3a188ccef44540c16f89da136a2b12b | 506,426 |
def in_reduce(reduce_logic_func, sequence, inclusion_list) -> bool:
"""Using `reduce_logic_func` check if each element of `sequence` is in `inclusion_list`"""
return reduce_logic_func(elmn in inclusion_list for elmn in sequence) | 746afeddf9d847dfa2aed9bb487199ba46f6b656 | 380,862 |
def eval_basic_op(l: str, op: str, r: str) -> str:
"""
Evaluate a basic arithmetic operation
:param l: Left operand
:param op: Operator
:param r: Right operand
:return: Result or a string representing the operation if it cannot be calculated
"""
if l.isdecimal() and r.isdecimal():
... | 2b35ae9eeef624f709009ddcd63e79179d41d978 | 204,342 |
def getData(d):
"""Returns the data object used"""
return d | 3ce72ad88a4a56a6292d76789489d1bba004ad6a | 562,262 |
def mostly_tracked(df, track_ratios):
"""Number of objects tracked for at least 80 percent of lifespan."""
return track_ratios[track_ratios >= 0.8].count() | 65f0389505484de4d289b465d70e6f981d02d039 | 332,869 |
def determiner_to_num(tag):
"""Converts a/an to 1."""
if tag[1] != "DET": return False, None
if tag[0].lower() in ("a","an"): return True, ("1","NUM")
return False, None | 8f0acf76989d16204ce17f3f52dc4cd4a70794cb | 491,599 |
from dateutil import tz
import dateutil.parser
def UTC_time(ISO_datestring):
"""Converts local ISO datastring to UTC date string"""
from_zone = tz.gettz('Pacific/Auckland')
to_zone = tz.gettz('UTC')
ISO_date = dateutil.parser.parse(ISO_datestring)
UTC_date = ISO_date.astimezone(to_zone)
UTC_... | 6634fbc0b23ebb0ace5ea9d808e34cbfaf383e59 | 445,784 |
from typing import Union
from pathlib import Path
from typing import List
def get_list_of_directories(
directory_path: Union[str, Path], descending=False
) -> List[Path]:
"""Gets a list of directories in a directory.
Parameters
----------
directory_path : Union[str, Path]
The path to the ... | 137a60b5dd3b635d74d25208bf9cab383442aca6 | 466,783 |
def get_xarray_group(dataset, group):
"""Get pseudo group from xarray.Dataset
Args:
dataset: A xarray.Dataset object with pseudo groups.
group: The name of the group (can also be a subgroup).
Returns:
A xarray.Dataset with the pseudo group.
"""
if not group.endswith("/"):
... | 20d7caa004f97855f3f8932a9f5638eb007f8d63 | 546,090 |
def to_str(value, encoding):
"""Decode a :obj:`bytes` object into a str with UTF-8 encoding.
:param bytes value: The value to decode
:param str encoding: The encoding type to use
:rtype: str
"""
return value.decode(encoding) | cc18f8c0f8e64860f374444a5bd065952c1420be | 452,936 |
def gray_to_binary(n):
"""Convert Gray codeword to binary and return it"""
mask=n=int(n,2) # Convert to int
while mask != 0:
mask >>= 1
n ^= mask
return bin(n)[2:]
# bin(n) returns n's binary representation with a '0b' prefixed
# the slice operation is to remove the prefix | 7008f57aaddf744bd80d2d7ffd65e45216c73f7e | 154,713 |
def format_duration_ms(ms):
"""Format milliseconds (int) to a human-readable string."""
def _format(d):
d = str(d)
if len(d) == 1:
d = '0' + d
return d
s = int(ms / 1000)
if s < 60:
return '00:{}'.format(_format(s))
m, s = divmod(s, 60)
return '{}:{}... | 751f233cb720b5365b1282d14e6b72fdb260689c | 523,866 |
def _convert_timestamp(time):
"""Convert datetime.datetime to string in datetime64[s] format
:arg time: datetime.datetime object
:return datetime64: str in datetime64[s] format
"""
year, month, day, hour, minute, second = str(time.year), str(time.month), str(time.day), str(time.hour), str(time.minut... | f4d817d21fd01f3b2a4d88058eb30fc2cd1b664a | 179,541 |
import re
def has_symbol_usage(symbol: str, text: str) -> bool:
""" Determine whether a symbol occurs in a text. """
# star matches any non-whitespace character
symbol = symbol.replace('*', '\S*?')
# match any use of symbol as a stand-alone element
pattern = r'\b{0}\b'.format(symbol)
# we're... | 66608d25d2dce555d471f504922f3fc5ecbfa6f5 | 498,186 |
def get_start_urls(base_url, webserver_map_entry):
"""
Extract the start URLs from the current webserver map results if available
"""
start_urls = []
for _, pages_node in webserver_map_entry.items():
for path in pages_node:
# base_url[:-1] to strip trailing slash, b/c path has a... | c7dcc3c7a9285106f50578f72397c3c3d2555135 | 286,262 |
def get_title(section_div):
"""Return the fathead entry title.
Parameters
----------
section_div : bs4.BeautifulSoup
The BeautifulSoup object corresponding to the div with the "class"
attribute equal to "section" in the html doc file.
Returns
-------
title : Str
The... | fa090adc09ac446f272262a72798cd000c76aa51 | 378,225 |
def digraph_edge_hamming_dist(g1, g2):
"""Returns number of directed edge mismatches between digraphs g1 and g2."""
dist = 0
for e1 in g1.edges:
if e1 not in g2.edges:
dist += 1
return dist | bb33330dc5029964e36947e1b09583c8e17e5754 | 495,137 |
def count_by(x, n):
""" Return a sequence of numbers counting by `x` `n` times. """
return range(x, x * n + 1, x) | 6bca9902f78f454da6a33cb40054a87f9832830a | 139,415 |
import math
def calc_viz_lim(P):
"""
Eq. 4.4
Calculates the visibility limit of the satellite, which is dependent on
the satellite's altitude.
Parameters
------------
P : float
The projection parameter of the satellite
Returns
------------
ups : float
The visi... | 97fb81dee635c4efb853a99f922cbb68ac95adc2 | 405,230 |
def get_column_names(outcomes, races, genders, pctiles):
""" Generate column names for outcomes and factors selected"""
col_names = []
for outcome in outcomes:
for race in races:
for gender in genders:
for pctile in pctiles:
col_names.append(outcome + ... | 8c5450508a7946eed6fb6935ed57e6c213c249c0 | 177,784 |
def get_and_check_wine_arch_valid(wine_arch: str = '') -> str:
"""
check for valid winearch - if wine_arch is empty, default to win32
valid choices: win32, win64
>>> import unittest
>>> assert get_and_check_wine_arch_valid() == 'win32'
>>> assert get_and_check_wine_arch_valid('win32') == 'win32... | 6317c99f420a63c334ca0e353b815302876f8c35 | 434,155 |
import smtplib
def connect(smtp_server, smtp_port, email, password):
"""
Connect to the SMTP server to send emails.
:param smtp_server: Hostname or IP Address of the SMTP server
:param smtp_port: Port number of the SMTP server.
:param email: Valid email address for authentication.
:param pass... | 34ac16b58b86f0e99709e80829114c6753fbc1d3 | 671,913 |
import csv
def sj_out_to_jxs(sj_out):
"""Accepts STAR-generated SJ.out.tab file & returns list of its junctions.
Input: sj_out (str) string pointing to STAR output __SJ.out file containing
junction calls from a STAR alignment.
Returns a list of the file's unique junctions in 0-based closed coord... | 137b72d3b7b5fd2335ffa0ed4e6508d8dd271d0a | 412,792 |
import re
def remove_non_numeric (value):
"""
Remove non-numeric characters from value.
:param value: The value to be modified.
:return Numeric value.
"""
return re.sub("[^0-9]", "", value) | 4c84deeaee5759cb0029e4baf585d272667369ba | 621,038 |
def get_major_version(version):
"""
:param version: the version of edge
:return: the major version of edge
"""
return version.split('.')[0] | c17e1b23872a25b3ce40f475855a9d1fe4eef954 | 688,639 |
def _create_docker_command(*args, **kwargs):
"""
Returns a string with the ordered arguments args in order,
followed by the keyword arguments kwargs (in sorted order, for
consistency), separated by spaces.
For example,
``_create_docker_command('./myprogram', 5, 6, wibble=7, wobble=8)``
retu... | 46315ad7eb34c5a61bb2c3c740a5451841073205 | 444,935 |
def xor_string(string: str, xor_int_value=42):
"""Takes a given string and does an XOR operation on the converted ord() value of each character with the "xor_int_value", which by default is 42
Examples:
>>> string2encode = 'Now is better than never.'\n
>>> xor_string(string2encode)\n
'd... | 4e3dd51cd49a6f3df9491dd86d76e6fcecf6fc38 | 637,233 |
def word_count(text: str, word: str='') -> int:
"""
Count the number of occurences of ``word`` in a string.
If ``word`` is not set, count all words.
"""
if word:
count = 0
for text_word in text.split():
if text_word == word:
count += 1
return coun... | f73ecbad4c81d9f5108c9a82756bd4caf5306a9a | 93,940 |
def create_field_matching_dict(airtable_records, value_field, key_field = None, swap_pairs = False):
"""Uses airtable_download() output to create a dictionary that matches field values from
the same record together. Useful for keeping track of relational data.
If second_field is `None`, then the dictio... | df5fbf24edb7047fc569b10a73eec47fb1234fcd | 687,184 |
def square_area(side):
"""Returns the area of a square"""
side = float(side)
if (side < 0.0):
raise ValueError('Negative numbers are not allowed')
return side**2.0 | a68c76dbdbe2918805c4788783e20c8ccf82ea6f | 296,025 |
import re
def string_to_list(s):
"""Return a list of strings from s where items are separated by any of , ; |"""
try:
return [text for text in re.split(r'\s*[,;\|]\s*', s) if text]
except TypeError:
if type(s) == list:
return s
raise | 4e679bfaf0d51120a2194a4db173d34a9eaf47d0 | 30,834 |
def unzip(index, list):
""" Returns the item at the given index from inside each tuple in the list.
"""
return [item[index] for item in list] | 887023728b3a9ddebd7b5667e6eb9a46e4537389 | 417,211 |
def get_unique_sublist(inlist):
"""return a copy of inlist, but where elements are unique"""
newlist = []
for val in inlist:
if not val in newlist: newlist.append(val)
return newlist | bc45dda0fd87d0c1b72f05db4fe72e3b312fe40c | 638,160 |
from pathlib import Path
def get_page_number(filename):
"""Parses a page number from a filename.
Presumes that:
The page number is preceded by an underscore
The page number is immediately followed by either by `_m`, `_me` or `_se`,
or the file extension.
Args:
file (str):... | 683ae951b0f8c0c397ec53ae8a33e014d61bd84f | 262,655 |
def IsRegionalHealthCheckRef(health_check_ref):
"""Returns True if the health check reference is regional."""
return health_check_ref.Collection() == 'compute.regionHealthChecks' | 4dea9aeaac365505555f3da0297920a1a57cec98 | 534,787 |
def element_wise_product(X, Y):
"""Return vector as an element-wise product of vectors X and Y"""
assert len(X) == len(Y)
return [x * y for x, y in zip(X, Y)] | e01ec3720ac6b2fa06cca1186cf1a5a4d8703d38 | 30,480 |
import torch
def flatten_grads(model):
"""
Flattens the gradients of a model (after `.backward()` call) as a single, large vector.
:param model: PyTorch model.
:return: 1D torch Tensor
"""
all_grads = []
for name, param in model.named_parameters():
all_grads.append(param.grad.view(... | c23dc028f56a245ea9f7cfb5c0468eaabd23063f | 486,961 |
import base64
def readDataOrPath(dataStr):
"""
Reads in either base64 data or a path.
"""
if dataStr.startswith('base64:'):
dataPath = None
dataContents = base64.b64decode(dataStr[7:])
else:
dataPath = dataStr
with open(dataStr, 'rb') as stream:
dataContents = stream.read()
return dataPath, dataConte... | 0b18eaa4affdb409455e7575a6938963df1f1db1 | 43,344 |
def get_adjusted_aspect(ax, aspect_ratio):
"""Adjust the aspect ratio
Parameters
----------
ax : :obj:`~matplotlib.axes.Axes`
A :obj:`~matplotlib.axes.Axes` instance
aspect_ratio : float
The desired aspect ratio for :obj:`~matplotlib.axes.Axes`
Returns
-------
float
... | 8a28e08bf3bcfec03954278cb498f2d56e93d1d1 | 615,825 |
def cells_different(cell_a, cell_b, compare_outputs = True):
"""
Return true/false if two cells are the same
cell_a: (obj) JSON representation of first cell
cell_b: (obj) JSON representation of second cell
compare_outputs: (bool) whether to compare cell outputs, or just inputs
"""
# check ... | c720a346550ca47b8841f0f60f8c566339b5e4aa | 74,626 |
def get_overlap_region(s1,e1,s2,e2):
"""0-based system is used (like in Biopython):
| INPUT | RETURNS |
|-----------------------------|-----------------------------|
| | |
| s1=3 e1=14 ... | 3b71131ae68a30404a307d34351234a46b0eae5b | 210,187 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.