content stringlengths 42 6.51k |
|---|
def euclide_algorithm(a: int, b: int) -> dict :
"""
Extended Euclide's algorithm
Compute the PGCD from two integers and return the Bezout's relation elements
Entry : two integers A and B
Return : a dict ( "PGCD" , "U" , "V")
where r is the remind and u and v are the the coefficients of the Bezout's relation
"... |
def RC(a,b):
"""
Compute Carlson's integral RC(a, b).
1 /\oo dx
RC(a, b) = - | -----------------
2 | 1/2
\/0 (x + a) (x + b)
The parameters a and b may be complex numbers.
"""
A, B = a, b
for k in range(4):
g... |
def count_startswith(L, ch):
""" (list of str, str) -> int
Precondition: the length of each item in L is >= 1, and len(ch) == 1
Return the number of strings in L that begin with ch.
>>> count_startswith(['rumba', 'salsa', 'samba'], 's')
2
>>> count_startswith(['rumba', 'salsa', 'samba'], 'r')... |
def full_name(obj):
"""Returns the full python name with the path as a string.
Args:
obj (string): Class
Returns:
str
"""
return "{0}.{1}".format(obj.__module__, obj.__name__) |
def strip_commands(commands):
""" Strips a sequence of commands.
Strips down the sequence of commands by removing comments and
surrounding whitespace around each individual command and then
removing blank commands.
Parameters
----------
commands : iterable of strings
Iterable of co... |
def quote_filenames(filenames):
"""Quote each elements so filename spaces don't mess up gyp's attempt to parse
it into a list."""
return " ".join(['"%s"' % x for x in filenames]) |
def i2xyz(i):
""" For easy reading of error checks """
if i == 0:
return "x"
elif i == 1:
return "y"
else:
return "z" |
def expand_tuples(L):
"""
>>> expand_tuples([1, (2, 3)])
[(1, 2), (1, 3)]
>>> expand_tuples([1, 2])
[(1, 2)]
"""
if not L:
return [()]
elif not isinstance(L[0], tuple):
rest = expand_tuples(L[1:])
return [(L[0],) + t for t in rest]
else:
rest = expand_... |
def spec_is_empty(specification):
"""Check if specification value is empty
Args:
specification: List of specification values
"""
if len(specification) == 0:
return True
return False |
def multi_split(s, split):
"""Splits on multiple given separators."""
for r in split:
s = s.replace(r, '|')
return [i for i in s.split('|') if len(i) > 0] |
def departure(ob, climo):
""" Compute a departure value """
if ob is None or climo is None:
return "M"
return ob - climo |
def learning_rate_warmup_distributed(
learning_rate,
epoch,
warmup_epochs,
num_workers,
curr_step,
steps_per_epoch
):
"""Implements gradual learning rate warmup:
`lr = initial_lr / hvd.size()` ---> `lr = initial_lr`
`initial_lr` is the learning rate of the mo... |
def _prune_tree(subtree, tree):
"""Do the work.
I'm struggling to write a good docstring here.
"""
if subtree == tree:
return {}
return {c: _prune_tree(subtree[c], tree[c]) for c in subtree} |
def typeid_of(category: str) -> int:
"""
Return a type ID matching the deviation category, or zero.
Args:
category: The deviation category.
Returns:
The type ID matching a deviation category, or zero.
"""
# Currently implementing art and journals only.
type_ids = {
... |
def counter(start, stop):
"""The counter function counts down from start to stop when start is bigger
than stop, and counts up from start to stop otherwise."""
x = start
if start > stop:
return_string = "Counting down: "
while x >= stop:
return_string += str(x)
if x != stop:
return_string += ","
x ... |
def obtainDictFromTrueToFitted(dictFitted2True):
"""
This function returns the dictionary from a given true class label to
the cluster label in the fitted clusters, predicted given the model
dictFitted2True = obtainTrueClusterLabel4AllFittedCluster(trueY, fittedY)
Args:
dictFittedToTrue sho... |
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 ... |
def diff(A, B):
""" A - B
"""
return list(set(A).difference(set(B))) |
def _PathsFrom(argv0, runfiles_mf, runfiles_dir, is_runfiles_manifest,
is_runfiles_directory):
"""Discover runfiles manifest and runfiles directory paths.
Args:
argv0: string; the value of sys.argv[0]
runfiles_mf: string; the value of the RUNFILES_MANIFEST_FILE environment
variable
... |
def sortedSquaredArrayNormal(array):
""" This function takes in a sorted array and return another sorted array
which is formed by squared of elements in the input array. O(nlogn) time complexity
and O(n) space complexity.
args:
---------
array : sorted array with numbers
output:
---------
array : which cons... |
def solution(n):
"""Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
3
>>> solution(10)
23
>>> solution(600)
83700
"""
a = 3
result = 0
while a < n:
if a % 3 == 0 or a % 5 == 0:
result += a
elif a ... |
def dict_merge(d1, d2, keys=None):
"""
Merge items of d2 to d1. if keys is None, merge all keys in d2.
:param keys|str,list: the keys to be merged.
"""
if keys is None:
for r in d2:
d1[r] = d2[r]
else:
if type(keys) == str:
keys = [keys]... |
def foo1(x, *args, **kwargs):
"""
foo1
:param x:
:param args:
:param kwargs:
:return:
"""
kwargs['name'] = 'Alice'
new_args = args + ('extra', )
# bar(x, *new_args, **kwargs)
return True |
def adaptive_name(template, vm_set, index):
"""
A helper function for interface/bridge name calculation.
Since the name of interface must be less than 15 bytes. This util is to adjust the template automatically
according to the length of vm_set name and port index. The leading characters (inje, muxy, mb... |
def _get_request_add_conditional_format(rule):
"""
Get request to conditionally format cells.
:param rule: dict form of rule to format cells.
:return: dict form of request.
"""
request = {
"addConditionalFormatRule": {
"rule": rule,
'index': 0
}
}
... |
def _subtract_clip(x, y):
"""Subtract y from x and clip to non-negative values.
Retains numerical type of x and y without introducing underflows.
"""
result = (x > y) * (x - y)
return result |
def genomic_dup4_abs_37(genomic_dup4_37_loc):
"""Create test fixture relative copy number variation"""
return {
"type": "AbsoluteCopyNumber",
"_id": "ga4gh:VAC.CYSRgw_prwhAhTZGM9blaEvmDjj952Uf",
"subject": genomic_dup4_37_loc,
"copies": {"type": "Number", "value": 3}
} |
def dict_patch(path, value):
"""Return dictionary patch.
Used for merging.
"""
if not path:
return value
if isinstance(path, str):
path = path.split(".")
curr = result = {}
for k in path[:-1]:
curr[k] = {}
curr = curr[k]
curr[path[-1]] = value
retu... |
def flatten_package_lock_dependencies(package_lock_dependencies):
"""
Flattens package.lock dependencies
:param package_lock_dependencies:
:return: tuple(flat_array, dep_mapping)
WHERE
array flat_array is a flat array of all dependencies
dict dep_mapping is a tree representing nested depe... |
def get_enduses_with_dummy_tech(enduse_tech_p_by):
"""Find all enduses with defined dummy technologies
Parameters
----------
enduse_tech_p_by : dict
Fuel share definition of technologies
Return
------
dummy_enduses : list
List with all endueses with dummy technologies
"... |
def _AppendIf(container, condition, value):
"""Appends to a list if a condition evaluates to truth.
"""
if condition:
container.append(value)
return condition |
def row_indices_snake(row, x_dimension):
"""Obtain the indices in a row from left to right in the
2-d snake ordering."""
indices = range(row * x_dimension, (row + 1) * x_dimension)
if row % 2 != 0:
indices = reversed(indices)
return list(indices) |
def multimodalcompute(models, train_x):
"""Compute encoded representation for each modality in train_x using encoders in models.
Args:
models (list): List of encoder instances
train_x (List): List of Input Tensors
Returns:
List: List of encoded tensors
"""
outs = []
for... |
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... |
def first(L):
"""
"""
for (n,l) in enumerate(L):
if l:
return n
return None |
def valid_page_name(page):
"""
Checks for valid mainspace Wikipedia page name
Args:
page: The page name to validate
Returns:
True if `page` is valid, False otherwise
"""
NON_MAINSPACE = ['File:',
'File talk:',
'Wikipedia:',
... |
def parse_arxiv_url(url):
"""
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id (1512.08756) and the version (2)
"""
ix = url.rfind('/')
idversion = url[ix+1:] # extract just the id (and the version)
parts = idversion.split('v')
if len(parts) > 2:
raise... |
def observable_extract_properties(observable):
"""Extracts properties from observable"""
result = {}
title = next((c for c in observable if c.name == 'Title'), None)
if title is not None:
title = title.text
result['stix_title'] = title
description = next((c for c in observable if c... |
def filter_clippables(clippables, eaf_wav_files, eaf_creators):
"""We have multiple EAFs for some wavs. When this is the case, only use
the one that is in the EAF creators metadata."""
new_clippables = []
has_metadata = {}
# Find out which wav regions we have metadata for
for eaf_file, start, ... |
def get_folder_data(folder):
""" Extracts existing permissions on folder """
folder_data = {}
folder_data["folderId"] = folder["id"]
folder_data["rootDefaultFolder"] = folder["defaultFolder"]
folder_data["rootDefaultStore"] = folder["defaultStore"]
folder_tenants = []
default_store = []
... |
def _get_exported_include_tree(dep):
"""
Generate the exported thrift source includes target use for the given
thrift library target.
"""
return dep + "-thrift-includes" |
def validate_password(password):
"""
ensure that any input password is at least length 6, has at least one upper case,
at least one lower case, and at least one special character
:param password: the password of the user
:return: returns True if the password is valid, False otherwise
"""
spe... |
def add_etherpad_urls (event_data):
""" Add item etherpad_urls"""
event_id = event_data['id']
# query our database or
#etherpad_urls = find_etherpad_urls(event_id)
#event_data['etherpad_urls'] = etherpad_urls
return event_data |
def a_to_i(text):
"""
Converts a string to an int if possible
:param text: str to possibly be converted
:return: either int (if text could be converted) or the same str back
"""
return int(text) if text.isdigit() else text |
def get_function_name(stack_outputs, function_logical_id):
"""Obtains the function name from given stack outputs.
:type stack_outputs: dict
:param stack_outputs: CloudFormation stack outputs.
:type function_logical_id: str
:param function_logical_id: logical ID of the function resource.
:rtyp... |
def equivalent_mod(a: int, b: int, n: int) -> bool:
"""Return whether a is equivalent to b modulo n.
You can compute this by comparing remainders.
Preconditions:
- n >= 1
>>> equivalent_mod(10, 66, 4) # Both have remainder 2
True
>>> equivalent_mod(13, 19, 5)
False
"""
re... |
def is_equal_to_as_set(l1, l2):
""" return true if two lists contain the same content
:param l1: first list
:param l2: second list
:return: whether lists match
"""
# Note specifically that set(l1) == set(l2) does not work as expected.
return len(set(l1).symmetric_difference(set(l2))) == 0 |
def list2pairs(l):
"""
Turns any list with N items into a list of (N-1) pairs of consecutive items.
"""
res = []
for i in range(len(l)-1):
res.append((l[i], l[i+1]))
return res |
def retrieve_tree(i):
"""
(function) retrieve_tree
------------------------
Retrieve the tree
Parameter
---------
- i : tree index
Return
------
- selected tree
"""
tree_list = [{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}},
{'no surf... |
def deriv(y, t, Delta, beta, mu, epsilon,gamma,alpha,delta):
"""
This function contains a system of equations for the S.E.I.R. model assuming non constant population
death (natural and due infection) and birth rates, as well as reinfection post recovery.
Args:
y (array): contains five f... |
def list_to_dict(_list):
"""Converts a list of dicts into a dict of dicts using the 'Name' key
from the dicts in the list as the key for the dict in the dict of dicts"""
_dict = {}
for item in _list:
if type(item) == dict:
_dict[item["Name"]] = item
else:
_dict[i... |
def as_dict(maybe_element, key):
"""helps to regularize input into a dict.
if ``maybe_element`` is not a dict, will return a dict with single
key as ``{key:maybe_element}``, else will return ``maybe_element``.
Args:
maybe_element: a dict or any object.
key : the sole key.
Returns:... |
def flatten(lists):
"""
flatten a list of lists
"""
result = []
for sublist in lists:
result += sublist
return result |
def MJD_to_Julian_Epoch(MJD):
"""
MJD_to_Julian_Epoch(MJD):
Convert Modified Julian Date (MJD) to Julian Epoch
"""
return 2000.0 + (MJD-51544.5)/365.25 |
def container_name_for(image, application_id):
"""
Get a name for a service container based on image and application ID
Parameters:
image - image that the container is for
application_id - application id that the container is for
Return value:
A string
"""
return image.... |
def flatten(l):
"""
inefficiently flattens a list
l: an arbitrary list
"""
if not l:
return l
if isinstance(l[0], list):
return flatten(l[0]) + flatten(l[1:])
return [l[0]] + flatten(l[1:]) |
def utc2event(utc):
"""
given utc string returns list with year,month,day,hour,minute,second
"""
# last part usually either Z(ulu) or UTC, if not fails
if utc[-3:] == "UTC":
utc = utc[:-2]
elif utc[-1:] == "Z":
pass
else:
raise Exception(
"Cannot handle ti... |
def celery_bug_fix(*args, **kwargs):
"""
celery chords only correctly handle errors with at least 2 tasks,
so we append a celery_bug_fix task.
https://github.com/celery/celery/issues/3709
"""
return [0, None, None] |
def add(X, value):
"""Add `value` to all elements of `X`"""
return [[a + value for a in row] for row in X] |
def return_new_bin(val):
"""
return new bin value
"""
if val < 3:
return 'a'
elif val < 10:
return 'b'
elif val < 20:
return 'c'
elif val < 30:
return 'd'
elif val < 50:
return 'e'
elif val < 200:
return 'f'
else:
retu... |
def calc_t_exp(n_int, t_ramp):
"""Calculates exposure time (or photon collection duration as told by APT.)
Parameters
----------
n_int : int
Integrations per exposure.
t_ramp : float
Ramp time (in seconds).
Returns
-------
t_exp : float
Exposure time (in seconds... |
def int_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval .
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
An int that... |
def powerlaw(wave, tau_v=1, alpha=1.0, **kwargs):
"""Simple power-law attenuation, normalized to 5500\AA.
:param wave:
The wavelengths at which optical depth estimates are desired.
:param tau_v: (default: 1)
The optical depth at 5500\AA, used to normalize the
attenuation curve.
... |
def acct(st1, yt1, t):
"""returns smoothed accumulation for a t-period total and incremental value"""
return st1 - st1 / t + yt1 |
def finvalue(cm, vi):
"""cm = coefficient multiplicateur vf = valeur finale vi = valeur initiale calcule la valeur finale"""
vf = cm * vi
return vf |
def countingValleys(steps, path):
"""
Args:
steps (int): len of the path.
path (str): string with Ds/Us.
Returns:
int: number of valleys"""
del steps
current_height = 0
valleys = 0
# loop over steps and update current height
for step in path:
if step == '... |
def GroupTestsForShard(num_of_shards, test_classes):
"""Groups tests that will be ran on each shard.
Args:
num_of_shards: number of shards to split tests between.
test_classes: A list of test_class files in the jar.
Return:
Returns a dictionary containing a list of test classes.
"""
test_dict = ... |
def _format_time(time_us):
"""Defines how to format time in FunctionEvent"""
US_IN_SECOND = 1000.0 * 1000.0
US_IN_MS = 1000.0
if time_us >= US_IN_SECOND:
return '{:.3f}s'.format(time_us / US_IN_SECOND)
if time_us >= US_IN_MS:
return '{:.3f}ms'.format(time_us / US_IN_MS)
return '{... |
def find_host(name):
"""Check if an entry already exists in /etc/hosts."""
hosts = open("/etc/hosts", "r")
for line in hosts:
if name in line:
return True
return False |
def bu_to_cm(x):
"""Convert blender units to cm."""
return x * 100.0 if x is not None else x |
def get_column_categories(data, index):
"""
Get distinct values of column
"""
return list(set(map(lambda item: item[index], data))) |
def zenodo_project_download_helper(is_record, project_name, project_helper, files):
"""
Downloads a full project from Zenodo and returns the expected list of dictionaries.
Parameters
----------
is_record : bool
Flag for if the resource is a published record
project_name : str
Th... |
def unhappy_f_point(list, index, other_index):
"""
Checks if a new point will be unhappy. Returns False if will be happy.
"""
if list[other_index] == 1:
list[other_index] = 0
else:
list[other_index] = 1
if list[index] != list[index - 1] or list[index] != list[(index + 1... |
def is_merc_projection(srs):
""" Return true if the map projection matches that used by VEarth, Google, OSM, etc.
Is currently necessary for zoom-level shorthand for scale-denominator.
"""
if srs.lower() == '+init=epsg:900913':
return True
# observed
srs = dict([p.split('=') fo... |
def rectangular_wetted_perimeter(width, height):
"""Returns rectangular wetted perimeter in open channel.
:param width: width of rectangular channel
:param height: height of water in open channel
"""
return width + 2 * height |
def total_probability(fixed_symbol: str, varying_symbol_template: str, n: int, start_at: int = 1) -> str:
"""
Returns a string for law of total probability.
**Parameters**
- `fixed_symbol`: str
The symbol that stays the same in the summation.
- `varying_symbol_template`: str
A t... |
def get_variants(category):
"""Provides the different data variants"""
variants = [
"cum",
"cum_rel_popmio",
"cum_rel_pop100k",
"diff",
"diff_rel_popmio",
"diff_rel_pop100k",
"diff_ma1w",
"diff_rel_popmio_ma1w",
"diff_rel_pop100k_ma1w",
... |
def extract_thread_ts(link):
"""
Get the thread timestamp from the message link
:param link: permalink of the message
:return: return the thread timestamp string
"""
if "thread" in link:
return link[-16:]
else:
return None |
def capitalize(words):
"""Capitalize every string in ``words``.
"""
return list(w[0].capitalize() + w[1:] for w in words) |
def euler_problem_1(n=1000):
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
# compute the number of such multiples in three sets
num_multiples_of_3 =... |
def create_test_statements(length=1) -> dict:
"""Assists with the creation of policy statements for testing"""
statement = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": [
"fake:action"
],
... |
def get_x_scale(xcoordinatemin, xcoordinatemax, xpixelmin, xpixelmax):
"""
Establishes the scaling from pixels to x axis units. Can also be used for the y scaling, with all 'x'
in input variables replaced with their 'y' counterparts
:param xcoordinatemin: number, minimum x (or y) value (from input image... |
def prefix_sub(instr):
"""
Remove x86 instruction prefix
:param instr: instruction string
"""
return instr.replace('lock ', '') if 'lock ' in instr else instr |
def _get_pairs(word):
"""
Return set of symbol pairs in a word.
word is represented as tuple of symbols (symbols being variable-length strings)
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs |
def flatten(
gtype: str ) -> str:
"""
"""
if gtype == 'MultiPoint':
return 'Point'
if gtype == 'MultiLineString':
return 'LineString'
if gtype == 'MultiPolygon':
return 'Polygon'
return gtype |
def format_unix_time(unix_time, style=None):
"""
Formats unix time to Discord'stimestamp markdown format.
For formatting details please check out ``TIMESTAMP_STYLES``, which contains the usable styles.
Parameters
----------
unix_time : `int`
The datetime to format.
style :... |
def parse_chocophlan_gene_indexes(annotation_gene_index):
""" Parse the chocophlan gene index input """
# Update the chocophlan gene indexes
chocophlan_gene_indexes = []
for index in annotation_gene_index.split(","):
# Look for array range
if ":" in index:
split_index = inde... |
def create_vocab(
lines, vocab_file, min_frequency=3, special_symbols=["[PAD]", "[SEP]", "[CLS]", "[MASK]", "[UNK]"],
):
"""Create vocabulary from lines"""
# Count word occurency
vocab = {}
for line in lines:
if line.strip():
for w in line.strip().split():
if w in... |
def _is_int(value):
""" Check whether a value is an int or not.
"""
try:
if (str(value).isdigit() or
(len(str(value)) > 1 and str(value)[0] == '-' and
str(value)[1:].isdigit()) or
int(value) == value):
return True
return False
... |
def get_nr_to_check(selection, line_scores):
"""
Gets the number of checks the annotators should do given a selection and a line_score
:param selection: selection of the lines to check
:param line_scores: the lines with the given score
:return: the number of checks that still need to be performed
... |
def slice_len(s):
"""Compute the 'length' of a slice, i.e. stop - start.
Args:
s (slice): Slice object.
Raises:
ValueError: If `s` has a step other than 1 or None.
ValueError: If `s` is decreasing.
"""
if s.step not in (None, 1):
raise ValueError("Slices may not de... |
def _float(item, default=0.0):
"""_float
Args:
item (Any): item
default (float, optional): default
Returns:
float: item in float type
"""
if isinstance(item, float):
return item
if item == 'null':
return 0.0
if item == 'false':
return 0.0
... |
def cap_sentence(string):
"""
Capitalize first letter of each word in string.
"""
return ' '.join(word[:1].upper() + word[1:] for word in string.split(' ')) |
def configurePhiRhoZ(depth, resln=1.0):
"""configurePhiRhoZ(depth)
Add a phi(rho*z) detector with the specified z dimension in meters."""
return { 'PhiRhoZ' : depth, 'resln': resln} |
def calculate_date(offset):
"""
:param offset:
:return:
"""
import datetime
from datetime import timedelta
calculated_date = datetime.datetime(1970,1,1)
endDate = calculated_date + timedelta(days=int(offset))
iso_date = endDate.isoformat()
return iso_date |
def create_callback_data(button_type,category):
""" Create the callback data associated to each button"""
return ";".join([button_type,category]) |
def apriori_generate(Lk, k):
"""
Takes a list of frequent itemsets, Lk
and the size of the sets, to produce
candidate itemsets.
"""
return_list = []
len_Lk = len(Lk)
for i in range(len_Lk):
for j in range(i + 1, len_Lk):
L1 = list(Lk[i])[:k - 2]
L2 = list(... |
def indent(text, indentation):
"""Indents a string of text with the given string of indentation.
PARAMETERS:
text -- str
indentation -- str; prefix of indentation to add to the front of
every new line.
RETURNS:
str; the newly indented string.
"""
return '\n'.j... |
def signature_for_type_name(type_name):
"""Determine the JNI signature for a given single data type.
This means a one character representation for primitives, and an
L<class name>; representation for classes (including String).
"""
if type_name == b'void':
return b'V'
elif type_name == b... |
def evidence(var, e, outcomeSpace):
"""
argument
`var`, a valid variable identifier.
`e`, the observed value for var.
`outcomeSpace`, dictionary with the domain of each variable
Returns dictionary with a copy of outcomeSpace with var = e
"""
newOutcomeSpace = outcomeSpace.copy() # Make... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.