content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def inside(resource1, resource2):
"""Is ``resource1`` 'inside' ``resource2``? Return ``True`` if so, else
``False``.
``resource1`` is 'inside' ``resource2`` if ``resource2`` is a
:term:`lineage` ancestor of ``resource1``. It is a lineage ancestor
if its parent (or one of its parent's parents, etc... | 906a05912bba8b299e42fdb3a3b4547a1b160bb4 | 17,011 |
def ask(question, no_input=False):
"""Display a Y/n question prompt, and return a boolean"""
if no_input:
return True
else:
input_ = input('%s [Y/n] ' % question)
input_ = input_.strip().lower()
if input_ in ('y', 'yes', ''):
return True
if input_ in ('n',... | b7eed52f3fa3eb65ed99d2076cce6520489269a1 | 17,013 |
def electrical_mobility_from_D(D, charge, T, constants=None, units=None):
"""
Calculates the electrical mobility through Einstein-Smoluchowski relation.
Parameters
----------
D: float with unit
Diffusion coefficient
charge: integer
charge of the species
T: float with unit
... | ec6d60ead515baf0a2faad59661f94067a7f3f7f | 17,015 |
def get_index_by_node_id(data):
""" Indexes a Dynalist data object by node for easy navigation. """
index = {}
for node in data["nodes"]:
index[node["id"]] = node
return index | 2a630c7468258625c9a3193e6b9906ad23293375 | 17,016 |
import yaml
def dump(data):
"""
Dump a YAML file.
"""
return yaml.dump(data) | 37845ceb70fa0fddcbf6a2fbbec51212bc70c897 | 17,017 |
def subset_on_taxonomy(dataframe, taxa_level, name):
"""
Return only rows of the datframe where the value in column taxa_level
matches the specified name.
:param dataframe: Pandas DataFrame with columns like 'Kingdom',
'Phylum', 'Class', ...
:param taxa_level: a taxagenetic label such as "Genus... | a1d72a96b277791d677e2bf81073ed7f4daa423f | 17,021 |
from typing import Optional
from typing import Union
from datetime import datetime
def fix_time_retrieved(s: str) -> Optional[Union[str, datetime]]:
"""
Fixes timestamps of the format: 15-Jul-2021 (22:29:25.643316)
"""
if not s or s == "None":
return s
return datetime.strptime(s, "%d-%b-%Y... | 6d6a163490bbfe312c4ca1a4e2508ba1f71f096d | 17,027 |
def effective_stiffness_from_base_shear(v_base, disp):
"""
Calculates the effective stiffness based on the base shear and displacement.
Typically used in displacement based assessment
:return:
"""
return v_base / disp | a6b48e4dc970c19d0cab3d3c798633512ca62d9a | 17,028 |
def expand_box(box, img_shape, scale=None, padding=None):
"""Expand roi box
Parameters
----------
box : list
[x, y, w, h] order.
img_shape : list
[width, height]
scale : float, optional
Expand roi by scale, by default None
padding : int, optional
Expand roi b... | 3fd9c97b8baa70a89b898d3e9d14e8c930d0045e | 17,029 |
def parse_by_prefix(input_string, prefix, end_char=[" "]):
"""searches through input_string until it finds the prefix. Returns
everything in the string between prefix and the next instance of
end_char"""
start = input_string.find(prefix) + len(prefix)
end = start
while input_string[end] not in... | 8cc80c9c359ae155ed4f8f197c1e9bd604cebf1d | 17,030 |
def FindPosition(point, points):
"""Determines the position of point in the vector points"""
if point < points[0]:
return -1
for i in range(len(points) - 1):
if point < points[i + 1]:
return i
return len(points) | 11ccabcade65053ccfa6751813d90a0eeaccc339 | 17,040 |
def check_digit10(firstninedigits):
"""Check sum ISBN-10."""
# minimum checks
if len(firstninedigits) != 9:
return None
try:
int(firstninedigits)
except Exception: # pragma: no cover
return None
# checksum
val = sum(
(i + 2) * int(x) for i, x in enumerate(rev... | 33d8da015a471e5e9f29eb4c9b2b0173979d8130 | 17,044 |
def _load_captions(captions_file):
"""Loads flickr8k captions.
Args:
captions_file: txt file containing caption annotations in
'<image file name>#<0-4> <caption>' format
Returns:
A dict of image filename to captions.
"""
f_captions = open(captions_file, 'rb')
captions = f_captions.read().deco... | 89a00a5befe1162eda3918b7b6d63046fccd4c70 | 17,046 |
from typing import List
def text_to_bits(
text: str,
encoding: str = "utf-8",
errors: str = "surrogatepass",
) -> List[int]:
"""
Takes a string and returns it's binary representation.
Parameters
----------
text: str
Any string.
Returns
-------
A list of 0s and 1s.... | cc9ab6497ab3b797625016176b74a6660ed59a80 | 17,047 |
def get_the_written_file_list(writefile_cursor):
"""Return the written files (W)."""
written_files_query = '''
SELECT process, name, mode
FROM opened_files
WHERE mode == 2
'''
writefile_cursor.execute(written_files_query)
return writefile_cursor.fetchall() | 8abe57fd88d569d5cf48b13dfbcfc142fa6c1504 | 17,049 |
def final_nonzero(L):
"""
Return the index of the last non-zero value in the list.
"""
for index, val in reversed(list(enumerate(L))):
if val:
return(index)
return(0) | 1064987732146a9f6c12a2cab1dc84d2657fa321 | 17,052 |
def pattern_count(text: str, pattern: str) -> int:
"""Count the number of occurences of a pattern within text
Arguments:
text {str} -- text to count pattern in
pattern {str} -- pattern to be counted within text
Returns:
int -- The number of occurences of pattern in the test
... | e6fcd2f0645141a3ddf211facb49058deb6dc1fd | 17,055 |
def _Divide(x, y):
"""Divides with float division, or returns infinity if denominator is 0."""
if y == 0:
return float('inf')
return float(x) / y | dee5ef0c4160c45ee9c8ee6aee651d60c3e70252 | 17,067 |
def get_results(m):
"""
Extract model results as dict
Parameters
----------
m : Pyomo model instance
Model instance containing solution (post-solve)
Returns
-------
results : dict
Dictionary containing model results
"""
results = {
"x": m.x.value,
... | 1dcb35bac7fe2379b096bb2fd838ed53a7ebaca4 | 17,068 |
def get_number_coluna(janela, chuva_height):
"""Determina o numero de linhas com gotas que cabem na tela."""
availble_space_y = (janela[1] - (3 * chuva_height))
number_coluna = int(availble_space_y / (2 * chuva_height))
return number_coluna | a41c2ae23da33149c88a507cf900b9f8e2772622 | 17,074 |
def _readSatCatLine(line):
"""Returns the name, international designator (id), nad NORAD catalog number
(catNum) from a line in the satellite catalog.
"""
name = line[23:47].strip()
id = line[0:11].strip()
catNum = line[13:18].strip()
return name, id, catNum | 7d30ab9836f30cb7c10285ad86ca70cad7965b9c | 17,082 |
def _argsort(it, **kwargs):
"""
Renvoie une version triée de l'itérable `it`, ainsi que les indices
correspondants au tri.
Paramètres :
------------
- it : itérable
- kwargs
Mots-clés et valeurs utilisables avec la fonction built-in `sorted`.
Résultats :
-----------
- i... | f36e0ac863c3861ba7f1e222ac3712c977364d98 | 17,090 |
def _create_postgres_url(db_user, db_password, db_name, db_host,
db_port=5432, db_ssl_mode=None,
db_root_cert=None):
"""Helper function to construct the URL connection string
Args:
db_user: (string): the username to connect to the Postgres
D... | f617f7f85545fcf2a1f60db8c9c43e0209c32c4f | 17,096 |
def to_case_fold(word: str):
"""
The casefold() method is an aggressive lower() method which
convert strings to casefolded strings for caseless matching.
The casefold() method is removes all case distinctions
present in a string. It is used for caseless matching
(i.e. ignores cases when comparin... | c917ab8661859ae29d8abecd9a7663b0b5112a63 | 17,099 |
import torch
def predict_raw(loader, model):
"""Compute the raw output of the neural network model for the given data.
Arguments
----------
loader : pyTorch DataLoader instance
An instance of DataLoader class that supplies the data.
model: subclass instance of pyTorch nn.Module
... | cb812c0792629c46d5774d9f1f4090369e047b78 | 17,100 |
def funql_template_fn(target):
"""Simply returns target since entities are already anonymized in targets."""
return target | a5f95bd6b7feabb4826fff826e6638cd242e04d6 | 17,102 |
import torch
def to_tensor(im, dims=3):
""" Converts a given ndarray image to torch tensor image.
Args:
im: ndarray image (height x width x channel x [sample]).
dims: dimension number of the given image. If dims = 3, the image should
be in (height x width x channel) format; while if dims = 4, the i... | d19a0c0104f4dc9401f70235cadb7266ffd01332 | 17,103 |
def _get_size_verifier(min_x, min_y, mode):
"""
Depending on what the user wants, we need to filter image sizes differently.
This function generates the filter according to the user's wishes.
:param min_x: Minimal x-coordinate length of image.
:param min_y: Minimal y-coordinate length of image.
... | 86919399a94caa60ff780ccf5959fe2d43d6d2eb | 17,104 |
import random
def weighted(objs, key='weight', generator=random.randint):
"""Perform a weighted select given a list of objects.
:param objs: a list of objects containing at least the field `key`
:type objs: [dict]
:param key: the field in each obj that corresponds to weight
:type key: str
:pa... | ea8b0ada198ae26a7ac54092c10a11daba3d18e0 | 17,112 |
def get_parameter_list_from_parameter_dict(pd):
"""Takes a dictionary which contains key value pairs for model parameters and converts it into a list of
parameters that can be used as an input to an optimizer.
:param pd: parameter dictionary
:return: list of parameters
"""
pl = []
for key i... | 38ab987fd2959c789f69a804f27e30bc86c7279b | 17,113 |
def all_accept_criteria(candidate_paraphrases, **kargs):
"""Always accept proposed words.
"""
return candidate_paraphrases, None | 745459e4fc432f666b2c763baafb69ea19a6181c | 17,114 |
import string
def camel_to_underscore(name):
""" convert a camel case string to snake case
"""
for char in string.ascii_uppercase:
name = name.replace(char, '_{0}'.format(char))
return name.lower() | db88bd3938073ec65e58344ba7228c75fef646a5 | 17,118 |
import inspect
def get_signature(obj):
"""
Get signature of module/class/routine
Returns:
A string signature
"""
name = obj.__name__
if inspect.isclass(obj):
if hasattr(obj, "__init__"):
signature = str(inspect.signature(obj.__init__))
return "class %s%... | 9da9d7e431783b89a5e65b4940b118cd5538799c | 17,119 |
def abs(x):
"""
Computes the absolute value of a complex-valued input tensor (x).
"""
assert x.size(-1) == 2
return (x ** 2).sum(dim=-1).sqrt() | 3b3a23873923597767c35eb4b5f6da1bb054705b | 17,121 |
def gcd_looping_with_divrem(m, n):
"""
Computes the greatest common divisor of two numbers by getting remainder from division in a
loop.
:param int m: First number.
:param int n: Second number.
:returns: GCD as a number.
"""
while n != 0:
m, n = n, m % n
return m | 5b50692baa396d0e311b10f2858a1278a9366d09 | 17,122 |
def _round_bits(n: int, radix_bits: int) -> int:
"""Get the number of `radix_bits`-sized digits required to store a `n`-bit value."""
return (n + radix_bits - 1) // radix_bits | 3e03385ee69f28b11e63885a80af48faa337697a | 17,123 |
import functools
def ignores(exc_type, returns, when=None):
"""Ignores exception thrown by decorated function.
When the specified exception is raised by the decorated function,
the value 'returns' is returned instead.
The exceptions to catch can further be limited by providing a predicate
which ... | 0c839c73218124fb988cea95fb5ee73abe7d5833 | 17,127 |
def build_hsts_header(config):
"""Returns HSTS Header value."""
value = 'max-age={0}'.format(config.max_age)
if config.include_subdomains:
value += '; includeSubDomains'
if config.preload:
value += '; preload'
return value | 9f94d87b1949f5c9e2f898466a8f5191f2327357 | 17,128 |
def argv_to_module_arg_lists(args):
"""Converts module ldflags from argv format to per-module lists.
Flags are passed to us in the following format:
['global flag', '--module', 'flag1', 'flag2', '--module', 'flag 3']
These should be returned as a list for the global flags and a list of
per-mod... | 847597d09e56af4221792a9a176bddfea334e622 | 17,132 |
import time
def get_template_s3_resource_path(prefix, template_name, include_timestamp=True):
"""
Constructs s3 resource path for provided template name
:param prefix: S3 base path (marts after url port and hostname)
:param template_name: File name minus '.template' suffix and any timestamp portion
... | 61f1ef829cbe83e1032dd5995cedf33a4809f787 | 17,140 |
import torch
def adj_to_seq(adj, device='cpu'):
"""
Convert a dense adjacency matrix into a sequence.
Parameters
----------
adj : torch.Tensor
The dense adjacency tensor.
device : str, optional
The device onto which to put the data. The default is 'cpu'.
Returns
-----... | 6b967962d5ba61a0ad45d5197ca23a7278fccca9 | 17,145 |
def makeUnique(list):
""" Removes duplicates from a list. """
u = []
for l in list:
if not l in u:
u.append(l)
return u | 02834bf5633c82f5f7428c03519ca68bee8916d4 | 17,151 |
def sample_labels(model, wkrs, imgs):
"""
Generate a full labeling by workers given worker and image parameters.
Input:
- `model`: model instance to use for sampling parameters and labels.
- `wkrs`: list of worker parameters.
- `imgs`: list of image parameters.
Output:
1. list ... | 1abd2d0d087f7ce452db7c899f753366b148e9e6 | 17,152 |
def default_state_progress_report(n_steps, found_states, all_states,
timestep=None):
"""
Default progress reporter for VisitAllStatesEnsemble.
Note that it is assumed that all states have been named.
Parameters
----------
n_steps : int
number of MD fra... | b0f740d18218dd9542704d03edcd4b6575a2c14e | 17,159 |
def childrenList(cursor,cd_tax):
"""
Retrieve all the children of a taxon in the database
Parameters:
----------
cursor: Psycopg2 cursor
cursor for the database connection
cd_tax: Int
idenfier of the taxon for which we search the children taxa
Returns:
-------
all_c... | ca50ac590674d19321144f77b54ec57d8dd49bb4 | 17,162 |
def path_sum(root, target_sum):
"""
Given a binary tree and a sum, determine if the tree has
a root-to-leaf path such that adding up all the values along
the path equals the given sum.
"""
def is_leaf(node):
return node.left is None and node.right is None
def leaf_nodes(node, paren... | 0971227d42abb3a0cde1c9050dcca39731858679 | 17,164 |
def IsAioNode(tag):
"""Returns True iff tag represents an AIO node."""
return tag.startswith('aio_nodes.') | 6603f4bca75a463ca651b44615a11c3dd29ca487 | 17,168 |
def _parse_name(wot_identifier):
"""
Parse identifier of the forms: nick
nick@key
@key
:Return: nick, key. If a part is not given return an empty string for it.
>>> _parse_name("BabcomTest@123")
('BabcomTest', '123')
"""
... | 7a33f5247e345175bad92fc8bf040eddc8b65804 | 17,171 |
import re
def baselineNumber (Title):
"""Extract the processing baseline number from the given product title."""
return re.sub(r".+_N(\d{4})_.+", r"\1", Title) | c69d099c6173cb771d14d35f520f12f32079229f | 17,178 |
def _is_expecting_event(event_recv_list):
""" check for more event is expected in event list
Args:
event_recv_list: list of events
Returns:
result: True if more events are expected. False if not.
"""
for state in event_recv_list:
if state is False:
return True
... | befbe6a614ede6a7e5b59d3bda9c148c04ddadde | 17,182 |
def get_orders_dict(orders):
"""Form a dictionary of current order buys and sells
"""
list_orders = list(orders)
orders_dict = {}
orders_dict["sells"] = []
orders_dict["buys"] = []
for order in list_orders:
if order["side"] == "sell":
temp_price = round(float(order["price... | 9d126d759dd0b3da7c584f6d4163243d8b2cee43 | 17,183 |
import re
def get_offer_total_floors(html_parser, default_value=''):
"""
This method returns the maximal number of floors in the building.
:param html_parser: a BeautifulSoup object
:rtype: string
:return: The maximal floor number
"""
# searching dom for floor data
floor_raw_data = ht... | 170e75a04104f6fa1c544788c3d25324edd6b2e8 | 17,185 |
def rreplace(s, old, new, occurrence):
"""This function performs a search-and-replace on a string for a given
number of occurrences, but works from the back to the front.
:param s: string to manipulate
:param old: substring to search for
:param new: substring to replace with
:param occurrence: ... | eac6d5ffb8adb7940e6d3374eec130cafcc311e7 | 17,188 |
import requests
def get_all_episodes(cfg, series_id):
"""
Request all episodes within a series.
:param series_id: Unique identifier for series
:param cfg: Opencast configuration
:return: List of pair of eventIds and titles for episodes
"""
url = cfg['uri'] + "/api/events"
params = {"f... | 05ea8c7c36641ec5ed3dacebe9579a903ef01fe7 | 17,189 |
def default_sid_function(id, rsid):
"""
The default function for turning a Bgen (SNP) id and rsid into a
:attr:`pysnptools.distreader.DistReader.sid`.
If the Bgen rsid is '' or '0', the sid will be the (SNP) id.
Otherwise, the sid will be 'ID,RSID'
>>> default_sid_function('SNP1','rs102343')
... | f13b8adab14eb4476a151059938eddf9763d35ef | 17,190 |
def filter_BF_matches(matches: list, threshold=45) -> list:
"""
filter matches list and keep the best matches according to threshold
:param matches: a list of matches
:param threshold: threshold filtering
:return: matches_tmp: list of the best matches
"""
matches_tmp = []
sorted_matches ... | cce90d95f72b00148355552d0284b87cb16a40c1 | 17,192 |
def _convert_key_and_value(key, value):
"""Helper function to convert the provided key and value pair (from a dictionary) to a string.
Args:
key (str): The key in the dictionary.
value: The value for this key.
Returns:
str: The provided key value pair as a string.
"""
upda... | 075c0a9a7fe54c35c19296e3da827484b579d4c8 | 17,194 |
def max_value_bits(b):
"""
Get maximum (unsigned) value of a given integer bit size variable.
Parameters
----------
b : int
Number of bits (binary values) that are used to describe a putative variable.
Returns
-------
max_value : int
Maximum value that putative variable... | 24041ed8833da09c1ecc8dea1c12f63ca7b29ed0 | 17,195 |
def aligned_output(cols, indent, tab_size=4):
"""
Pretty printing function to output tabular data containing multiple
columns of text, left-aligned.
The first column is aligned at an indentation of "indent". Each
successive column is aligned on a suitable multiple of the "tab_size"
with spaces ... | 856391043607c4570f75b804917c10b4c4b42dc1 | 17,197 |
import re
def remove_blank(text):
"""
Args:
text (str): input text, contains blank between zh and en, zh and zh, en and en
Returns:
str: text without blank between zh and en, zh and zh, but keep en and en
Examples:
>>> text = "比如 Convolutional Neural Network,CNN 对应中 文是卷 积神 经网络... | 8b2093254aeefc26e72c507f0ec5f9e7400a41ea | 17,199 |
def last_of_list(the_list):
"""Return the last item of the provided list."""
if len(the_list) == 0:
return None
return the_list[len(the_list) - 1] | b88bf4c2f55497093888cebe703a14c1eb45199d | 17,202 |
import torch
def get_mean_std(loader):
"""Calculate mean and standard deviation of the dataset
Args:
loader (instance): torch instance for data loader
Returns:
tensor: mean and std of data
"""
channel_sum, channel_squared_sum, num_batches = 0,0,0
for img,_ in loader:
... | f5ee2a66edc5925aec3f78811c8ec6b8b943a1d3 | 17,203 |
from typing import Tuple
def get_sweep_time_ascii(
data: str, sweep_b: Tuple[int, int], time_b: Tuple[int, int]
) -> Tuple[int, int]:
"""Get sweep and time from a given ASCII string.
:param data: ASCII string
:param sweep_b: Boundaries of sweep
:param time_b: Boundaries of time
:return: swee... | f1848b70439314dff5d4a5e50ae0706f64315378 | 17,204 |
def bubbles_from_fixed_threshold(data, threshold=0, upper_lim=True):
"""
@ Giri at al. (2018a)
It is a method to identify regions of interest in noisy images.
The method uses a fixed threshold.
Parameters
----------
data : ndarray
The brightness temperature or ionization fraction cube.
threshold : floa... | 63977ae51eaa80a99b8325124e2d78b98f61b549 | 17,206 |
import re
def lower_case_all_tags(s):
"""
Change all the tags to lower-case
"""
return re.sub(r'(<.*?>)', lambda pat: pat.group(1).lower(), s,
flags=re.IGNORECASE) | 54b8dfdeb81e7cc21c930fd97e1787616a2a8939 | 17,209 |
def check(file1, file2):
"""Compare file1 and file2.
Ignore leading and trailing whitespaces of the file"""
with open(file1) as f1:
test_output = f1.read()
with open(file2) as f2:
ref_output = f2.read()
#p = subprocess.run(['diff', file1,file2], stdout=subprocess.PIPE)
#print(p.... | 3a10065ea681188fd4453bade2a04207aadf954a | 17,213 |
def trim_lcs(lcs : dict, cut_requirement : int = 0) -> dict :
"""
Remove epochs from a lightcurve that occur before object discovery, which
is defined as the first mjd with SNR >= 3.0.
Args:
lcs (dict): dictionary from a lightcurve file
cut_requirement (int, default=0): cut number to re... | 0071682cebb6cca56d93eb808d3d662d8e908787 | 17,214 |
def format_data_types(s):
"""
apply the correct data type to each value in the list created from a comma
separated sting "s"
x1: PDB ID (string)
x2: Macro molecule overlaps (int)
x3: Symmetry overlaps (int)
x4: All overlaps (int)
x5: Macro molecule overlaps per 1000 atoms (float)
x6: Symmetry overlap... | b027e98e3fcba4439c9073936cc9bcfc6df93b9d | 17,215 |
import math
def choose(n,k):
"""Standard Choose function.
:param n: The total sample size.
:type n: int
:param k: The number of elements you're choosing.
:type k: int
:return: n choose k
:rtype: int
"""
return (math.factorial(n)/(math.factorial(k)*math.factorial(n-k))) | faf862e502971ec55a34eb8ee2909b9790252a32 | 17,217 |
import re
def sanitize_target(target: str = "") -> str:
"""
Format target, allow only numeric character e.g.
- "012345678901234" => "012345678901234"
- "080-123-4567" => "0801234567"
- "1-1111-11111-11-1" => "1111111111111"
- "+66-89-123-4567" => "66891234567"
:param target:
:return:
... | ee490997a96a409967f7c8eebcb0e8daa28180b6 | 17,218 |
def create_label_dict(signal_labels, backgr_labels, discard_labels):
""" Create label dictionary, following the convetion:
* signal_labels are mapped to 1,2,3,...
* backgr_labels are mapped to 0
* discard_labels are mapped to -1
Args:
signal_labels: list, or... | 75ef46153cb1cd1c5bc2b56ea540e89f8c5fa4b5 | 17,220 |
from typing import Optional
import torch
def check_nans_(x, warn: Optional[str] = None, value: float = 0):
"""Mask out all non-finite values + warn if `warn is not None`"""
msk = torch.isfinite(x)
if warn is not None:
if ~(msk.all()):
print(f'WARNING: NaNs in {warn}')
x.masked_fill... | 5817f1488e7f187af6f68f97f3e943115a08e066 | 17,230 |
def get_element_text(element):
"""Builds the element text by iterating through child elements.
Parameters
----------
element: lxml.Element
The element for which to build text.
Returns
-------
text: str
The inner text of the element.
"""
text = ''.join(element.iterte... | 41409e83a23927a5af0818c5f3faace0ca117751 | 17,234 |
def _sum_counters(*counters_list):
"""Combine many maps from group to counter to amount."""
result = {}
for counters in counters_list:
for group, counter_to_amount in counters.items():
for counter, amount in counter_to_amount.items():
result.setdefault(group, {})
... | 0806ec754397d00a72ed985ef44081c9deb025c7 | 17,235 |
def solution(A, target): # O(N)
"""
Similar to src.arrays.two_sum, find all the combinations that can be added
up to reach a given target. Given that all values are unique.
>>> solution([1, 2, 3, 4, 5], 5)
2
>>> solution([3, 4, 5, 6], 9)
2
"""
... | adcdaa6825569a0d589b6abc01a514ce9d5f38f5 | 17,237 |
def exponential_ease_in_out(p):
"""Modeled after the piecewise exponential
y = (1/2)2^(10(2x - 1)) ; [0,0.5)
y = -(1/2)*2^(-10(2x - 1))) + 1 ; [0.5,1]
"""
if p == 0.0 or p == 1.0:
return p
if p < 0.5:
return 0.5 * pow(2, (20 * p) - 10)
else:
return -0.5 * pow... | 8d528b7628b735e1dd2e3e8b89d0ef398c696ed6 | 17,239 |
def xor_bytes(a, b):
"""Returns a byte array with the values from XOR'ing each byte of the input arrays."""
if len(a) != len(b):
raise ValueError("Both byte arrays must be the same length.")
return bytes([a[i] ^ b[i] for i in range(len(a))]) | 7cf107be20d916eeef6414118b8da35926997814 | 17,248 |
def _is_numeric(obj):
"""Return True if obj is a number, otherwise False.
>>> _is_numeric(2.5)
True
>>> _is_numeric('spam')
False
"""
try:
obj + 0
except TypeError:
return False
else:
return True | 8122eea635fd5ed9b2d0e42bda284631cc6cd07b | 17,249 |
def identity(x):
"""
恒等関数
Args:
x(np.array): 入力値
Returns: 入力値と同じ配列
"""
return x | 76a5d06675e9244b49acf74cf955a1dd9c6462c4 | 17,253 |
def GetGLGetTypeConversion(result_type, value_type, value):
"""Makes a gl compatible type conversion string for accessing state variables.
Useful when accessing state variables through glGetXXX calls.
glGet documetation (for example, the manual pages):
[...] If glGetIntegerv is called, [...] most floating-p... | aa2c283985fb824c603efe76b69479667c4fdd96 | 17,266 |
def list_to_csv(row):
"""
Takes a list and converts it to a comma separated string.
"""
format_string = ",".join(["{}"] * len(row))
return format_string.format(*row) | 104cc3e75d9c5d39fbdc7b7decd274a50b6e1b08 | 17,267 |
def add_link(s):
"""
if `s` is a url, then adds anchor tags for html representation in ipynb.
"""
if s.startswith('http'):
a = '<a href="{0}" target="_blank">'.format(s)
a += s
a += '</a>'
return a | 5a85592b9c976e2f20874849287e9eded552c98c | 17,271 |
def GenerateCompareBuildsLink(build_ids, siblings):
"""Return the URL to compare siblings for this build.
Args:
build_ids: list of CIDB id for the builds.
siblings: boolean indicating whether sibling builds should be included.
Returns:
The fully formed URL.
"""
params = ['buildIds=%s' % ','.join... | c309d71cff85becaa0d9cac26dd2a0481475a6ff | 17,272 |
def int_to_bool(value):
"""Turn integer into boolean."""
if value is None or value == 0:
return False
else:
return True | aa8f0f15be18f0c682ad1df4ed0f710880d5ecd5 | 17,278 |
def deep_merge(base, changes):
"""
Create a copy of ``base`` dict and recursively merges the ``changes`` dict.
Returns merged dict.
:type base: dict
:param base: The base dictionary for the merge
:type changes: dict
:param changes: The dictionary to merge into the base one
:return: The... | b74ac0e4213e8bfb0792f9e84053a96af3bb29f0 | 17,280 |
from typing import Optional
def admin_obj_url(obj: Optional[object], route: str = "", base_url: str = "") -> str:
"""
Returns admin URL to object. If object is standard model with default route name, the function
can deduct the route name as in "admin:<app>_<class-lowercase>_change".
:param obj: Objec... | 19601794a2455cf6f76231fd3a1c932fdbe09eae | 17,283 |
def contains_subsets(iter_of_sets):
"""
Checks whether a collection of sets contains any sets which are subsets of
another set in the collection
"""
for si in iter_of_sets:
for sj in iter_of_sets:
if si != sj and set(sj).issubset(si):
return True
return F... | 2b5055f0a31f5f00d975b49b08a4976c3c251fc5 | 17,285 |
import random
import string
def random_numeric_token(length):
"""Generates a random string of a given length, suitable for typing on a numeric keypad.
"""
return ''.join(random.choice(string.digits) for i in range(length)) | b63ac76ff32b86d01fb3b74772340cf1ebfcc321 | 17,295 |
def tensor_to_string_list(tensor):
"""Convert a tensor to a list of strings representing its value"""
scalar_list = tensor.squeeze().numpy().tolist()
return ["%.5f" % scalar for scalar in scalar_list] | 4c8844c5401850e6fb3364b4efbe745d7e5f0dad | 17,296 |
def to_brackets(field_name, format_spec):
"""Return PEP 3101 format string with field name and format specification.
"""
if format_spec:
format_spec = ':' + format_spec
return '{' + field_name + format_spec + '}'
return '{' + field_name + '}' | b699b664d1d6bee8c5009bc04513e67c3c15755b | 17,299 |
import re
def _get_valid_filter_terms(filter_terms, colnames):
"""Removes any filter terms referencing non-existent columns
Parameters
----------
filter_terms
A list of terms formatted so as to be used in the `where` argument of
:func:`pd.read_hdf`.
colnames :
A list of co... | a47dff6d9c34e6fc75a77ecc2f9828bb1667f7bb | 17,313 |
def dekker(
t: float,
x1: float,
y1: float,
x2: float,
y2: float,
x3: float,
y3: float,
x4: float,
y4: float,
) -> float:
"""
Estimates the root using Dekker's method.
Uses a secant line from (x2, y2) to either (x1, y1) or (x3, y3), depending on
which point is closes... | a50d57f6961dc11293975f03eb047a659598abcb | 17,316 |
def paren(iterable):
"""Return generator that parenthesizes elements."""
return ('(' + x + ')' for x in iterable) | c841c9145c35a0f600a39845484176a01b6492be | 17,323 |
def all_suffixes(li):
"""
Returns all suffixes of a list.
Args:
li: list from which to compute all suffixes
Returns:
list of all suffixes
"""
return [tuple(li[len(li) - i - 1:]) for i in range(len(li))] | ff1a2cf4fa620d50ecb06e124a4c2ca192d5d926 | 17,324 |
from typing import List
from typing import Dict
from typing import Union
import warnings
def _get_group_id(
recorded_group_identifier: List[str],
column_links: Dict[str, int],
single_line: List[str],
) -> Union[str, None]:
"""Returns the group_name or group_id if it was recorded or "0" if not.
Fav... | ea8e64d8377513d00205cb8259cb01f8711bf135 | 17,325 |
import warnings
def parse_sacct(sacct_str):
"""Convert output of ``sacct -p`` into a dictionary.
Parses the output of ``sacct -p`` and return a dictionary with the full (raw)
contents.
Args:
sacct_str (str): stdout of an invocation of ``sacct -p``
Returns:
dict: Keyed by Slurm J... | 2719e08dea13305c6e6fcef19bd4320072ad7647 | 17,326 |
import pytz
def format_date(dt):
"""
Format a datetime into Zulu time, with terminal "Z".
"""
return dt.astimezone(pytz.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ') | 524ee5803e5a5e26e7b9f8a1b6b680d7d739b3b1 | 17,328 |
import random
import string
def generate_random_string(len: int):
""" Creates a randomly generated string of uppercase letters
Args:
len (int): The desired length
Returns:
random_string (str)
"""
return ''.join(random.choices(string.ascii_uppercase, k=len)) | 5414ecb7a6e212379000e43fef07e4642c0e63a0 | 17,329 |
def modular_exponentiation(b, e, m):
"""produced modular exponentiation.
https://en.wikipedia.org/wiki/Modular_exponentiation
:param b: a base number.
:param e: an exponent.
:param m: a modulo.
:return: a reminder of b modulo m.
"""
x = 1
y = b
while e > 0:
if e % 2 == 0... | 389cab70e83bb2c2972c39583edbb2bca8efeacb | 17,330 |
def expected_bfw_size(n_size):
"""
Calculates the number of nodes generated by a single BFW for a single root node.
:param n_size: <list> The number of neighbours at each depth level
:return: The size of the list returned by a single BFW on a single root node
"""
total = []
for i, d in enume... | f275af1c152c4d4704c0be5ee43f3d0f8802900b | 17,332 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.