content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import string
def is_punctuation(term):
"""
Check whether a string consists of a single punctuation mark
Example:
>>> is_punctuation(".")
True
>>> is_punctuation("word")
False
"""
return len(term) == 1 and term in string.punctuation | 3689159c0773bb6db025d84373206524b6bed5e3 | 621,689 |
import string
import random
def generate_random_words(nb_words, nb_character_max, nb_character_min = 3):
"""
Generates 'nb_words' random words composed from 1 to 'nb_character_max' ASCII characters.
"""
words = []
for i in range(nb_words):
word = string.ascii_letters
word = ''.joi... | e7aa64e443079da1b216fc914f6aa15a16b5b6f1 | 621,690 |
def copy_func_data(source_func, dest_func):
"""
Copy all useful data that is not the __code__ from source to
destination and return destination.
"""
dest_func.__name__ = source_func.__name__
dest_func.__qualname__ = source_func.__qualname__
dest_func.__doc__ = source_func.__doc__
dest_fu... | a9cc82bd9259c62ca5b90518ade7ab13abd9c785 | 621,691 |
def not_found(request, response):
"""Basic controller to act as default for unmatched request paths."""
response.status_code = 404
response.write("We can't find %s\n" % request.path)
return response | 6821386c0ba02f73411be3420cfc162f4aca30d9 | 621,692 |
def FilenameMatchesExtension(filename, extensions):
"""Checks to see if a file name matches one of the given extensions.
Args:
filename: The full path to the file to check
extensions: A list of candidate extensions.
Returns:
True if the filename matches one of the extensions, otherwise False.
"""
... | aacba258cb3c96e26df94dc2a7c2b31fec49b210 | 621,696 |
def tonumpy_batch(imgs):
"""
Convert a batch of torch images to numpy image map
:param imgs: (B, C, H, W)
:return: (B, H, W, C)
"""
return imgs.permute(0, 2, 3, 1).cpu().detach().numpy() | d3d826480f4191b8688740b04cb39687c80edce1 | 621,697 |
import random
import string
def get_random_string(length=32, prefix_string=""):
"""This function returns a random alphanumeric string to use as a salt or password.
:param length: The length of the string (``32`` by default)
:type length: int
:param prefix_string: A string to which the salt should be ... | f59fd7530a1ab6a454f6555ceed3beaacc28d20e | 621,698 |
def convert_by_vocab_dict(vocab_dict, items):
"""
Converts a sequence of [tokens|ids] according to the vocab dict.
"""
output = []
for item in items:
if item in vocab_dict:
output.append(vocab_dict[item])
else:
output.append(vocab_dict["<unk>"])
return out... | 38001a3be3c4abeceb0fba5cb9488ab2f7e93ef3 | 621,701 |
def screen_np(a, b):
"""screen(A, B) 1 − (1 − A) * (1 − B)"""
return 255 - (255 - a) * (255 - b) | 7fbb63e78b9e4ba95682a64e443a2347df59d24a | 621,702 |
def read_labels(labels_path):
"""
def read_labels(labels_path)
function to read labels from names file
Args:
labels_path (str): names file path
Returns: dictionary of labels, id pairs.
"""
with open(labels_path, 'r') as names_file:
lines = names_file.read()
i = 0
... | b5e9c6c2b0fb429495b5b1e5383120b238b4903f | 621,704 |
def titlecase(name):
"""Title-case target `name` if it looks safe to do so."""
return name if name.startswith(('1', 'C/', 'DSS-')) else name.title() | 4ea191e3c983cf8ba1c9d02abd7466d40bf8cab2 | 621,705 |
import torch
def label_to_onehot(labels, num_classes=10):
""" Converts label into a vector.
Args:
labels (int): Class label to convert to tensor.
num_classes (int): Number of classes for the model.
Returns:
(torch.tensor): Torch tensor with 0's everywhere except for 1 in
... | e6cfd53cf460970dcc85254a175359a14dbf9bed | 621,709 |
def titlesplit(src='', linelen=24):
"""Split a string on word boundaries to try and fit into 3 fixed lines."""
ret = ['', '', '']
words = src.split()
wlen = len(words)
if wlen > 0:
line = 0
ret[line] = words.pop(0)
for word in words:
pos = len(ret[line])
... | e87c258430ec4bfd958fa11a95fbbf5fa33702d9 | 621,710 |
def calc_bn_sparsity(L, q, K):
"""Calculates sparsity of Block Beighborhood scheme"""
sparsity = (L/K)*(q**K - 1) +1
return sparsity | d5d0623305bd182cd2f5fa97f63addaf163c110b | 621,722 |
from typing import Union
def object_to_qualified_name(value, fail=False, default_module_name='builtins') -> Union[str, None]:
"""
Get the fully qualified name of a Python object.
It is true that ``qualified_name_to_object(object_to_qualified_name(obj)) is obj``.
>>> from unittest import TestCase
... | e2399e4abb848649c66b2f11c7f77c11a82d9f81 | 621,727 |
import re
def shorten_url(url):
"""
Return a URL which is shorter but still useful, for
being displayed in logs
>>> shorten_url("https://www.civicboom.com/i/like/bacon")
'/i/like/bacon'
doesn't affect urls that are already short:
>>> shorten_url("/waffo/waffo")
'/waffo/waffo'
a... | cb373836dc09e664ceedc9f710b5e13ea22c8091 | 621,732 |
def diffs_stats(pairs):
"""returns the avg and the maximum difference between the given pairs and
the count of cases where the first element is bigger than the second
"""
s = 0.0
m = 0.0
n = 0
for (old, new) in pairs:
d = new - old # not using abs here on purpose
s += d
... | 4d383fececda5ca293a2faad3dd1158068863d74 | 621,739 |
def get_square(tracks, position):
"""Get square from tracks with position."""
row, col = position
return tracks[row][col] | df8c0aa03d89d28bc47a4054b2f0fa2880d2a39e | 621,740 |
def convert_to_float(value_string, parser_info_out=None, suc_return=True):
"""
Tries to make a float out of a string. If it can't it logs a warning
and returns True or False if convertion worked or not.
:param value_string: a string
:returns value: the new float or value_string: the string given
... | e55349aec92132dd292aed57fcc4fb7d23c93a46 | 621,741 |
def computeContinuousStatistics(df):
"""computeContinuousStatistics
Computes statistics for continuous features.
Input:
df -- DataFrame to use
Output:
{} -- a dictionary containing the statistics
"""
# returning the final statistics
return {
'count': len(df),
'miss_percentage': ((len(df)-df... | 62ce3175a31b103a303d109f63e28f8f4f91a043 | 621,745 |
def bezier( x1,y1, x2,y2, x3,y3, x4,y4, t ):
"""
Returns coordinates for t (=0.0...1.0) on curve segment.
x1,y1 and x4,y4: coordinates of on-curve nodes
x2,y2 and x3,y3: coordinates of BCPs
"""
x = x1*(1-t)**3 + x2*3*t*(1-t)**2 + x3*3*t**2*(1-t) + x4*t**3
y = y1*(1-t)**3 + y2*3*t*(1-t)**2 + y3*3*t**2*(1-t) +... | 24583504a832bc0b75b7ebb164838d80c0a84195 | 621,746 |
def getInputTimeSteps(algorithm, port=0, idx=0):
"""Get the timestep values for the algorithm's input
Args:
algorithm (vtkDataObject) : The data object (Proxy) on the pipeline
(pass `self` from algorithm subclasses)
port (int) : the input port
idx (int) : optional : the con... | 4003934a2b3b682b7ab7ad890d7ef9a9f1b8ad69 | 621,750 |
from typing import List
from pathlib import Path
def console_script_exists(site_packages_dirs: List[Path], console_script: str) -> bool:
"""Return true if the console script with provided name exists in one of the site-packages directories.
Console script is expected to be in the 'bin' directory of site pack... | 388b564012612695b538102860e4e9c6261efc72 | 621,756 |
import re
def seqs_from_stats(statfile):
"""Looks in the specified file for a line "SN sequences: {\d+}" and
returns the number. If the file is not found or the line is not found
returns None.
"""
try:
with open(statfile) as sfh:
for line in sfh:
mo = ... | 87665ae54acedbd6141e8aa8dd3d98775f014c58 | 621,759 |
def actionmessage(case, mass=False):
""" Default way to present action confirmation in chat """
output = f"**{case}** the user"
if mass:
output = f"**{case}** the IDs/Users"
return f"✅ Successfully {output}" | 932aac42aae38fe2f4ac6813b37e1549eb1d5baa | 621,761 |
import unicodedata
def unicode_to_ascii(sentence):
"""
Converts the unicode file to ascii
:param sentence: str/unicode
:return: str
"""
return ''.join(c for c in unicodedata.normalize('NFD', sentence)
if unicodedata.category(c) != 'Mn') | 012c405d9db27e29f92c6260e277b9905ee18201 | 621,768 |
def is_WORD(c):
"""
:param c character to check
:returns True if c is not whitespace
"""
return c and not c.isspace() | 365a95368bdc88d2e648eb8cf1c3bf9da1dc96ed | 621,772 |
def generate_playready_object(wrmheader):
"""
Generate a playready object from a wrmheader
"""
return ((len(wrmheader) + 10).to_bytes(4, "little") + # overall length
(1).to_bytes(2, "little") + # record count
(1).to_bytes(2, "little") + #... | 92a572392541a89f2fe8d6695aa217dd6f4d4616 | 621,773 |
def identity(X, y):
"""Identity operation.
Parameters
----------
X : torch.Tensor
EEG input example or batch.
y : torch.Tensor
EEG labels for the example or batch.
Returns
-------
torch.Tensor
Transformed inputs.
torch.Tensor
Transformed labels.
... | c0441302d7c85979fd73475d2d24f993a25490d3 | 621,779 |
import inspect
def getframeinfo(frame, context=1):
"""
Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line wi... | 974819633f126589461613a1e2b8ad2e5e25e5f8 | 621,781 |
from typing import OrderedDict
def _compute_offsets(inputs):
"""
Compute offsets of real inputs into the concatenated Gaussian dims.
This ignores all int inputs.
:param OrderedDict inputs: A schema mapping variable name to domain.
:return: a pair ``(offsets, total)``, where ``offsets`` is an Orde... | 69b673018032ee78205a866d87434ec7da6f2639 | 621,784 |
def str2dict(strdict):
"""Convert key1=value1,key2=value2,... string into dictionary.
:param strdict: key1=value1,key2=value2
Note: This implementation overrides the original implementation
in the neutronclient such that it is no longer required to append
the key with a = to specify a corresponding... | 76fc5e3d4957713426af9121dac3e461964ec0f7 | 621,785 |
def inventree_github_url(*args, **kwargs):
""" Return URL for InvenTree github site """
return "https://github.com/InvenTree" | b1fad67729e8d188e4b58e36205582510f5bc29b | 621,786 |
def always_false(value):
"""A function that always returns False."""
return False | 3f97c9604695cc734dd3313b86c305b503ca47a9 | 621,788 |
def ls_props(thing):
"""List all of the properties on some object
:param thing: Some object
:return: The list of properties
"""
return [x for x in dir(thing) if isinstance(getattr(type(thing), x, None), property)] | a60eac122a1b44a2798cc0d1855b3886cbfad79e | 621,791 |
def kbytes(text):
"""convert memory text to the corresponding value in kilobytes
Args:
text (str): string corresponding to an abbreviation of size.
Returns:
int representation of text.
Examples:
>>> kbytes(\'10K\')
10
>>>
>>> kbytes(\'10G\')
10... | 9f6901eb23a77124fc4ce67d77507549702fbae1 | 621,792 |
import re
def getKeepAlive(response):
"""Extracts and returns the keep alive token from the response.
Extracts and returns the actual keep-alive token from within the response;
this token enables subsequent requests for CSV data.
Args:
response: The Python requests response object, typically correspon... | 0486def47c3b460cc775adba7772ee0ba264295d | 621,793 |
def data_checker(task_name):
"""
Verify if a task associated to a dataset is valid in maxsmi.
Parameters
----------
task_name : str
The considered physical chemical task.
Returns
-------
bool :
True if the name is valid. Raises an error otherwise.
"""
if task_na... | cb2f11f7de796aecadbcc7e8af04b4441c8c3b09 | 621,795 |
def _vax_to_ieee_single_float(data):
"""Converts a float in Vax format to IEEE format.
data should be a single string of chars that have been read in from
a binary file. These will be processed 4 at a time into float values.
Thus the total number of byte/chars in the string should be divisible
by 4... | 0d7cbf6d192be174c2fe7d04773b455fdf7223f7 | 621,797 |
def getBlockNumbersForRegionFromBinPosition(regionIndices, blockBinCount, blockColumnCount, intra):
""" Gets the block numbers we will need for a specific region; used when
the range to extract is sent in as a parameter
Args:
regionIndices (array): Array of ints giving range
blockBinCount (in... | 065630ade7cf5b5ffc86b05fd80bcd890a0eed76 | 621,802 |
def _find_subclasses(cls):
"""Find all the subclasses of a class.
Args:
cls (class): The parent class.
Returns:
list: Subclasses of the given parent class.
"""
results = []
for subclass in cls.__subclasses__():
results.append(subclass)
return results | 779f963c5e7b6c21020aadb3e4faada76c6d2f59 | 621,805 |
def _bop_or(obj1, obj2):
"""Boolean or."""
return bool(obj1) or bool(obj2) | 9638d7680cf71f81839b825c81bd844d9820f545 | 621,808 |
def copy_tensor_list(ten_list):
"""
Create a copy of a list of tensors
"""
ten_list_cp = [None]*len(ten_list)
for i in range(len(ten_list)):
ten_list_cp[i] = ten_list[i].copy()
return ten_list_cp | 5bdcc40ed003e64d54dedb63d46ed40b255f970a | 621,810 |
import json
def to_json_string(my_obj):
"""
Function that returns the JSON representation of an object.
Args:
my_obj (str): Surce object
Returns:
JSON representation.
"""
return json.dumps(my_obj) | 18e51b0ae242ef99ec3831a915b9a1693e25281a | 621,817 |
import toml
def load_features(path):
"""
Loads a Cargo.toml file and extracts all features from it.
:param path: The path to the Cargo.toml
:return: A list of features this package has
"""
with open(path, 'r') as f:
config = toml.load(f)
if 'features' not in config:
... | 58ff9723e5281da344c27e344e559b75245b9017 | 621,818 |
def sum_even_fibonacci(limit: int) -> int:
"""
Sums even terms in the Fibonacci sequence.
:param limit: Limit for the sequence, non-inclusive.
:return: Sum of even terms in the Fibonacci sequence.
"""
term_a = 1
term_b = 2
result = 0
while term_b < limit:
if not term_b % 2:
... | fc7ed095ffba1339e2c866cbb9165b264ba67bcf | 621,819 |
import json
def get_config(config):
""" convert json config file into a python dict """
with open(config, 'r') as f:
config_dict = json.load(f)[0]
return config_dict | f4acafc9e42031c9c7e5ce9bc166fc222eb812a3 | 621,820 |
def intFromBytes(b, signed=False):
"""
Decodes an integer from bytes.
Args:
b (bytes-like): The encoded integer.
signed (bool): Whether to decode as a signed integer.
Returns:
int: The decoded integer.
"""
return int.from_bytes(b, "big", signed=signed) | fe091403b5fcc66928d495142bd120e279b38bd8 | 621,829 |
def isNaN(num):
"""
Checks if a value is nan
:param num: value to be checked
:return: Boolean True or False
"""
return num != num | 3fa3b4498bbb1712ea8ba34ccce41f8c52573f95 | 621,832 |
import itertools
def flock(predicate, iterable):
"""Groups elements into subsequences after sorting::
things = [("phone", "android"),
("phone", "iphone"),
("tablet", "ipad"),
("laptop", "dell studio"),
("phone", "nokia"),
("lapto... | ce55a1952f0c5c7e009b84d9da0b1cbace480ce4 | 621,834 |
import torch
def batch_to_device(batch,target_device):
"""
send a pytorch batch to a device (CPU/GPU)
"""
for key in batch:
if isinstance(batch[key], torch.Tensor):
batch[key] = batch[key].to(target_device)
return batch | d4d48303fba766aba4d92bb195f0a03c8947b7bb | 621,837 |
def makeEvalStop(limit, timer, value=None):
"""Use a closure to create a heuristic function that forces the search
timer to expire when a fixed number of node expansions have been perfomred
during the search. This ensures that the search algorithm should always be
in a predictable state regardless of no... | 8ac700c981c05bbb0dc285f1a46a1e10edb2eef2 | 621,840 |
def partition(predicate, sequence):
"""
Takes a predicate & a sequence of items, and
applies the predicate to each of them.
Returns a tuple with the first item being the
list of matched items, and the second being
the list of not matched items.
"""
match, nomatch = [], []
for item i... | 195fc633401f965560dceac7cf9c2d467b378763 | 621,842 |
from typing import Dict
from typing import Union
from typing import List
from typing import Tuple
from typing import Any
from typing import cast
from typing import Type
def _path_param_reducer(acc: Dict[str, Union[str, List[str]]], cur: Tuple[Dict[str, Any], str]) -> Dict[str, Any]:
"""
Reducer function - acc... | 403eb8953d5b8636bad465e8ba9aa2ded80ef0f6 | 621,849 |
def histogram(letters):
"""
Creates a frequency histogram of the given letters
Input: letters -- word or scrambled letters
Output: dictionary mapping from letters to the # of occurences of that letter
"""
d = dict()
for letter in letters:
if letter in d:
d[letter] += 1
... | 9b9016f9b7a28c986c26c908fa06943dfaf8047d | 621,851 |
def get_num_label_vols(md):
"""
Get the number of volumes used for labelling - e.g. 2 for tag-control pair data
"""
iaf = md.get("iaf", "tc")
if iaf in ("tc", "ct"):
return 2
elif iaf == "diff":
return 1
elif iaf == "mp":
return md.get("nphases", 8)
elif iaf == "v... | 897ce0f5182dd6ea0f516db23106c7233998a25d | 621,852 |
import torch
def sort_by_seq_lens(batch, sequences_lengths, descending=True):
"""
Sort a batch of padded variable length sequences by their length.
Args:
batch: A batch of padded variable length sequences. The batch should
have the dimensions (batch_size x max_sequence_length x *).
... | 135606d9db2ee6e35be59b4e93d4405e26c2a039 | 621,855 |
def calculate_height(distance, y_max, y_min, focal_y):
"""
Calculate real person height in centimeters.
"""
px_height = y_max - y_min
person_height = distance * px_height / focal_y
return person_height | cea53b7316583c34666c88dee769c129f8f11e84 | 621,858 |
def _sub2instance(initial_condition, perturbation_index, total_perturbations):
"""
Converts initial condition index (ci) and perturbation index (pi) subscripts
to an instance number (ii)
instances use 1-based indexes and vary according to this function:
ii = ci * len(PERTURBATIONS) + pi + 1
... | 7c29b8d8b43509c200201cd0d046f3c287ac0057 | 621,859 |
def years_to_seconds(years):
"""
Converts `years` to seconds.
"""
return 3.15569e7 * years | 52ac4b8725d96bd461acca423d303fb6d1943771 | 621,863 |
def is_control(line, index, word):
""" Return whether LINE[INDEX] is actual the start position of
control statement WORD. It must be followed by an opening
parantheses and only whitespace in between WORD and the '('.
"""
if index > 0:
if not (line[index-1] in [' ', '\t', ';']):
return False
inde... | a9d7c567899de9d431d8e4f3cdc3931abad24384 | 621,866 |
import re
def cextra(string):
"""Length of extra color characters in a string"""
return len(''.join(re.findall(r'\033[^m]*m', string))) | a04d0a8efe276519d6b018b5e4f20c26c2a10088 | 621,868 |
def remove_excess_whitespace(maybe_text):
"""Removes excess whitespace from maybe_text if this argument
is a string.
:param maybe_text: An object that might be a string.
"""
if isinstance(maybe_text, str):
maybe_text = ' '.join(maybe_text.split())
maybe_text = maybe_text.strip()
... | 52fc70a367674bb08677ca651d0a05f1341d5bd1 | 621,875 |
def format_type_tuple(type_tuple):
"""Return a list of type names from tuple of types."""
return ", ".join([item.__name__ for item in type_tuple]) | 9f1b645e0c505bf3d49ec4f05a2dcae0b8df5771 | 621,880 |
def param_row(param_keys, param_values):
""" Returns a dict {param key: param value}
"""
values = list(param_values)
return {k: values[i] for i, k in enumerate(param_keys)} | 07b6f70125040238958e3184bef4190f21738171 | 621,883 |
def get_verts(data, x_col, y_col, z_col, scaling):
"""
Get the (x,y,z) verticies from the given data frame using the given columns
and point range scaling.
"""
def get_xyz(row):
x = row[x_col] * scaling
z = row[y_col] * scaling #SWAPPED
y = row[z_col] * scaling * -1.0 #SWAPPE... | 2b5faf7e2cbd9b2dc2a1e228aafec11df2d3b058 | 621,886 |
def linear(x):
"""
Performs linear function on the input elements.
Linear function: f(x) = x
:param x: {array}, shape {n_samples,}
input to the function.
:return: {array}, shape {n_samples,}
output of linear function.
"""
return x | dbab732e58688e8d5763cd13833feb8ab22cd321 | 621,892 |
import torch
def load_model(checkpoint_file,model,optimizer):
"""
Reloads a checkpoint, loading the model and optimizer state_dicts and
setting the start epoch
"""
checkpoint = torch.load(checkpoint_file)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(chec... | e4bcafc8fc0cfa242409a9e47e71cf98260da0d4 | 621,895 |
from pathlib import Path
def extract_book_title(image_path: Path) -> str:
"""Extract book title from image file path."""
return image_path.parts[-1].split('_')[0].split('-')[0] | 11d5a8986aebb107d04a998eea5bce8375642471 | 621,901 |
import hashlib
def sha3_512_half(m: bytes) -> bytes:
"""Return the SHA3_512_half digest of the provided message."""
h = hashlib.sha3_512()
h.update(m)
d = h.digest()
return d[:len(d) // 2] | 819e440f629cef97b9b452e196eb83c574d75e5e | 621,904 |
def isNumber(x):
""" Is the argument a python numeric type. """
return ( (type(x) == float) or (type(x) == int) ) | ec75b53fd5a04b40b7f6590b9c1a9724c5a2a41c | 621,908 |
import torch
def quaternion_to_rotmat_vec(q):
"""
Converts batched quaternions of shape (batch, 4)
to vectorized rotation matrices of shape (batch, 9)
"""
qr = q[:, 0:1]
qi = q[:, 1:2]
qj = q[:, 2:3]
qk = q[:, 3:4]
r1 = torch.cat(
(1. - 2*(qj ** 2 + qk ** 2), 2*(qi*qj - qk*... | 83227075a4824431316e476bf2d16141c7af90a9 | 621,913 |
import re
def match_in(key):
"""Is the key the 'in' keyword"""
rx = re.compile("^_?([iI][nN])_?$")
match = rx.match(key)
if match:
return True
return False | e4a50a28e53f7acaad8d0bb9c48fe9e0d5ff64d2 | 621,916 |
import torch
def cut_components_mixmvn(mixmeans, mixvars, mixweights, cutoff_limit=1e-6):
"""
Remove components of mixture of diagonal normal distributions
whose weights are below some cutoff point
Parameters
----------
mixmeans : torch.Tensor
Mean matrix of mixtures of
diagon... | 7e6ffaf80de054bad8e992b3037f35a0b012a500 | 621,917 |
from typing import Union
from typing import Dict
import yaml
def load_yaml(yaml_config: Union[Dict, str]) -> Dict:
"""Load YAML
Convenience function to allow for providing YAML inputs either as filename
or as dictionary.
Arguments:
yaml_config:
PEtab YAML config as filename or di... | 539cf9cfe7f8aa5fe1df1bf77224f8d44259aaed | 621,918 |
import struct
import codecs
def hex_to_rgb(hex):
"""Convert a hex string to rgb."""
return struct.unpack('BBB', codecs.decode(hex[1:], 'hex')) | de02c9623d4563d6b27caedbc9eb531ac104ea7a | 621,931 |
import re
def tags_matching_regex(key, regex_str:str, compiled_regex = None):
"""
Returns a list of tags with all tags that match the regular expression
"""
if compiled_regex is None:
compiled_regex = re.compile(regex_str)
tags_list = []
for tag in key.getTags():
if compil... | 32f077cf1c32178a777d774ed5bddf1c71d4e51f | 621,938 |
def ParseKey(algorithm, key_length, key_type, messages):
"""Generate a keyspec from the given (unparsed) command line arguments.
Args:
algorithm: (str) String mnemonic for the DNSSEC algorithm to be specified in
the keyspec; must be a value from AlgorithmValueValuesEnum.
key_length: (int) The key l... | e68e208f11479075e09ff69be80a199e6e8b76b0 | 621,940 |
def comma_separated_int(s):
"""
Used as the 'dtype' argument to TextFileParser.add_field(), to parse integer fields
which appear in text files with comma separators.
"""
s = s.replace(',','')
return int(s) | 1eecd58efadf780d37915b733b0b613147dc425f | 621,942 |
def lazy_reduce(reduction, block, launches, contexts):
"""
Applies a reduction over a sequence of parallelizable device operations.
The reduction can be something like built-in `max` or `min`. The
`launches` argument is a sequence of callables which trigger the
asynchronous calculation and return a... | ea0a1442133ff3fd37ada2e54385597cce4423c5 | 621,943 |
def calc_longitude_shift(screen_width: int, percent_hidden: float) -> float:
"""Return the amount to shift longitude per column of screenshots."""
return 0.00000268 * screen_width * (1 - percent_hidden) * 2
# return 0.0000268 * screen_width * (1 - percent_hidden) | 14349732f0006f3e86cbb0bac945808f6224cdd7 | 621,945 |
import csv
import base64
def create_download_link(
dataframe,
filename: str,
file_type: str = "csv",
index: bool = False,
header: bool = True,
):
"""
Generate a download link for a pandas dataframe.
Args:
dataframe: Pandas DataFrame
filename: Name of exported file
... | 3e09f806426211920b651d3946f3c1a229130136 | 621,946 |
def _format_time(elapsed_time):
"""
Format a number of seconds as a HHMMSS string
:param elapsed_time: float, an amount of time in seconds
:return time_string: a formatted string of the elapsed time
"""
hours = elapsed_time // 3600
minutes = (elapsed_time - hours * 3600) // 60
seconds =... | d674672b0419ecdd5e32956ead5c8d0442bb013d | 621,957 |
from typing import Iterable
from typing import Literal
from typing import List
def make_ner_labels(
entity_types: Iterable[str], type_: Literal["BIO", "BILUO"] = "BIO"
) -> List[str]:
"""Make BILUO or BIO style ner label from entity type list.
Examples:
>>> make_ner_labels(["PERSON"])
["-... | 34d32f2adc227e7e79f162cc0c02f4e3af69145c | 621,964 |
def get_unit_concept_id_dict(df):
"""
Retrieve dictionary containing the unit_concept_id and its corresponding unit_concept_name
:param df: dataframe
:return: a dictionary containing the unit_concept_id and its corresponding unit_concept_name
"""
return dict(zip(df.unit_concept_id, df.... | daa01e3e28961498170ac09d89155800e744e036 | 621,965 |
def _AssignTypeToRow(schema, row):
"""Uses a map to parse a given row's field, and assign it to obj.
Args:
schema (dict): Type and name of the row fields. Example:
[
{ 'type': 'INTEGER', 'name': 'field_name'},
...
]
row (dict): Raw row from bigquery response.
{'f... | b21a18e7e917be347913a125c51b47528a6ec883 | 621,966 |
def real_value(value, base):
"""
Returns int(value) if it isn't a percentage, or applies it over base
@param value The value or percentage
@param base The maximum value if value is a percentage
"""
try:
if not value.endswith('%'):
return int(value)
else:
value = float(value[:-1])
... | 50d9f019fa58d8390a8d3839ae269f1f514dcbe0 | 621,969 |
def modify(node):
"""
Modify the branch to NODE, if NODE is a terminal node and the `division_exposure`
of NODE differs from the `division`.
This creates an intermediate branch, with a single child, such that we have
PARENT-INTERMEDIATE-NODE.
"""
if "children" in node:
return node
... | 983714cc7a4703e0bc2cc84d4c75d2c657719745 | 621,970 |
def clean_up_file_name(filename):
"""
If FILENAME has spaces in it, replaces them with underscores. Otherwise,
this function returns the filename unchanged.
"""
words = filename.split()
if len(words) > 1:
filename = "_".join(words)
return filename | db7e289cecc7ca1f11e6eed7153f29231b087688 | 621,972 |
def sanitize_imagename(name: str) -> str:
"""
remove risky characters in a latex image filename and replace them
with a non-risky one (-)
:param name: the image filename to sanitize
:return: the sanitized filename
"""
for c in "%.|_#[]@":
name = name.replace(c, "-")
return name | 8ca2cb0043d3135b89d73124bca30235b597992a | 621,977 |
from typing import Tuple
from typing import Any
from typing import Iterator
def iter_nested_tuple(
data_tuple: Tuple[Any],
sortkey: bool = False
) -> Iterator[Tuple[Any]]:
"""Iterate over a tuple of nested structures. Similar to iter_nested
but it iterates each of each nested data in the input tuple.
For ex... | 6fa81a9b8076ffeecdb8ca29adf59e38eb513916 | 621,978 |
import re
def match_mm3_vdw(mm3_label):
"""Matches MM3* label for bonds."""
return re.match('[\sa-z]6', mm3_label) | 7c4afe17eb47d9ac083272802b53119031b4db10 | 621,980 |
def _graph_without_edge_labels(dg, vertices):
"""
Expand the graph, by introducing new vertices in the middle of edges.
Return the corresponding partition of the new vertices.
There is one new vertex for each edge with label not equal to ``(1,-1)``.
These vertices are numbered starting from the sma... | dffbf43b510b75f36ab52b0a0069cb178c6eaad3 | 621,982 |
def tcp_received(data=None, data_length=None, id=None):
"""
Construct a template for TCP incoming data
"""
tpl = { 'tcp-event': 'received' }
if data is not None:
tpl['tcp-data'] = data
if data_length is not None:
tpl['tcp-data-length'] = data_length
if id is not None:
tpl['client-id'] = str(id)
retu... | d653a81a830c463d6c69c3990b521c1b0ffc917e | 621,994 |
import json
def read_json(file):
"""Load JSON file as dict."""
with open(file, "r") as read_file:
data = json.load(read_file)
return data | f68d8ee17494c9ab4c6d54947571d1129f88327c | 621,995 |
def _validate_port_number(port_number):
"""Validate port number.
Parameters
----------
port_number : int
Supplied port number.
Returns
-------
int
Valid port number.
Raises
------
TypeError
If `port_number` is not of type int.
ValueError
If ... | 1a1b166078e42d1d7dfc56159b7c44b5ffc74a24 | 621,996 |
def Grab_Sequence( reader ):
""" given reader is the position after a fasta header, extract a sequence
return the last line read and the sequence
"""
#read and concatenate lines until > found or other non-sequence character found
total_sequence = ''
sequence = reader.readline( )
while( s... | 6237540eb6c01dd6149d04c7df893e8613533e92 | 622,001 |
def difference(dataset, interval=1):
"""
Differencing time series according to difference_order/interval
dataset:
type:list,
Desc: list contaning timeseries values
interval:
type:integers
Desc: Differencing order
"""
def do_diff(dataset):
diff = list()
... | c3814698ec91b1b754f37018945eb5233c1369bc | 622,002 |
def expected_utility(a, s, U, mdp):
"""The expected utility of doing a in state s, according to the MDP and U."""
# print(sum([p * U[s1] for (p, s1) in mdp.T()[a][s]]))
R, T, beta = mdp.R(), mdp.T(), mdp.beta
return R[a][s] + beta * sum([p * U[s1] for (p, s1) in T[a][s]]) | a5b753f89430c4a83301f8559d04d9cea89a6898 | 622,004 |
import math
def round_power_2(value):
"""
Return value rounded up to the nearest power of 2.
"""
if value == 0:
return 0
return math.pow(2, math.ceil(math.log(value, 2))) | 46d4d4dd9bd96e3d1f34b39c40bb859945391851 | 622,012 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.