content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def prepare_function_parameters(input_parameters, training_parameters):
"""Prepare function parameters using input and training parameters"""
function_parameters = {}
function_parameters = input_parameters.copy()
function_parameters.update(training_parameters)
return function_parameters | 747a9fd878e7729353876819d0d2c871b76a54b0 | 443,354 |
def fix_sequence_length(sequence, length):
"""
Function to check if length of sequence matches specified
length and then return a sequence that's either padded or
truncated to match the given length
Args:
sequence (str): the input sequence
length (int): expec... | 300566ba387ac33709ed2e9eef28f1ab65ed5f60 | 576,054 |
def trajectory_importance_max_min(states_importance):
""" computes the importance of the trajectory, according to max-min approach: delta(max state, min state) """
max, min = float("-inf"), float("inf")
for i in range(len(states_importance)):
state_importance = states_importance[i]
if state_... | c9185e46455224056d9dbdd4704f7cb1aa6cddac | 247,170 |
def _get_nullable_handle(handle_wrapper):
"""Return the handle of `handle_wrapper` or None"""
if handle_wrapper is None:
return None
else:
return handle_wrapper._handle | 1e55b535b38b0ae56a011fb7cd3620a3296b609a | 428,436 |
def color(priority, text):
"""
Colors the text according to the priority of the task
:param priority: priority of task
:param text: string, that needs to be colored
:return: colored text
"""
if priority == 1: # красный
return f'\033[31m{text}\033[0m'
elif priority == 2: # желт... | 9609c951127453a72d7c5c6e1642800658f8e0d5 | 353,194 |
import torch
def one_hot(y, num_dim=10):
"""
One Hot Encoding, similar to `torch.eye(num_dim).index_select(dim=0, index=y)`
:param y: N-dim tenser
:param num_dim: do one-hot labeling from `0` to `num_dim-1`
:return: shape = (batch_size, num_dim)
"""
one_hot_y = torch.zeros(y.size(0), num_d... | 694bfea18ecbb5c5737e0d38c0aa0f5f52a82a55 | 1,007 |
def hook(t):
"""Calculate the progress from download callbacks (For progress bar)"""
def inner(bytes_amount):
t.update(bytes_amount) # Update progress bar
return inner | d8228b9dec203aaa32d268dea8feef52e8db6137 | 3,102 |
import base64
def get_hash(crc):
"""Gets the base64-encoded hash from a CRC32C object.
Args:
crc (google_crc32c.Checksum|predefined.Crc): CRC32C object from
google-crc32c or crcmod package.
Returns:
A string representing the base64 encoded CRC32C hash.
"""
return base64.b64encode(crc.digest(... | 70a358132c9d11fa6aecd3fa84bc755f8c247697 | 565,679 |
def split_arguments(args):
"""Returns the 2-tuple (args[:-1], args[-1]) if args[-1] exists and
is a dict; otherwise returns (args, {}).
"""
if args and isinstance(args[-1], dict):
return args[:-1], args[-1]
else:
return args, {} | e5dcc6228cf2d92f701bb8c2e89dc2fdac97e993 | 276,649 |
def compute_bytes_per_voxel(element_type):
"""Returns number of bytes required to store one voxel for the given
metaIO ElementType """
switcher = {
'MET_CHAR': 1,
'MET_UCHAR': 1,
'MET_SHORT': 2,
'MET_USHORT': 2,
'MET_INT': 4,
'MET_UINT': 4,
'MET_LONG'... | b2bd1ff15d1bfef979e8f5c2152a5776b4754220 | 332,270 |
def _swiftmodule_for_cpu(swiftmodule_files, cpu):
"""Select the cpu specific swiftmodule."""
# The paths will be of the following format:
# ABC.framework/Modules/ABC.swiftmodule/<arch>.swiftmodule
# Where <arch> will be a common arch like x86_64, arm64, etc.
named_files = {f.basename: f for f in ... | 59e978f22f4b1959ef32b0f2d68b0d92ec7fabe0 | 38,046 |
def calculate_width(size: tuple[int, int], pixel_height: int) -> int:
""" Calculates width according to height to keep the aspect ratio. """
original_width, original_height = size
height_ratio = pixel_height / original_height
return round(original_width * height_ratio, None) | 077de208c5a471a550bf2955fc978e3fdf77d83a | 389,379 |
def writePattern(df, pat):
"""
utility function to append a pattern in a dataframe
Parameters
----------
df : pandas dataframe
input dataframe to be updated
pat : src.Patterns.pattern
pattern to be added
Returns
-------
pandas dataframe
updated dataframe
... | 0e65b2a8024109e1d72782293764b663f70ccaf2 | 305,597 |
def smooth_freqs(freqs):
"""
Smooths freqs vector, guarantees sum == 1
:param freqs: vector of frequencies
:return: vector of frequencies guaranteed to sum to 1
"""
s = sum(freqs)
return [f/s for f in freqs] | 89238cdf5d43d72010e05512b0d80fb648666aec | 169,496 |
def curb_gpred_spans(dmrs_xml, max_tokens=3):
"""
Remove general predicate node token alignments if a general predicate node spans more than max_tokens.
This prevents general predicate nodes from dominating rule extraction.
:param dmrs_xml: Input DMRS XML
:param max_tokens: Maximum number of allowed... | 45d80423a0604ca503e8f2ae730b9b5ca0c3e1e1 | 107,538 |
def get_structure(dataset_or_iterator):
"""Returns the type specification of an element of a `Dataset` or `Iterator`.
Args:
dataset_or_iterator: A `tf.data.Dataset` or `tf.data.Iterator`.
Returns:
A nested structure of `tf.TypeSpec` objects matching the structure of an
element of `dataset_or_iterato... | e1def0868e3f656b258c3639543ac01e83d96d14 | 161,943 |
from typing import OrderedDict
def process_odin_args(args):
"""
Finds arguments needed in the ODIN stage of the flow
"""
odin_args = OrderedDict()
odin_args["adder_type"] = args.adder_type
if args.adder_cin_global:
odin_args["adder_cin_global"] = True
if args.disable_odin_xml:
... | 92a50c84be6d16f966323d02a9db8d5f32a04c2e | 48,483 |
def className(obj):
""" Return the name of a class as a string. """
return obj.__class__.__name__ | 557d77c70387524e83c4956ce859f90116251136 | 393,662 |
def boost_nph(group, nph):
"""
Return a fraction of boost based on total number of high-binding peptides per IAR.
:param pandas.core.frame.DataFrame group: The IAR under review.
:param float nph: The total boost amount allotted to this criterion.
:returns: The percent of boost provided by this crit... | 383cff2d6c4f9bff5aadd02982368a3d24f9b167 | 528,388 |
def set_offset(chan_obj):
""" Return a tuple of offset value and calibrate value.
Arguments:
chan_obj (dict): Dictionary containing channel information.
"""
physical_range = chan_obj['physical_max'] - chan_obj['physical_min']
digital_range = chan_obj['digital_max'] - chan_o... | 06ab3aeafcb1ba26799d3ac2696b62909928310d | 80,751 |
from math import floor, log10
def findSizeInt(number):
"""
#EN-US:
→ Calculates the number of digits in a number.
:param number: the number to be calculated.
:return: the number of digits of the number entered.
#PT-BR:
→ Calcula a quantidade de dígitos em um número.
:param number: o n... | 8b174183520337f31f17bfb4163d5ed5ff90e896 | 14,360 |
def turbulent_kinetic_energy(field):
"""
Calculates turbulent kinetic energy.
Parameters
----------
field : Field2D
Returns
-------
Field2D
Author(s)
---------
Jia Cheng Hu
"""
return 0.5*(field.rms()**2).fsum(0) | 53c7e6eb34051f3df6e71efefb89776492fdd785 | 359,170 |
def play_sound(register, cur_instruction, name):
"""Play sound/send instruction."""
register['sound'].append(register[name])
register['counter'] += 1
return cur_instruction | 6a1f664e40d998c36cefea1987281dfb72cd7f1f | 454,347 |
import json
def read_coco(cocofile):
"""Read coco annotation file (json format) into dictionaries"""
# Read file
with open(cocofile, 'r') as fptr:
cocojson = json.load(fptr)
imgid_to_annot = {}
# Create dict of image id to filename and annots for all images
imgid_to_filename = {im... | acd156c4ed45a5b24783ab0cb7c9280e74032668 | 381,104 |
def bookkeep_product(mol):
"""Bookkeep reaction-related information of atoms/bonds in products
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
RDKit molecule instance for products.
Returns
-------
info : dict
Reaction-related information of atoms/bonds in products
"""... | bf2d774fd42c98468bfb3af1abe1e2adc15ec8e2 | 531,534 |
import torch
def _convert_boxes_to_roi_format(boxes):
"""
Convert rois into the torchvision format.
:param boxes: The roi boxes as a native tensor[B, K, 4].
:return: The roi boxes in the format that roi pooling and roi align in torchvision require. Native tensor[B*K, 5].
"""
concat_boxes = bo... | 72ce30f5d7a92b3a09eb692c88f610da26b1edeb | 70,941 |
def compare_distributions(actual_distribution, expected_distribution,
threshold):
"""Compare if two distributions are similar.
Args:
actual_distribution: A list of floats, contains the actual distribution.
expected_distribution: A list of floats, contains the expected dist... | 198f3d54cee98b5d69ada2d12f9b7f09a31a87b3 | 436,378 |
import re
def pathspec(expression):
"""
Normalizes a path which is separated by backward or forward slashes to be
separated by forward slashes.
"""
return '/'.join(re.split(R'[\\\/]', expression)) | c5a028eb8b6371a8fa85928844c1e463fa44ab69 | 185,780 |
def no_forcing(grid):
"""Zero-valued forcing field for unforced simulations."""
del grid
def forcing(v):
return tuple(0 * u.array for u in v)
return forcing | 5ffe81104de215f80c30c1edc896933ae980917e | 476,640 |
import six
def _compare_match(dict1, dict2):
"""
Compare two dictionaries and return a boolean value if their values match.
"""
for karg, warg in six.iteritems(dict1):
if karg in dict2 and dict2[karg] != warg:
return False
return True | c2da782d6dc6d9a00b49dd093fc2b2acb76200bf | 155,609 |
def strip_output(nb):
"""strip the outputs from a notebook object"""
nb.metadata.pop('signature', None)
for cell in nb.worksheets[0].cells:
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
return nb | 94f168f9ee04c18076eb154d2da704e53cb883ff | 311,254 |
def remove_new_lines_in_paragraph(article):
"""When we publish articles to dev.to sometimes the paragraphs don't look very good.
So we will remove all new lines from paragraphs before we publish them. This means we
don't have to have very long lines in the document making it easier to edit.
Some elemen... | 6f2123bebe966b4e3b03a0c4473628985b883f3f | 645,770 |
import re
def parse_arches_from_config_in(fname):
"""Given a path to an arch/Config.in.* file, parse it to get the list
of BR2_ARCH values for this architecture."""
arches = set()
with open(fname, "r") as f:
parsing_arches = False
for line in f:
line = line.strip()
... | af1d8de9a5a210f4e009b942cf069f1c6d6c4e47 | 648,849 |
def GROUP(e):
"""
puts the argument in a group
:param:
- `e`: a string regular expression
:return: grouped regular expression (string)
"""
return "({e})".format(e=e) | 93a57b6004b59f1f52ba8bdfda8e5727f9653bea | 523,049 |
from typing import OrderedDict
def invert(mapper):
"""Invert a dict of lists preserving the order."""
inverse = OrderedDict()
for k, v in mapper.items():
for i in v:
inverse[i] = k
return inverse | 0cd15a56762b36a774cb91b711f5d893da62de1f | 664,585 |
def parse_dataset_sid_pid2eval_sid_pid(dataset_sid_pid2eval_sid_pid):
"""
Parsing priority, sid_pid is mapped to:
1. dataset_sid_pid2eval_sid_pid[sid_pid] if it exists, else
2. to the same sid_pid
Returns:
sid_pid2eval_id: a dense mapping having keys for all possible sid_pid s (0 to 99_99)
usin... | dfbf98f1f295aa2cecbf6213ea189bc7f609c567 | 371,950 |
def decipher(message: str, cipher_map: dict) -> str:
"""
Deciphers a message given a cipher map
:param message: Message to decipher
:param cipher_map: Dictionary mapping to use
:return: Deciphered string
>>> cipher_map = create_cipher_map('Goodbye!!')
>>> decipher(encipher('Hello World!!', c... | 0953dcb3119c8158f829b45184af85e1a5964716 | 335,057 |
from typing import Iterable
from typing import Tuple
from typing import List
import itertools
def sorted_chain(*ranges: Iterable[Tuple[int, int]]) -> List[Tuple[int, int]]:
"""Chain & sort ranges."""
return sorted(itertools.chain(*ranges)) | 6724c401a451b7d64aafb594af481e914de61277 | 263,237 |
def gen_orthoplot(f, gs):
"""Create axes on a subgrid to fit three orthogonal projections."""
axs = []
size_xy = 5
size_z = 1
size_t = size_xy + size_z
gs_sub = gs.subgridspec(size_t, size_t)
# central: yx-image
axs.append(f.add_subplot(gs_sub[:size_xy, :size_xy]))
# middle-bottom... | 92d90a6e472349d539a30165e6cbfce2e5b53e4f | 360,963 |
from typing import Any
from typing import Callable
from functools import reduce
def pipe(v: Any, *fns: Callable):
"""
Thread a value through one or more functions.
Functions are applied left to right
>>> def double(n):
... print(f'Doubling {n}...')
... return n * 2
>>> def inc(n)... | 94d0d3dad502494b444a0aabfa31c1c1ad471db4 | 298,047 |
def parseCustomHeaders(custom: str) -> list:
"""
Parse string of semi-colon seperated custom headers in to a list
"""
if ";" in custom:
if custom.endswith(';'):
custom = custom[:-1]
return custom.split(';')
else:
return [custom] | 1cfdf1a9b8e0c70ca60b1938dd4a6f2b5a8a17f2 | 349,462 |
def CODE(string):
"""
Returns the numeric Unicode map value of the first character in the string provided.
Same as `ord(string[0])`.
>>> CODE("A")
65
>>> CODE("!")
33
>>> CODE("!A")
33
"""
return ord(string[0]) | 0f680fe1e45156c00d0a5839e24f1619a456773f | 700,680 |
from typing import Any
import json
def save_object_as_json(obj: Any, filepath: str) -> None:
"""Saves Python object as JSON file"""
with open(file=filepath, mode='w') as fp:
json.dump(obj=obj, fp=fp, indent=4)
return None | 3f38a33dd7cbf6e9d25308ede4ed48e4ccd9c28d | 291,851 |
import re
def tag_to_label(tag: str) -> str:
"""Return the spaced and lowercased label for the given camelCase tag."""
return re.sub(r'(?<!^)(?=[A-Z])', ' ', tag).lower() | 262d72d343c99f509e91da07fbd307ac6c30836b | 612,313 |
def builder_support(builder):
"""
Return True when builder is supported.
Supported builders output in html format, but exclude
`PickleHTMLBuilder` and `JSONHTMLBuilder`, which run into issues
when serializing blog objects.
"""
if hasattr(builder, "builder"):
builder = builder.build... | 3e3244bfefa0cb81f52fc3aadb12b052865a5b90 | 570,231 |
def is_abba(abba_str):
"""Returns true if 4 character string consists of a pair of two different characters followed
by the reverse of that pair"""
if len(abba_str) != 4:
raise Exception
return abba_str[0] == abba_str[3] and abba_str[1] == abba_str[2] and abba_str[0] != abba_str[1] | 78484e6cc5174aaba30e98c2bd843d57c81ab9f0 | 538,664 |
import random
def integers_equal(n, min_, max_):
""" Return sequence of N equal integers between min_ and max_ (included).
"""
eq = random.randint(min_, max_)
return [eq for _ in range(n)] | 4ab257ed7c434bf4574afac4b0fc3f0e543da57c | 144,205 |
import math
def geometric_mean(values):
"""
Evaluates the geometric mean for a list of numeric values.
@param values: List with values.
@return: Single value representing the geometric mean for the list values.
@see: http://en.wikipedia.org/wiki/Geometric_mean
"""
try:
values = [i... | 34f0c5906b0425fbd915f3c7218f033d54d04f08 | 322,577 |
def ossec_level_to_log_level(message: dict) -> str:
"""
converts OSSEC_Level to log level
OSSEC level. An integer in the range 0 to 15 inclusive. 0-3=Low severity, 4-7=Medium severity, 8-11=High severity, 12-15=Critical severity.
"""
level = message.get("OSSEC_Level", 0)
if level >= 8:
r... | 085230cf38f45647feec7a0e47c0e1d0d34b5408 | 148,722 |
def remove_remote(ssh, path):
"""Remove a remote file or directory.
Arguments:
ssh: Established SSH connection instance.
path (str): Absolute path to the file or directory.
Returns:
Boolean indicating result.
"""
stdin, stdout, stderr = ssh.exec_command('rm -rf %s' % path)
... | 5b7f02df2dc1147771712e468559f5741d674b6e | 525,547 |
def diff(list_1, list_2):
"""
get difference of two lists
:param list_1: list
:param list_2: list
:return: list
"""
return list(set(list_1) - set(list_2)) | 46671b83b604947a10467a6376ee2ea1025b41cb | 399,942 |
def character_ngrams(s, ngram_range, lhs='<', rhs='>'):
"""
Extract character n-grams of length *n* from string *s*
Args:
s: the string whence n-grams are extracted
ngram_range: tuple with two elements: the min and max ngram lengths
lhs: left-padding character (to show token boundar... | 2728a9d787594c77b78206278afa717ddd5c5e07 | 140,036 |
from typing import Iterable
from typing import Tuple
import itertools
def find_two_numbers_that_add_to(numbers: Iterable[int],
desired_outcome: int) -> Tuple[int, int]:
"""Finds two numbers in a list (or other iterable) of numbers that
add up to the desired outcome. Returns th... | 6f7e0feea89c21909d9596cc7fb3e3afadd468f6 | 146,122 |
def GetComplementaryColor(hexStr):
"""Returns complementary RGB color
Example Usage:
>>> GetComplementaryColor('#FFFFFF')
'#000000'
"""
if hexStr[0] == '#':
hexStr = hexStr[1:]
rgb = (hexStr[0:2], hexStr[2:4], hexStr[4:6])
compColor = '#'
for a in rgb:
comp... | 5c42a8ccfc48f57d4f8ba2728b83ad0972dbd644 | 620,214 |
def flatten(l):
"""Flatten a nested list to a one dimensional list."""
r = []
for item in l:
if isinstance(item, list) or isinstance(item, tuple):
r.extend(flatten(item))
else: r.append(item)
return r | 4355cce3c291356c45758f29939dad364edcfe55 | 190,760 |
import random
def random_anagrammable(Nsamples, wbags, Nanagrams=1, Lmax=None):
"""
Randomly sample words from a dictionary which also have an anagram in the dictionary.
Parameters
----------
Nsamples : int
Number of words to sample
wbags : mapping
Structure mapping `wordbag(w... | 54d14f3af3a4d20cbc01d473ba18b89a07de5415 | 471,132 |
def elev_gain_loss(elev_data, smooth_time=25):
"""
Calculate elevation gain and loss over the course of the activity.
Elevation profile smoothed to reduce the impact of short-term elevation noise.
Gain and loss defined as cumulative sum of positive and negative 1st discrete difference, respectively.
... | df73dad3a80c4396b9268b39b58499a200d7b738 | 306,186 |
def num_owned_indices_from_cyclic(dd):
"""Given a dimension dictionary `dd` with dist_type 'c', return the number
of indices owned.
"""
block_size = dd.get('block_size', 1)
global_nblocks, partial = divmod(dd['size'], block_size)
local_nblocks = ((global_nblocks - 1 - dd['proc_grid_rank']) //
... | 653137633fad20db171cb2566273dbf4f9b2077a | 236,678 |
import torch
def load_model_from_file(path, model):
"""
Load a (trained) model from file.
Parameters
----------
path: str
File where the model to be loaded is saved.
Returns
-------
Pytorch object
Pytorch object as defined in the file.
"""
model.load_state_dic... | 7b767d536efe587c0b58afdba51a8e3c597e7e98 | 450,372 |
def default(df):
"""
By default, do nothing
:param df:
:return:
"""
return df | d64c9bca054f08e969e0167fb074554257e03ae5 | 165,187 |
def _IsGritInputFile(input_file):
"""Returns True iff this is a GRIT input file."""
return input_file.endswith('.grd') | 9a45554185c4b6958001500518c9d18d6d563c63 | 446,194 |
def get_model_dir(experiment_params, flags_obj):
"""Gets model dir from Flags."""
del experiment_params
return flags_obj.model_dir | d3a3254939a9f1973d369235964a2e1935d8ddd0 | 304,524 |
from typing import Sequence
from typing import List
def make_golden(
sequence: Sequence,
)-> List:
"""Given a sequence of elements, separates it into two new sequences,
on the index that is equivalent to the golden ratio of the sequence length.
"""
golden_index = round(len(sequence) * 0.618)... | 34b63a8a88aa2a0154b75070c8a6eaed7d3be259 | 294,374 |
from typing import Optional
from typing import Type
def is_none_type(type_: Optional[Type]) -> bool:
"""Is the given type NoneType?"""
return type_ is type(None) | adacf3da1037bfb10d44570fbd3e9ebd07c85b45 | 378,288 |
def h(level: int, text: str) -> str:
"""Wrap text into an HTML `h` tag."""
return f"<h{str(level)}>{text}</h{level}>" | b7dac43c54ed2080687b89a72f268e5a2d580d24 | 181,188 |
def link(url, linkText='{url}'):
"""Returns a link HTML string.
The string is an <a> tag that links to the given url.
If linkText is not provided, the link text will be the url.
"""
template = '<a href={url}>' + linkText + '</a>'
return template.format(url=url) | a53c4cd468de23cfc25572093ca8787feb4f12a4 | 66,595 |
def get_class_name(o, lower=False):
"""
Returns the class name of an object o.
"""
if not isinstance(o, type):
o = o.__class__
if lower:
return o.__name__.lower()
else:
return o.__name__ | 15ef10f6612e34e4c81bae707044daca15b5f81f | 637,216 |
import re
def parse_tags(app_tags):
"""
Parse given tags value, standardize, and remove duplicates.
"""
app_tags = [_f for _f in re.split("[,]+ *", app_tags) if _f]
tags = []
for tag in app_tags:
tag = tag.replace('"', '')
tag = tag.replace("'", '')
tag = re.sub(r"\s+"... | 8d974b640bc4e6f1fc0035b2aa1433b04b068aca | 167,911 |
def _return_ordered_config(unordered_config: dict, template_config: dict) -> dict:
"""Orders the keys in unordered_config according to the order in template_config.
Note this function assumes all keys in both dictionaries are identical,
including all nested dictionaries.
"""
# create a dictionary ... | f74f62973511bf26b188c77e6ee6d31367c8fcf6 | 647,410 |
def count_char(char, text):
"""Count number of occurences of char in text."""
return text.count(char) | dad3ad1fb81387efadb5e7e0fdde8c7d67e4be05 | 477,661 |
def normalize_content(content: str) -> str:
"""
Remove preceding and trailing whitespaces from `content` string.
:param content: string to be normalized.
:returns: normalized string.
"""
return content.strip(' \n\t') | b5fd7c6fb28bd9ff90ecfcb7784d3152660643b7 | 241,361 |
def get_solution(self, j_t0=0):
"""Return the solution corresponding to a time step.
Parameters
----------
self : MeshSolution
an MeshSolution object
j_t0 : int
a time step
Returns
-------
solution: Solution
a Solution object
"""
return self.solution[j... | cc0c14b73727a6fdbdeae8b69ced1218b2b64d9b | 257,455 |
def _get_stat_var_mcf(sv_id: str, sv_pv: dict) -> str:
"""Generate a MCF node string for a statVar
Args:
sv_id: Node Id string for the StatVar
sv_pv: dictionary of all property:values for the StatVar
Returns:
a string with StatVar node in MCF format with each property in a new line
... | c4eb06bbe60a858f647818b64b4721e188ad9886 | 267,975 |
def last_updated_cell(i):
"""Make and return the last_updated cell at Column E."""
return "E{}".format(str(i)) | 53e61c345746184200819ab41a7bae73718657c9 | 206,409 |
import time
def watch_condition(cond, target=None, timeout=None, interval=0.1):
"""
Watch a given condition (a callable) until it returns the target value, and
return that value. Stop watching on timeout, in that case return None. The
condition is tested approximately every 'interval' seconds.
"... | 8915cb03e35615403f77d8f5682e7b0225cfb57d | 363,554 |
from typing import Dict
from typing import Any
from typing import List
def _create_group_codes_names(
contact_models: Dict[str, Any], assort_bys: Dict[str, List[str]]
) -> Dict[str, str]:
"""Create a name for each contact models group codes.
The group codes are either found in the initial states or are a... | 0fe1419ae5e1b3a6e3b6b60880e8e2db641d6297 | 300,488 |
import torch
def bhwc_to_bchw(input: torch.Tensor) -> torch.Tensor:
"""
Permutes a tensor to the shape [batch size, channels, height, width]
:param input: (torch.Tensor) Input tensor of the shape [batch size, height, width, channels]
:return: (torch.Tensor) Output tensor of the shape [batch size, chan... | b4ce50136977edd4f2f5156298c84f75fa7780a8 | 138,184 |
def mmd2_u_stat_variance(K, inds=(0, 1)):
"""
Estimate MMD variance with estimator from https://arxiv.org/abs/1906.02104.
K should be a LazyKernel; we'll compare the parts in inds,
default (0, 1) to use K.XX, K.XY, K.YY.
"""
i, j = inds
m = K.n(i)
assert K.n(j) == m
XX = K.matrix(... | 6fad7095651f8f66d991af8b33597e64464b7d70 | 139,537 |
def to_sequence(index, text):
"""Returns a list of integer indicies of lemmas in `text` to the word2idx
vocab in `index`.
:param index: word2idx vocab.
:param text: list of tokens / lemmas / words to be indexed
:returns: list of indicies
"""
indexes = [index[word] for word in text if word... | 974c62ee767e2e48c903aabda9b1f4894071cb3a | 249,858 |
def alpha_from_k_half_mode(khalf, beta, gamma):
"""Calculates alpha, given the half-mode wavenumber"""
return 1./khalf * (2.**(1./gamma) - 1. )**(1./beta) | 4eee2694ca05b5a6ebe424791e465e6f954a9f25 | 86,226 |
import pathlib
import json
def check_configuration(configuration_file: str) -> dict:
"""
load json into a dictionary from a given valid file path string,
otherwise throws FileNotFoundError exception
:param configuration_file: string of path to configuration
:return: dict
"""
path_object = ... | 4a380855799045bdfeea921d55b72e5b16e97eb0 | 529,456 |
def unique_list(a_list, unique_func=None, replace=False):
"""Unique a list like object.
- collection: list like object
- unique_func: the filter functions to return a hashable sign for unique
- replace: the following replace the above with the same sign
Return the unique subcollection of collectio... | 8d7957a8dffc18b82e8a45129ba3634c28dd0d52 | 708,206 |
def sliding_box(start, stop, size, step=1):
"""
Find sliding boxes of region
Parameters:
-----------
start: int
0 based start coordinate of the region.
stop : int
0 based stop coordinate of the region, i.e. stop is not part of the
region anymore;
size : int
T... | 7bb0ce44fe0d97e36b38abdc7342df0f5c47fd91 | 569,028 |
import re
def dont_document_data(config, fullname):
"""Check whether the given object should be documented
Parameters
----------
config: sphinx.Options
The configuration
fullname: str
The name of the object
Returns
-------
bool
Whether the data of `fullname` s... | dfe56e6cad36ecb978d2973efa0a313e4b75587e | 634,446 |
def get_resource_name(prefix, project_name):
"""Get a name that can be used for GCE resources."""
# https://cloud.google.com/compute/docs/reference/latest/instanceGroupManagers
max_name_length = 58
project_name = project_name.lower().replace('_', '-')
name = prefix + '-' + project_name
return name[:max_nam... | 7779f71e00063b32566f05d4cb0d8daef81043c0 | 700,829 |
def _pretty_multiplier(x: float) -> str:
"""Make a prettier version of a multiplier value
Args:
x: Value for a multiplicative factor (e.g., b = x * a)
Returns:
A humanized version of it
"""
if x > 100:
return f'{x:.0f}x'
elif x > 2:
return f'{x:.1f}x'
return ... | 98c2f96ac429ac0b17ed929fe39d5caf548c36e2 | 247,020 |
import copy
def _fold_stats(result, stats, ktk_cube_dataset_id):
"""
Add stats together.
Parameters
----------
result: Dict[str, Dict[str, int]]
Result dictionary, may be empty or a result of a previous call to :meth:`_fold_stats`.
stats: Dict[str, int]
Statistics for a single... | 72dee1f34ca9357974b858a221b23b9d6ff116dc | 154,799 |
def getOperator(instr):
"""Get the operator from an existing instruction"""
operator = (instr/100)*100 # change for binary machine, but beware of breaking number output
return operator | 5d8163a2cf3f497dbae84565cbe6af913f65085c | 231,021 |
def xpath(elt, xp, ns, default=None):
"""
Run an xpath on an element and return the first result. If no results
were returned then return the default value.
"""
res = elt.xpath(xp, namespaces=ns)
if len(res) == 0:
return default
else:
return res[0] | e8e873db535597edc82a3af439db2ddb7a0c1c1b | 96,675 |
def get_clean_block(block):
"""Clean up unicode characters and common OCR errors in blocks"""
replacements = {'fi': 'fi',
'fl': 'fi',
'—': '-',
"’": "'",
"‘": "'",
'”': '"',
'“': '"',
... | 7a769ebeb1992070286e1d57bb93421c68c79afc | 662,796 |
def match_edit(json, body):
"""Checks the json edit response matches the request body."""
# Check the benchmark matches the request
if 'benchmark_id' in body:
assert json['benchmark']['id'] == str(body['benchmark_id'])
# Check the site matches the request
if 'site_id' in body:
asse... | 9c5bfceb25c742371db1edc014355a3cb7eecf23 | 523,775 |
def camel_case_to_snake_case(camel_case_string):
"""
Convert a camelCase string to a snake_case string.
Args:
camel_case_string (str):
A string using lowerCamelCaseConvention.
Returns:
str:
A string using snake_case_convention.
"""
# https://stackoverfl... | fc05ba07de498864088211fc447bc24d33b470b3 | 502,837 |
from typing import Union
from typing import Dict
def _format_peak_comment(mz: Union[int, float], peak_comments: Dict):
"""Format peak comment for given mz to return the quoted comment or empty string if no peak comment is present."""
if peak_comments is None:
return ""
peak_comment = peak_comments... | dd303655f0b163af27ab043ce69efdefa53d28b6 | 622,794 |
def detect_edge_features(features, Dx, Dy, wx, wy=None):
"""Detects edge features from feature set.
Parameters
----------
features : `pd.DataFrame`
Feature set returned from `trackpy.locate`
Dx, Dy : scalar
Dimensions of stack
wx, wy : scalar
Dimensions of bounding boxes... | ded29e4fe047a114e833e522a596cc56d576c007 | 552,870 |
def TransformNextMaintenance(r, undefined=''):
"""Returns the timestamps of the next scheduled maintenance.
All timestamps are assumed to be ISO strings in the same timezone.
Args:
r: JSON-serializable object.
undefined: Returns this value if the resource cannot be formatted.
Returns:
The timesta... | 7d6bd3bc2437c0f0eaf006674c61a42f11c191a6 | 377,083 |
def add_negated_bounded_span(works, start, length):
"""Filters an isolated sub-sequence of variables assined to True.
Extract the span of Boolean variables [start, start + length), negate them,
and if there is variables to the left/right of this span, surround the span by
them in non negated form.
Args:
... | 2ffcf0e008cebca2b59d89fbc5b3b517aee5df1c | 336,204 |
def define_orderers(orderer_names, orderer_hosts, domain=None):
"""Define orderers as connection objects.
Args:
orderer_names (Iterable): List of orderer names.
orderer_hosts (Iterable): List of orderer hosts.
domain (str): Domain used. Defaults to none.
Returns... | 32ea2ed7b89afdf64356674e9a1fa0aea85792e3 | 56,096 |
def mk_item_id(item_id: str, collection_id: str):
"""Make the Elasticsearch document _id value from the Item id and collection."""
return f"{item_id}|{collection_id}" | 9707c13e9a1e606c4f495004a4561dafe4d08957 | 451,626 |
from typing import List
def recortar_nombres(nombres: List[str]) -> List[str]:
"""Recorta los nombres de la lista a la longitud de la última
cadena de caracteres.
:param nombres: Lista de cadenas de caracteres.
:nombres type: List[str]
:return: Lista de cadenas de caracteres recortadas.
:rtyp... | 00c356d6bf07bdf76054e8ee9cb01800508f2529 | 457,111 |
import requests
import json
def request_new_tokens(refresh_token, client_id, client_secret, write_out=None):
"""
Contacts api.amazon.com/auth/o2/token to retrieve new access and refresh tokens
:param refresh_token: valid refresh_token
:param client_id: client_id
:param client_secret: client_secre... | 1ce8bfb274d02b6b8cfdf71aea11b4d59a7fdef5 | 244,929 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.