content
stringlengths 42
6.51k
|
---|
def tj(a):
""" Tab Join """
return "\t".join(map(lambda i: str(i), a))
|
def build_latex(hyp):
"""
Parameters
----------
hyp : dict
{'segmentation': [[0, 3], [1, 2]],
'symbols': [{'symbol': ID, 'probability': 0.12}],
'geometry': {'symbol': index,
'bottom': None or dict,
'subscript': None or dict,
'right': None or dict,
'superscript': None or dict,
'top': None or dict},
'probability': 0.123
}
"""
latex = []
for symbol in hyp["symbols"]:
latex.append(symbol["symbol"].split(";")[1])
return " ".join(latex)
|
def getHashedBucketEndpoint(endpoint, file_name):
""" Return a hashed bucket endpoint """
# Example:
# endpoint = "atlas_logs", file_name = "log.tgz"
# -> hash = "07" and hashed_endpoint = "atlas_logs_07"
# return endpoint + "_" + getHash(file_name, 2)
return endpoint
|
def pt2px(pt):
"""Crude point to pixel work"""
return int(round(pt * 96.0 / 72))
|
def ApplyFuncs(data, funcs):
"""Takes input data and list of str funcs; evals; applies."""
for f in funcs:
try:
func = eval("lambda x: "+f)
data = func(data)
except Exception as e:
print("Function "+f+" did not evaluate correctly:")
print(e)
print("Skipping.\n"+"-"*79)
return(data)
|
def gini(clusters_labels):
"""Compute the Gini coefficient for a clustering.
Parameters:
- clusters_labels: pd.Series of labels of clusters for each point.
"""
import pandas as pd
# Get frequencies from clusters_labels
clusters_labels = pd.Series(clusters_labels)
frequencies = clusters_labels.value_counts()
# Mean absolute difference
mad = frequencies.mad()
# Mean frequency of clusters
mean = frequencies.mean()
# Gini coefficient
gini_coeff = 0.5 * mad / mean
return gini_coeff
|
def callMultiF(f,n,cache):
"""
Try to get n unique results by calling f() multiple times
>>> import random
>>> random.seed(0)
>>> callMultiF(lambda : random.randint(0,10), 9, set())
[9, 8, 4, 2, 5, 3, 6, 10]
>>> random.seed(0)
>>> callMultiF(lambda : random.randint(0,10), 9, set([8,9,10]))
[4, 2, 5, 3, 6, 7]
"""
rs = []
rs_s = set()
if cache:
for c in cache: rs_s.add(c)
for _ in range(n):
c = f()
c_iter = 0
while c in rs_s and c_iter < 3:
c_iter += 1
c = f()
if c not in rs_s:
rs_s.add(c)
rs.append(c)
assert len(rs) <= n
return rs
|
def _get_hamming_distance(a, b):
"""Calculates hamming distance between strings of equal length."""
distance = 0
for char_a, char_b in zip(a, b):
if char_a != char_b:
distance += 1
return distance
|
def apply_cushion(x0, x1, cushion):
"""
x0, x1: ints, x coordinates of corners.
cushion: float, how much leniancy to give.
"""
if x0 < x1:
x0 += cushion
x1 -= cushion
else:
x0 -= cushion
x1 += cushion
return x0, x1
|
def choose_mrna(mrna1, mrna2, min_identity, max_ratio_diff, blast_dict):
"""
"""
best_mrna = None
best_mrna_length = 0
for mrna in [mrna1, mrna2]:
if not mrna:
continue
if mrna not in blast_dict:
continue
transcript_name = mrna.split(".mrna")[0]
# if the best match is a protein from another transcript - disqualify
if transcript_name != blast_dict[mrna]["sseqid"]:
continue
perc_identity = blast_dict[mrna]["pident"]
# if protein is too different from the ref protein
if perc_identity < min_identity:
continue
qlen = blast_dict[mrna]["qlen"]
slen = blast_dict[mrna]["slen"]
# if query and subject lengths are too different
if not (1 - max_ratio_diff < slen/qlen < 1 + max_ratio_diff):
continue
if best_mrna and blast_dict[mrna]["bitscore"] < blast_dict[best_mrna]["bitscore"]:
continue
# if we get here, it means this is the best mRNA so far
best_mrna = mrna
return best_mrna
|
def beta(R0, gamma, prob_symptoms, rho):
"""
R0 from model parameters.
"""
Qs = prob_symptoms
return R0 * gamma / (Qs + (1 - Qs) * rho)
|
def sort_by_key_asc(my_list=[], keys=[]):
"""
Reorder your list ASC based on multiple keys
Parameters:
:param (list) my_list: list of objects you want to order
[{'code': 'beta', 'number': 3}, {'code': 'delta', 'number': 2}]
:param (list) keys: list of keys and direction to order.
eg: ['code', 'number']
Returns:
:return (list) my_list: your list reordered
"""
if keys:
first = keys[0]
remaining = keys[1:]
presorted_list = sort_by_key_asc(my_list, remaining)
return sorted(presorted_list, key=lambda row: row[first], reverse=False)
else:
return my_list
|
def get_table_position(screen_layout):
""" return first position of table encountered within screen layout
"""
for _, data in screen_layout.items():
if data.get('table'):
return data['position']
return None
|
def font_size_picker(button_name, input):
"""
description:
- Increase font for highlited button
:param buttonname: the button to be determined wheter to be bigger or not
:param game_state: the button to be highlighted
:return: int font size
"""
if button_name == "move_left" and input == 1:
return 20*1.2
elif button_name == "move_right" and input == 2:
return 20*1.2
elif button_name == "do_pause" and input == 3:
return 20*1.2
elif button_name == "difficulty" and input == 4:
return 20*1.2
elif button_name == "shoot_ball" and input == 5:
return 20*1.2
else:
return 20
|
def _reverse_ordering(ordering_tuple):
"""
Given an order_by tuple such as `('-created', 'uuid')` reverse the
ordering and return a new tuple, eg. `('created', '-uuid')`.
"""
def invert(x):
return x[1:] if (x.startswith('-')) else '-' + x
return tuple([invert(item) for item in ordering_tuple])
|
def prime_factors(n):
"""
GCD algorithm to produce prime factors of `n`
Parameters
----------
n : int
The number to factorize.
Returns
-------
list
The prime factors of `n`.
"""
i = 2; factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
|
def compare_queryset(first, second):
"""
Simple compare two querysets (used for many-to-many field compare)
XXX: resort results?
"""
result = []
for item in set(first).union(set(second)):
if item not in first: # item was inserted
item.insert = True
elif item not in second: # item was deleted
item.delete = True
result.append(item)
return result
|
def xmlbool(bool):
"""Convert a boolean into the string expected by the elfweaver XML."""
# Is there a smarter way of doing this?
if bool:
return "true"
else:
return "false"
|
def in_array(array1, array2):
"""This function is the solution to the Codewars Which are in? Kata that
can be found at:
https://www.codewars.com/kata/550554fd08b86f84fe000a58/train/python"""
words_in_array = set()
for word_from_array2 in array2:
for word_from_array1 in array1:
if word_from_array1 in word_from_array2:
words_in_array.add(word_from_array1)
return sorted(words_in_array)
|
def mad_quote(value):
"""Add quotes to a string value."""
if '"' not in value:
return '"' + value + '"'
if "'" not in value:
return "'" + value + "'"
# MAD-X doesn't do any unescaping (otherwise I'd simply use `json.dumps`):
raise ValueError("MAD-X unable to parse string with escaped quotes: {!r}"
.format(value))
|
def fileno(file_or_fd):
"""Return a file descriptor from a file descriptor or file object."""
fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
if not isinstance(fd, int):
raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
return fd
|
def _check_eftype(eftype):
"""Check validity of eftype"""
if eftype.lower() in ['none', 'hedges', 'cohen', 'glass', 'r',
'eta-square', 'odds-ratio', 'auc']:
return True
else:
return False
|
def v1_deep_add(lists):
"""Return sum of values in given list, iterating deeply."""
total = 0
lists = list(lists)
while lists:
item = lists.pop()
if isinstance(item, list):
lists.extend(item)
else:
total += item
return total
|
def _change_controller_type(raid_config, type):
"""Typecast the controller values to requested type
:param raid_config: The dictionary containing the requested
RAID configuration.
:param type: Requested type for the typecast
:returns raid_config: The modified raid_config with typecasted
controller value.
"""
for ld in raid_config['logical_disks']:
if 'controller' in ld.keys():
ld['controller'] = type(ld['controller'])
return raid_config
|
def sumatoria_gauss(n: int) -> int:
"""CHALLENGE OPCIONAL: Re-Escribir utilizando suma de Gauss.
Referencia: https://es.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF
"""
return n * (n + 1) // 2
|
def split_forward_slash_value(value, default):
"""
Returns '<default>/<value>' if value does not contain '/', otherwise
'<token1>/<token2>'
"""
if '/' in value:
return tuple(value.split('/', 1))
return default, value
|
def safe_repr(obj, limit=1000):
""" Find the repr of the object, but limit the number of characters.
"""
r = repr(obj)
if len(r) > limit:
hlimit = limit // 2
r = '%s ... %s' % (r[:hlimit], r[-hlimit:])
return r
|
def root_equals(col: str, val: str) -> str:
"""Return a string that has col = val."""
return f"{col} = {val}"
|
def _parse_conll_identifier(
value: str, line: int, field: str, *, non_zero=False
) -> int:
"""Parse a CoNLL token identifier, raise the appropriate exception if it is invalid.
Just propagate the exception if `value` does not parse to an integer.
If `non_zero` is truthy, raise an exception if `value` is zero.
`field` and `line` are only used for the error message."""
res = int(value)
if res < 0:
raise ValueError(
"At line {line}, the `{field}` field must be a non-negative integer, got {value!r}".format(
line=line, field=field, value=value
)
)
elif non_zero and res == 0:
raise ValueError(
"At line {line}, the `{field}` field must be a positive integer, got {value!r}".format(
line=line, field=field, value=value
)
)
return res
|
def generate_hosts_inventory(json_inventory):
"""Build a dictionary of hosts and associated groups from a Ansible JSON inventory file as keys.
Args:
json_inventory (dict): A dictionary object representing a Ansible JSON inventory file.
Returns:
dict(list): A dictionary of hosts with each host having a list of associated groups.
{ 'host_name': ['group1', 'group2'] }
"""
inventory_child_groups = {}
try:
inventory_hosts = {k: set() for k in json_inventory['_meta']['hostvars'].keys()}
inventory_groups = {k: v for (k, v) in json_inventory.items() if k != '_meta'}
except KeyError:
raise RuntimeError('Expected key(s) missing from inventory file! ("_meta", hostvars")')
for group_name, group_info in inventory_groups.items():
if 'children' in group_info and len(group_info['children']) > 0:
for child in group_info['children']:
if child in inventory_child_groups.keys():
inventory_child_groups[child].add(group_name)
else:
inventory_child_groups[child] = {group_name}
for group_name, group_info in inventory_groups.items():
if 'hosts' in group_info.keys():
for host in group_info['hosts']:
inventory_hosts[host].add(group_name)
if group_name in inventory_child_groups.keys():
inventory_hosts[host].update(inventory_child_groups[group_name])
return inventory_hosts
|
def different_ways_tabulation(n):
"""Tabulation implementation of different ways, O(n) time and O(n) space pre-allocated"""
# build array such that d[i] = # ways to write i as sum of 1s, 3s, and 4s
d = [0] * (n + 1)
# d allows us to define D0 = 1 as above, but we cannot represent Dn = 0 for negative n in d, thus we need different
# base cases. consider the following that have Dn n<0 on the RHS:
# D1 = D0 + D-2 + D-3 => we know D1 = 1 (1 = 1), add this as a base case
# D2 = D1 + D-1 + D-2 => we know D2 = 1 (1 + 1 = 2), add this as a base case
# D3 = D2 + D0 + D-1 => we know D3 = 2 (1 + 1 + 1 = 3, 3 = 3) add this as a base case
# we can express Dn for n >= 4 without negative numbers, example:
# D4 = D0 + D1 + D3 = 1 + 1 + 2 (1 way if xk = 4 i.e. when x1 + ... + xk-1 = 0, 1 way if xk = 3 i.e. when x1 + ...
# + xk-1 = 1, 2 ways if xk = 1 i.e. when x1 + ... + xk-1 = 3)
# thus we now have 4 base cases (which is the minimum here)
d[0] = 1
d[1] = 1
d[2] = 1
d[3] = 2
# now we can derive from d Di for 4 <= i <= n with our recursive step
for i in range(4, n + 1):
d[i] = d[i - 1] + d[i - 3] + d[i - 4]
return d[n]
|
def _round_up_div(a: int, b: int) -> int:
"""Divide by b and round up to a multiple of b"""
return (a + b - 1) // b
|
def left_rotate(n, b):
"""Left rotate a 32-bit integer n by b bits."""
return ((n << b) | (n >> (32 - b))) & 0xffffffff
|
def square_and_multiply(x, k, p=None):
"""
Square and Multiply Algorithm
Parameters: positive integer x and integer exponent k,
optional modulus p
Returns: x**k or x**k mod p when p is given
"""
b = bin(k).lstrip('0b')
r = 1
for i in b:
r = r ** 2
if i == '1':
r = r * x
if p:
r %= p
return r
|
def load_file(file_path):
"""Load the contents of a file into a string"""
try:
with open(file_path, 'r') as file:
return file.read()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None
|
def editdistance(seq1, seq2):
"""Calculate the Levenshtein edit-distance between two strings.
The edit distance is the number of characters that need to be substituted,
inserted, or deleted, to transform seq1 into seq2. For example,
transforming 'rain' to 'shine' requires three steps, consisting of two
substitutions and one insertion: 'rain' -> 'sain' -> 'shin' -> 'shine'.
These operations could have been done in other orders, but at least three
steps are needed."""
# initialize 2-D array to zero
len1, len2 = len(seq1), len(seq2)
lev = [[0] * (len2 + 1) for _ in range(len1 + 1)]
for i in range(len1 + 1):
lev[i][0] = i # column 0: 0,1,2,3,4,...
for j in range(len2 + 1):
lev[0][j] = j # row 0: 0,1,2,3,4,...
# iterate over the array
for i in range(len1):
for j in range(len2):
a = lev[i][j + 1] + 1 # skip seq1[i]
b = lev[i][j] + (seq1[i] != seq2[j]) # match seq1[i] with seq2[j]
c = lev[i + 1][j] + 1 # skip seq2[j]
lev[i + 1][j + 1] = min(a, b, c) # pick the cheapest
return lev[len1][len2]
|
def score_style(polarity_value):
"""
Returns colour of score progress bar based on polarity score.
:param polarity_value: the polarity
:return color: the colour of the progress bar
"""
color = 'warning'
if polarity_value < 33:
color = 'danger'
if polarity_value > 66:
color = 'success'
return color
|
def press_Davison_1968(t_k):
"""From Davison
Parameters
----------
t_k, K
Returns
-------
Vapor pressure, Pa
References
----------
Davison, H.W.
"Complication of Thermophysical Properties of Liquid Lithium."
NASA Technical Note TN D-4650. Cleveland, Ohio: Lewis Research Center, July 1968.
Notes
-----
"With this equation the data shown in figure 8 are correlated
with a standard deviation of 3.38 percent. The maximum deviation
of -32.6 percent occurred at a vapor pressure of about 6 Pa."
The plot Figure 8 shows 800 to 1800 K so we can take that as the applicable range.
"""
return 10**(10.015 - 8064.5 / t_k)
|
def strip_quotes(text) -> str:
"""
Strips starting and trailing quotes from input string
:param text: Text string to strip the quotes from.
:return: Text string without quotes.
"""
if text is None:
return ""
l = len(text)
if l == 0:
return text
start = 0 if text[0] != "'" and text[0] != '"' else 1
end = l if text[l-1] != "'" and text[l-1] != '"' else l-1
return text[start:end]
|
def convert_service_banner_json(json):
"""Convert json file to string if supplied with custom banner json file."""
# open json file
with open(json, "r") as j:
json_string = j.read()
return json_string
|
def get_site_ends_distance(s1, e1, s2, e2):
"""
Get nearest distance between two site ends / starts.
>>> get_site_ends_distance(100, 120, 130, 150)
10
>>> get_site_ends_distance(130, 150, 100, 120)
10
>>> get_site_ends_distance(100, 120, 120, 140)
0
>>> get_site_ends_distance(120, 140, 110, 160)
0
"""
diff1 = s2 - e1
diff2 = s1 - e2
dist = diff2
if diff1 >= diff2:
dist = diff1
if diff1 <= 0 and diff2 <= 0:
dist = 0
return dist
|
def compose_dict_obj(raw_data, keys, search_words):
"""
Return a dictionary of selected keys from raw_data
"""
d = {}
for key in keys:
if key == "keyword":
d[key] = search_words
else:
d[key] = raw_data.get(key)
return d
|
def node_available(node):
""" Return true if the node can append a child
"""
if node is None:
return False
return node.status == 'OK' and (not node.left or not node.right)
|
def fnSeconds_To_Hours(time_period):
"""
Convert from seconds to hours, minutes and seconds.
Date: 16 October 2016
originally in AstroFunctions.py
"""
num_hrs = int(time_period/(60.*60.));
time_period =time_period - num_hrs*60.*60.;
num_mins = int(time_period/60.);
num_secs = time_period - num_mins*60.;
return num_hrs,num_mins,num_secs
|
def strip_num(word : str):
"""Returns the word, without numerical chars at the beginning"""
i =0
while i<len(word) and word[i].isnumeric():
i+=1
return word[i:]
|
def upper_lower_none(arg):
"""Validate arg value as "upper", "lower", or None."""
if not arg:
return arg
arg = arg.strip().lower()
if arg in ["upper", "lower"]:
return arg
raise ValueError('argument must be "upper", "lower" or None')
|
def importString(import_name):
"""Imports an object based on a string.
The string can be either a module name and an object name, separated
by a colon, or a (potentially dotted) module name.
"""
if ':' in import_name:
modname, obj = import_name.split(':', 1)
elif '.' in import_name:
modname, obj = import_name.rsplit('.', 1)
else:
modname, obj = import_name, None
fromlist = [obj] if obj else []
try:
mod = __import__(modname, {}, {}, fromlist)
except ImportError as err:
raise ImportError(
'Could not import %r: %s' % (import_name, err)) from err
if not obj:
return mod
else:
return getattr(mod, obj)
|
def replace_variable_in_value(value, variable, replacement):
""" Replace variable in value string with replacement string
"""
return value.replace(variable, replacement)
|
def check5(n, p):
"""
Return a bool. Check if a set of measurements can apply normal approximation.
"""
return n * p > 5 and n * (1 - p) > 5
|
def find_metadata_item(metadata_items, key_name):
""" Finds a metadata entry by the key name. """
for item in metadata_items:
if item['key'] == key_name:
return item
return None
|
def dict_as_tuples(dct):
"""Transforms a dict to a choices list of tuples."""
lst = []
for key in dct.keys():
lst.append((key, dct[key]))
return lst
|
def add_fracs_for(n):
"""
Returns the sum of the fractions 1/1 + 1/2 + ... + 1/n
Parameter n: The number of fractions to add
Precondition: n is an int > 0
"""
# Accumulator
v = 0 # call this 1/0 for today
for i in range(1,n+1):
v = v + 1.0 / i
return v
|
def solve_substring_with_precedence(text):
"""
Same as 'solve_substring' but read the addition first
:param str text: A flat equation to solve
:return: The result of the given equation
:rtype: int
"""
text = text.replace("(", "")
text = text.replace(")", "")
inputs = text.split(" ")
while len(inputs) > 1:
if "+" in inputs:
i = inputs.index("+")
value = int(inputs[i - 1]) + int(inputs[i + 1])
else:
i = inputs.index("*")
value = int(inputs[i - 1]) * int(inputs[i + 1])
inputs.pop(i + 1)
inputs.pop(i)
inputs.pop(i - 1)
inputs.insert(i - 1, value)
return int(inputs[0])
|
def tcl_delta_filename(curef, fvver, tvver, filename, original=True):
"""
Generate compatible filenames for deltas, if needed.
:param curef: PRD of the phone variant to check.
:type curef: str
:param fvver: Initial software version.
:type fvver: str
:param tvver: Target software version.
:type tvver: str
:param filename: File name from download URL, passed through if not changing filename.
:type filename: str
:param original: If we'll download the file with its original filename. Default is True.
:type original: bool
"""
if not original:
prdver = curef.split("-")[1]
filename = "JSU_PRD-{0}-{1}to{2}.zip".format(prdver, fvver, tvver)
return filename
|
def parse_soil_code(s):
"""
Function to parse the soil code.
:param s: (str) String with the soil code.
:return: Soil code.
"""
return s.replace("'", "")
|
def ordered_sample(population, sample_size):
"""
Samples the population, taking the first `n` items (a.k.a `sample_size') encountered. If more samples are
requested than are available then only yield the first `sample_size` items
:param population: An iterator of items to sample
:param sample_size: The number of items to retrieve from the population
:return: A list of the first `sample_size` items from the population
"""
empty = True
results = []
for i, item in enumerate(population):
empty = False
if i >= sample_size:
break
results.append(item)
if empty:
raise ValueError('Population is empty')
return results
|
def find_check_run_by_name(check_runs, name):
""" Search through a list of check runs to see if it contains
a specific check run based on the name.
If the check run is not found this returns 'None'.
Parameters
----------
check_runs : list of dict
An array of check runs. This can be an empty array.
name : str
The name of the check.
Returns
-------
check : dict
The check run that was created for the commit that matches the name
parameter. If no check matches the name, then this is an empty
dict.
"""
for check in check_runs:
if check.get('name') == name:
return check
return None
|
def yesno(value, icaps=True):
"""
Return 'yes' or 'no' according to the (assumed-bool) value.
"""
if (value):
str = 'Yes' if icaps else 'yes'
else:
str = 'No' if icaps else 'no'
return str
|
def get_stats(data):
"""
Returns some statistics about the given data, i.e. the number of unique entities, relations and
their sum.
Args:
data (list): List of relation triples as tuples.
Returns:
tuple: #entities, #relations, #entities + #relations.
"""
entities = set()
relations = set()
for triple in data:
entities.add(triple[0])
entities.add(triple[2])
relations.add(triple[1])
return len(entities), len(relations), len(entities) + len(relations)
|
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('/')
assert ix >= 0, 'bad url: ' + url
idv = url[ix+1:] # extract just the id (and the version)
parts = idv.split('v')
assert len(parts) == 2, 'error splitting id and version in idv string: ' + idv
return idv, parts[0], int(parts[1])
|
def _difftrap1(function, interval):
"""
Perform part of the trapezoidal rule to integrate a function.
Assume that we had called difftrap with all lower powers-of-2
starting with 1. Calling difftrap only returns the summation
of the new ordinates. It does _not_ multiply by the width
of the trapezoids. This must be performed by the caller.
'function' is the function to evaluate (must accept vector arguments).
'interval' is a sequence with lower and upper limits
of integration.
'numtraps' is the number of trapezoids to use (must be a
power-of-2).
"""
return 0.5 * (function(interval[0]) + function(interval[1]))
|
def try_call(func, *args, **kwargs):
"""
Attempts to invoke a function with arguments. If `func` is not callable, then returns `func`
The second return value of this function indicates whether the argument was a callable.
"""
if callable(func):
ret = func(*args, **kwargs)
return ret, True
return func, False
|
def _cons6_77(m6, L66, L67, d_byp, k, Cp, h_byp, dw1, kw1, dw2, kw2,
adiabatic_duct=False, conv_approx=False):
"""dz constrant for edge bypass sc touching 2 corner bypass sc"""
term1_out = 0.0
if not adiabatic_duct:
if conv_approx:
R2 = 1 / h_byp + dw2 / 2 / kw2
term1_out = L66 / m6 / Cp / R2 # conv / cond to duct 2 MW
else:
term1_out = h_byp * L66 / m6 / Cp # conv to outer duct
if conv_approx:
R1 = 1 / h_byp + dw1 / 2 / kw1
term1_in = L66 / m6 / Cp / R1 # conv / cond to duct 1 MW
else:
term1_in = h_byp * L66 / m6 / Cp
term2 = 2 * k * d_byp / m6 / Cp / L67 # cond to adj bypass corner
return 1 / (term1_in + term1_out + term2)
|
def split_list(func, *args):
""" Split args into one list containing all args where func returned True, and rest in the second one. """
one, two = [], []
for arg in args:
if func(arg):
one.append(arg)
else:
two.append(arg)
return one, two
|
def default(x, y, f=None):
"""If y is not None, returns y if f is None, otherwise returns f(y). If y is
None, returns x.
>>> default(1, None, None)
1
>>> default(1, 5, None)
5
>>> default(1, 5, lambda x: x + 1)
6
"""
if y:
if f:
return f(y)
else:
return y
else:
return x
|
def class_name_to_dir_name(class_name):
"""
Replace all spaces with underscores.
:param class_name: Class name string.
:return: Modified class name.
"""
return class_name.replace(" ", "_")
|
def url_part_unescape(urlpart):
"""
reverse url_part_escape
"""
return ''.join(
bytes.fromhex(s).decode('utf-8') if i % 2 else s
for i, s in enumerate(urlpart.split('_'))
)
|
def Int2AP(num):
"""Convert integer to A-P string representation."""
val = b''; AP = b'ABCDEFGHIJKLMNOP'
num = int(abs(num))
while num:
num, mod = divmod(num, 16)
val = AP[mod:mod+1] + val
return val
|
def decode_number(num):
"""
Decodes numbers found in app.xml.
They are of the formats "U:" (undefined), "V:" (void/none?), or
"I:<integer>". Returns None if the number is undefined ("U:") or
an empty string. Raises an exception if the format is otherwise
invalid.
"""
if num == "" or num == "U:":
return None
elif num == "V:": # "void?" use for pointer and unsized arrays
return 0
elif num[0:2] == "I:":
try:
return int(num[2:])
except ValueError:
raise ValueError("Failed to decode (%s) as a number" % num)
else:
raise ValueError("Invalid encoded number (%s)" % num)
|
def _merge_tokens(token_1: str, token_2: str) -> str:
"""Fast, whitespace safe merging of tokens."""
if len(token_2) == 0:
text = token_1
elif len(token_1) == 0:
text = token_2
else:
text = token_1 + " " + token_2
return text
|
def convert_to_milli(val):
"""
Converts a string to milli value in int.
Useful to convert milli values from k8s.
Examples:
convert_to_milli('10m') -> 10
convert_to_milli('10000m') -> 10000
convert_to_milli('1') -> 1000
convert_to_milli('100') -> 100000
"""
if val[-1] == 'm':
return int(val.rstrip('m'))
else:
return 1000 * int(val)
|
def _pprint(params):
"""Pretty print the dictionary 'params'."""
params_list = list()
for i, (k, v) in enumerate(params):
if type(v) is float:
this_repr = '{}={:.4f}'.format(k, v)
else:
this_repr = '{}={}'.format(k, v)
params_list.append(this_repr)
return params_list
|
def flatten(items, seq_types=(list, tuple)):
"""convert nested list to flat list"""
for c, item in enumerate(items):
while c < len(items) and isinstance(items[c], seq_types):
items[c : c + 1] = items[c]
return items
|
def apply_typedef(item, typedef):
"""
This applies isinstance() to item based on typedef.
"""
if isinstance(typedef, (tuple, list)):
typedef_strlist = list(typedef)
elif isinstance(typedef, str):
typedef_strlist = [typedef]
else:
return False
typedef_ok = []
for x in typedef_strlist:
if x == "str":
typedef_ok.append(isinstance(item, str))
elif x == "float":
typedef_ok.append(isinstance(item, float))
elif x == "int":
typedef_ok.append(isinstance(item, int))
elif x == "dict":
typedef_ok.append(isinstance(item, dict))
elif x == "list":
typedef_ok.append(isinstance(item, list))
elif x == "bool":
typedef_ok.append(item is True or item is False)
elif x == "Any":
typedef_ok.append(item is not None)
elif x == "None":
typedef_ok.append(True)
else:
typedef_ok.append(False)
return any(typedef_ok)
|
def escape_lemma(lemma):
"""Format the lemma so it is valid XML id"""
def elc(c):
if (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z'):
return c
elif c == ' ':
return '_'
elif c == '(':
return '-lb-'
elif c == ')':
return '-rb-'
elif c == '\'':
return '-ap-'
elif c == '/':
return '-sl-'
else:
return '-%04x-' % ord(c)
return "".join(elc(c) for c in lemma)
|
def format_parameter_list(parameters):
"""Given an item list or dictionary of matching parameters, return a formatted string.
Typically used to format matching parameters or bestrefs dicts for debug.
"""
items = sorted(dict(parameters).items())
return " ".join(["=".join([key, repr(str(value))]) for (key,value) in items])
|
def remove_suffix(string, suffix):
"""
This function removes the given suffix from a string, if the string does indeed end with the suffix; otherwise,
it returns the original string.
"""
# Special case: if suffix is empty, string[:0] returns ''. So, test for a non-empty suffix.
if suffix and string.endswith(suffix):
return string[:-len(suffix)]
else:
return string
|
def makeFlags(*args):
"""Resolve tuple-like arguments to a list of string.
Parameters
----------
args
List of tuples of the form: [(True, "foo"), (False, "bar")]
Returns
-------
dirname : str
The generated directory name
Examples
--------
>>> makeFlags((True, "foo"), (False, "bar"))
["foo"]
"""
return [name for check, name in args if check]
|
def unlist(nestedList):
"""Take a nested-list as input and return a 1d list of all elements in it"""
import numpy as np
outList = []
for i in nestedList:
if type(i) in (list, np.ndarray):
outList.extend(unlist(i))
else:
outList.append(i)
return outList
|
def neighbors (row, col, nrows, ncols):
"""Returns a list of `(r, c)` 4-neighbors (up, down, left, right) for
`(row, col)`.
Invalid neighbor coordinates outside the range row and column range
`[0, nrows]` or `[0, ncols]`, respectively, will not be returned.
"""
deltas = (-1, 0), (0, -1), (1, 0), (0, 1)
valid = lambda r, c: r in range(0, nrows) and c in range(0, ncols)
return [ (row + r, col + c) for r, c in deltas if valid(row + r, col + c) ]
|
def varintdecode(data):
""" Varint decoding
"""
shift = 0
result = 0
for c in data:
b = ord(c)
result |= ((b & 0x7f) << shift)
if not (b & 0x80):
break
shift += 7
return result
|
def int_func(A):
"""
Defines the interaction term of the target and dark matter particle
Parameters
----------
A : Float
Atomic mass of the detector element.
Returns
-------
Interaction factor.
"""
return(A**2)
|
def separate_type(type_dict):
"""return the type for word and class separately"""
wt_dict = dict()
ct_dict = dict()
for key, v in type_dict.items():
contain_word = key.find('w') != -1
contain_class = key.find('c') != -1
if contain_word and not contain_class:
wt_dict[key] = v
if contain_class and not contain_word:
ct_dict[key] = v
return wt_dict, ct_dict
|
def is_palindromic_phrase(s):
""" (str) -> bool
Return True iff s is a palindrome, ignoring case and non-alphabetic
characters.
>>> is_palindromic_phrase('Appl05-#$elppa')
True
>>> is_palindromic_phrase('Mada123r')
False
"""
result = ''
for i in range(len(s)):
if s[i].isalpha():
result += s[i]
return result.lower() == result.lower()[::-1]
|
def set_show_fps_counter(show: bool) -> dict:
"""Requests that backend shows the FPS counter
Parameters
----------
show: bool
True for showing the FPS counter
"""
return {"method": "Overlay.setShowFPSCounter", "params": {"show": show}}
|
def make_contact_name(contact: dict, include_title: bool = True) -> str:
"""
Create a contact_name string from parts.
Args:
contact (dict): Document from contacts collection.
include_title (bool): Whether to include the title field as a prefix.
Returns:
(str): Contact name string.
"""
if 'name' not in contact:
return 'No Name Provided'
if include_title:
first_index = 0
else:
first_index = 1
return " ".join(list(contact['name'].values())[first_index:-1])
|
def modular_pow(base, exponent, modulus):
"""Computes (base**exponent) % modulus by using the right-to-left binary method."""
if modulus == -1:
return 0
result = 1
base %= modulus
while exponent > 0:
if exponent % 2:
result = (result * base) % modulus
exponent >>= 1
base = (base * base) % modulus
return result
|
def my_hourly_schedule(_context):
"""
A schedule definition. This example schedule runs a pipeline every hour.
For more hints on scheduling pipeline runs in Dagster, see our documentation overview on
Schedules:
https://docs.dagster.io/overview/schedules-sensors/schedules
"""
run_config = {}
return run_config
|
def asInt(val):
"""Converts floats, integers and string representations of integers
(in any base) to integers. Truncates floats.
Raises ValueError or TypeError for all other values
"""
if hasattr(val, "lower"):
# string-like object; force base to 0
return int(val, 0)
else:
# not a string; convert as a number (base cannot be specified)
return int(val)
|
def CreateModelInfo(model_info_d):
"""
model_info_d: (dict)
model_in_use: (str)
"""
mm = model_info_d['model_in_use']
HTML_l = ["<h2> Information on Model: </h2>"]
HTML_l += ["<h3> Using the following given Model:</h3>"]
HTML_l += ["<h4>" + mm.split('/')[-1] + "</h4>"]
HTML_l += ["<h1>--------------------------------------</h1>"]
return "\n".join(HTML_l)
|
def extract_filter_list(filter_list):
"""Helper for isolated script test wrappers. Parses the
--isolated-script-test-filter command line argument. Currently, double-colon
('::') is used as the separator between test names, because a single colon may
be used in the names of perf benchmarks, which contain URLs.
"""
return filter_list.split('::')
|
def visit(h):
"""Converts our bespoke linked list to a python list."""
o = h
l = []
while o is not None:
l.append(o.value)
o = o.next
return l
|
def convert_vface_to_efaces(vfaces):
"""Convert faces given by vertices to faces given by strings (edge faces).
It works for up to 26 edges."""
#list of edges
eds = []
nA = ord("A")
na = ord("a")
faces = []
for ff in vfaces:
#print("ff",ff)
f = ff+[ff[0]]
n = len(f)
e = ""
for i in range(n-1):
aa = f[i]
bb = f[i+1]
a,b = aa,bb
if a > b:
a,b = b,a
if [a,b] not in eds:
eds.append([a,b])
i = eds.index([a,b])
if aa > bb:
e += chr(na+i)
else:
e += chr(nA+i)
faces.append(e)
return faces
|
def timeout_command(command, timeout):
"""call shell-command and either return its output or kill it
if it doesn't normally exit within timeout seconds and return None"""
import subprocess, datetime, os, time, signal
start = datetime.datetime.now()
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while process.poll() is None:
time.sleep(0.1)
now = datetime.datetime.now()
if (now - start).seconds > timeout:
os.kill(process.pid, signal.SIGKILL)
os.waitpid(-1, os.WNOHANG)
return False
return True
|
def _fix_host(host: str) -> str:
"""
Remove any leading "https://" from a host
:param host: the host string
:return: possibly modified result
"""
if host.startswith("https://"):
host = host[len("https://") :]
return host.replace("/", "")
|
def nested_get(futures, ndim, getter):
"""Recusively get results from nested futures.
"""
return (tuple(getter(fut) for fut in futures) if ndim == 1 else
tuple(nested_get(fut, ndim - 1, getter) for fut in futures))
|
def rgb_2_plt_tuple(r, g, b):
"""converts a standard rgb set from a 0-255 range to 0-1"""
plt_tuple = tuple([x/255 for x in (r, g, b)])
return plt_tuple
|
def kochanekBartelsInterpolator(v0, v1, v2, v3, alpha, tension, continuity, bias):
"""
Kochanek-Bartels interpolator. Allows even better control of the bends in the spline by providing three
parameters to adjust them:
* tension: 1 for high tension, 0 for normal tension and -1 for low tension.
* continuity: 1 for inverted corners, 0 for normal corners, -1 for box corners.
* bias: 1 for bias towards the next segment, 0 for even bias, -1 for bias towards the previous segment.
Using 0 continuity gives a hermite spline.
"""
alpha2 = alpha * alpha
alpha3 = alpha2 * alpha
m0 = ((((v1 - v0) * (1 - tension)) * (1 + continuity)) * (1 + bias)) / 2.0
m0 += ((((v2 - v1) * (1 - tension)) * (1 - continuity)) * (1 - bias)) / 2.0
m1 = ((((v2 - v1) * (1 - tension)) * (1 - continuity)) * (1 + bias)) / 2.0
m1 += ((((v3 - v2) * (1 - tension)) * (1 + continuity)) * (1 - bias)) / 2.0
a0 = 2 * alpha3 - 3 * alpha2 + 1
a1 = alpha3 - 2 * alpha2 + alpha
a2 = alpha3 - alpha2
a3 = -2 * alpha3 + 3 * alpha2
return a0 * v1 + a1 * m0 + a2 * m1 + a3 * v2
|
def iops_to_kiops(number: float) -> float:
"""
Convert iops to k-iops.
Parameters
----------
number : float
A ``float`` in iops.
Returns
-------
float
Returns a ``float`` of the number in k-iops.
"""
return round(number * 1e-3, 3)
|
def _strToBoundNumeral(v, interval, conversion):
"""Test (and convert) a generic numerical type, with a check against a lower and upper limit.
@param v: the literal string to be converted
@param interval: lower and upper bounds (non inclusive). If the value is None, no comparison should be done
@param conversion: conversion function, ie, int, long, etc
@raise ValueError: invalid value
"""
try:
i = conversion(v)
if (interval[0] is None or interval[0] < i) and (interval[1] is None or i < interval[1]):
return i
except:
pass
raise ValueError("Invalid numerical value %s" % v)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.