content stringlengths 42 6.51k |
|---|
def unlistify(x):
""" remove list wrapper from single item. similar to function returning list or item """
return x[0] if len(x)==1 else x |
def absorption_spectrum(spectrum, wave_len, wave_len_min, wave_len_max):
"""
Determines wavelength of emitted bundle based upon the phosphor absorption
spectrum (approximates the spectrum of sunlight) The normalized intensity
per wavelength is called from excel and a random cumulative intensity is
u... |
def recursive_any(l: list, fn) -> bool:
"""Returns True if callback function fn returns True given any element from list l. Otherwise, False."""
if not l:
return False
if fn(l[0]):
return True
return recursive_any(l[1:], fn) |
def generate_oa_dfs(in_a_measurements_df, in_b_measurements_df,
oa_band_mutations, oa_plot_measurements, prepare_and_filter, plan):
"""Prepare other/additional attributes (OAs) and write the DataFrames
used to name matched data files."""
# Note that B(b) is not used yet, as only GA supported for now... |
def G(S, K):
"""the payoff function of put option. Nothing to do with barrier"""
return max(K-S, 0) |
def extract_arguments(start, string):
""" Return the list of arguments in the upcoming function parameter closure.
Example:
string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))'
arguments (output):
'[{'start': 1, 'end': 7},
{'start': 8, 'end': 16},
... |
def _get_names_from_list_of_dict(rows):
"""Return list of column names if ``rows`` is a list of dict that
defines table data.
If rows is not a list of dict then return None.
"""
if rows is None:
return None
names = set()
for row in rows:
if not isinstance(row, dict):
... |
def count(grid, char):
"""Counts the occurrences of [char] in the grid."""
res = 0
for line in grid:
res += sum(1 for c in line if c == char)
return res |
def count_ones_iter(n):
"""Using Brian Kernighan's Algorithm. (Iterative Approach)"""
count = 0
while n:
n &= n - 1
count += 1
return count |
def convert_age_units(age_unit):
"""
Simple function to convert proband age units to cgap standard
Args:
age_unit (str): proband age unit
Return:
str: cgap age unit
"""
convert_dict = {
"d": "day",
"w": "week",
"m": "month",
"y": "year"
}
... |
def minSize(split, mined):
"""
Called by combineCheck() to ensure that a given cleavage or peptide is larger than a given minSize.
:param split: the cleavage or peptide that is to have its size checked against max size.
:param mined: the min size that the cleavage or peptide is allowed to be.
:re... |
def get_maximum_contexts (dict_context) :
"""Get the number of sentences before and after to take"""
max_before_context=0
for pronoun in dict_context :
if max_before_context <dict_context[pronoun]["sentences_before"] :
max_before_context=dict_context[pronoun]["sentences_before"]
ma... |
def shorten(text, width, placeholder='...'):
"""
>>> shorten('123456789', width=8)
'12345...'
>>> shorten('123456789', width=9)
'123456789'
"""
if not text:
return text
if len(text) <= width:
return text
return text[: max(0, width - len(placeholder))] + placeholder |
def findChIndex(c, str_in):
"""
Version 2: Using built-in methods.
Write a python function that returns the first index of a character 'c' in string
'str_in'.
If the character was not found it returns -1.
Ex:
findChIndex('a', 'dddabbb') will return 3
findC... |
def get_mlt_query(like_these, minimum_should_match):
"""
Perform a More Like This elasticsearch query on a given collection of documents
"""
return {
"query": {
"more_like_this": {
"fields": [
"title", "abstract"
],
... |
def f(_a, _c):
"""Get first flattening.
Parameters
----------
_a : float
Semi-major axis
_c : float
Semi-minor axis
"""
return 1 - _c / _a |
def cartesian_product(list1, list2):
"""Returns the cartesian product of the lists."""
ret = []
for i in list1:
ret.append([(i, j) for j in list2])
return ret |
def request_to_jsonable(request):
"""Get a request object and return a dict with desired key, value
pairs that are to be encoded to json format
"""
return dict(
(k, request[k]) for k in (
'id',
'user',
'watchers',
'state',
'repo',
... |
def strip_checkpoint_id(checkpoint_dir):
"""Helper function to return the checkpoint index number.
Args:
checkpoint_dir: Path directory of the checkpoints
Returns:
checkpoint_id: An int representing the checkpoint index
"""
checkpoint_name = checkpoint_dir.split('/')[-1]
retur... |
def number(lst, prefix, start=0):
""" Number the items in the lst
:lst: contains items to number
:returns: a dict with item as the key and its number as the value
"""
return {item: '{0}{1}'.format(prefix, itemId)
for itemId, item in enumerate(sorted(lst), start=start)} |
def area_of_polygon(x, y):
"""Area of an arbitrary 2D polygon given its verticies
"""
area = 0.0
for i in range(-1, len(x)-1):
area += x[i] * (y[i+1] - y[i-1])
return abs(area) / 2.0 |
def miller_rabin_test(n):
"""Statistically test the primality of a number using the Miller-Rabin
algorithm.
"""
k, m = 0, n - 1
while True:
if m % 2 != 0:
break
else:
k += 1
m /= 2
b = 2**m % n
if (b - n) == -1 or b == 1:
return T... |
def string_to_bool(s, default=False):
"""
Turns a string into a bool, giving a default value preference.
"""
if len(str(s).strip()) == 0:
return default
if default:
if s[0].upper() == "F":
return False
else:
return True
else:
if s[0].upper... |
def _is_constant_mapping(val_dict):
"""
@param val_dict:
Defines the mapping, by defining an output value for each row of
constrains. Each row is defined by a dictionary of operand names to
operand values.
@type val_dict:
[ ([ dict(opname:string -> opval:string) ], value:string) ]
The r... |
def string2bool(input_string):
"""
Converts string to boolena by checking if texts meaning is True, otherwise returns False.
"""
return input_string in ['true', 'True', 'Yes', '1'] |
def get_ascii_character_for_key(key):
"""Map a key to ASCII character."""
if not key:
return None
value = key.value
if value > 255:
return None
return chr(value) |
def isInstalled(name):
"""Check whether `name` is in the PATH.
"""
from distutils.spawn import find_executable
return find_executable(name) is not None |
def flatten(lists):
"""
Return a new (shallow) flattened list.
:param lists: list: a list of lists
:return list
"""
return [item for sublist in lists for item in sublist] |
def threshold(suffix, config_dict):
"""Determines null percent thresholds for categories based on suffix."""
if suffix in config_dict:
t1 = config_dict[suffix]['cat1']
t2 = config_dict[suffix]['cat2']
t3 = config_dict[suffix]['cat3']
else:
t1 = config_dict['Categories']['cat... |
def forcefully_read_lines(filename, size):
"""Return lines from file.
Ignore UnicodeDecodeErrors.
"""
input_file = open(filename, mode='rb')
try:
return input_file.read(size).decode('utf-8', 'replace').splitlines()
finally:
input_file.close()
return [] |
def desi_proc_joint_fit_command(prow, queue=None):
"""
Wrapper script that takes a processing table row (or dictionary with NIGHT, EXPID, OBSTYPE, PROCCAMWORD defined)
and determines the proper command line call to process the data defined by the input row/dict.
Args:
prow, Table.Row or dict. M... |
def jolt_differences( data ):
"""
To the given data, add the jolts of the charging outlet at the start and
jolt of the device to the end of the adapters list. Since all the adapters
have to be used, the difference between the sorted adapters are computed.
The 1's and 3's are counted and their mul... |
def get_sources(results):
"""
Get sources from hits, sorted by source id
Args:
results (dict): Elasticsearch results
Returns:
list of dict: The list of source dicts
"""
sorted_hits = sorted(results['hits'], key=lambda hit: hit['_source']['id'])
return [hit['_source'] for hi... |
def ranks_to_acc(found_at_rank, fid=None):
"""
Computes top-1-accuracy from list of ranks
:param found_at_rank: List of ranks.
:param fid: File identifier.
:return accs: top-N-accuracies
"""
def fprint(txt):
print(txt)
if fid is not None:
fid.write(txt + ... |
def was_preemptible_vm(metadata, was_cached):
"""
Modified from: https://github.com/broadinstitute/dsde-pipelines/blob/develop/scripts/calculate_cost.py
"""
# if call cached, not any type of VM, but don't inflate nonpreemptible count
if was_cached:
return None
elif (
"runtimeAttr... |
def get_max_prime_factor_less_than(
n, ceil
):
"""
Helper function for recursive_seed_part. Returns the largest prime factor of ``n`` less than
``ceil``, or None if all are greater than ceil.
"""
factors = []
i = 2
while i * i <= n:
if n % i:
i += 1
else:
... |
def fmt_point(point):
"""Format a 2D point."""
assert len(point) == 2
return f"({point[0]},{point[1]})" |
def purge(li):
"""renvoie la liste avec uniquement les chiffres"""
return [i for i in li if type(i) == int or type(i) == float] |
def get_list_of(key, ch_groups):
"""
Return a list of values for key in ch_groups[groups]
key (str): a key of the ch_groups[groups] dict
ch_groups (dict): a group-name-indexed dict whose values are
dictionaries of group information (see expand_ch_groups)
Example: get_list_of('system', ch_g... |
def remove_markdown(body):
"""Remove the simple markdown used by Google Groups."""
return body.replace('*', '') |
def select_packages(packages, categories):
"""
Select packages inside the chosen categories
Parameters
----------
packages : dict
Dictionary with categories and their corresponding packages as lists.
categories : list
List containing the chosen categories
Returns
------... |
def getarg(args, index):
"""
Helper to retrieve value from command line args
"""
return args[index] if index < len(args) else None |
def sortedMerge(list1, list2):
"""assumes list1 and list2 are lists
returns a list of tuples, from the elements of list1 and list2"""
# zip lists
combo_list = list(zip(list1, list2))
# sort list by 2nd elem
combo_list = sorted(combo_list, key=lambda a: a[1])
return combo_list |
def mod_type_to_string(mod_type):
""" Prints module type in readable form
"""
out = '('
# type
if (mod_type & 0xf) == 0:
out += ' builtin'
elif (mod_type & 0xf) == 1:
out += ' loadable'
# Module that may be instantiated by fw on startup
if ((mod_type >> 4) & 0x1) == 1:
... |
def pluralize(value):
""" Add an 's' or an 'ies' to a word.
We've got some special cases too.
"""
plural = value
if value[-1] == 'y':
plural = '%sies' % value[:-1]
else:
plural += 's'
return plural |
def _get_widget_selections(widgets, widget_selections):
"""Return lists of widgets that are selected and unselected.
Args:
widgets (list):
A list of widgets that we have registered already.
widget_selections (dict):
A dictionary mapping widgets
(:py:class:`r... |
def clean_filename(filename):
""" Remove leading path and ending carriage return from filename.
"""
return filename.split('/')[-1].strip() |
def get_fold_val(fold_test, fold_list):
""" Get the validation fold given the test fold.
Useful for cross-validation evaluation mode.
Return the next fold in a circular way.
e.g. if the fold_list is ['fold1', 'fold2',...,'fold10'] and
the fold_test is 'fold1', then return 'fold2'.
If the fold_... |
def get_fly_energy(weight, distance):
"""
Calculate E_f.
"""
m_d = weight
# v_d is in m/s
v_d = 5.70 * (m_d ** 0.16)
# convert to m
L_d = distance * 1000
# convert to hours
temp_time = L_d / v_d / 60 / 60
E_v = 300 / 4.184
E_f = m_d * E_v * temp_time
return E_f |
def get_command_name(value):
"""
Gets command name by value
:param value: value of Command
:return: Command Name
"""
if value == 1:
return 'CONNECT'
elif value == 2:
return 'BIND'
elif value == 3:
return 'UDP_ASSOCIATE'
else:
return None |
def subtract(coords1, coords2):
"""
Subtract one 3-dimensional point from another
Parameters
coords1: coordinates of form [x,y,z]
coords2: coordinates of form [x,y,z]
Returns
list: List of coordinates equal to coords1 - coords2 (list)
"""
x = coo... |
def ndvi(nir, red):
"""Compute Normalized Difference Vegetation Index from NIR & RED images."""
return (nir - red) / (nir + red) |
def dot_product(u, v):
"""Computes dot product of two vectors u and v, each represented as a tuple
or list of coordinates. Assume the two vectors are the same length."""
output = 0
for i in range(len(u)):
output += (u[i]*v[i])
return output |
def remove_last_syllable(phon: str) -> str:
"""Remove the last syllable boundary in a phonetic string.
Example: Turn `fa:-n` (stem of `fa:-n@`) into `fa:n`.
"""
# Find the last hyphen marking a syllable boundary and remove it.
i = phon.rfind("-")
j = i + 1
return phon[:i] + phon[j:] |
def branch(path):
"""
Builds a tuple containing all path above this one.
None of the returned paths or the given paths is required to
actually have a corresponding Node.
Expample:
>>> branch("/a/b/c/")
('/', '/a/', '/a/b/', '/a/b/c/')
"""
li = tuple(p for p in path.split('/') if p)
... |
def convert_to_numbers(string_to_convert):
"""Converts A-Z strings to numbers."""
numbers_from_string = []
for letter in string_to_convert:
numbers_from_string.append(ord(letter)-64)
#numbers_from_string.append(keystream.letters_to_keys_list[letter])
return numbers_from_string |
def parse_to_tuples(command_strs):
"""
Parse commands into a tuple list
"""
tuples = []
for command in command_strs:
cmd, arg = command.split(" ")
cmd = cmd.strip()
arg = int(arg.strip())
tuples.append((cmd, arg))
return tuples |
def format_tag_endings(tag, punct_value, endings=[]):
"""Format punctuation around a tag.
Normalizes in case of irregularity. For instance, in the
cases of both
words.</>
words</>.
the tags will be normalized to either an in/exclusive order.
"""
if punct_value == 'inclusive... |
def get_name(node):
"""Return name of node."""
return node.get('name') |
def get_comparments(list_trans):
"""
Getting a list of transtions, return the compartments
"""
l = []
for trans in list_trans:
if trans.from_comp not in l:
l.append(trans.from_comp)
if trans.to_comp not in l and trans.to_comp != 'zero':
l.append(trans... |
def format_currency(value, decimals=2):
"""
Return a number suitably formatted for display as currency, with
thousands separated by commas and up to two decimal points.
>>> format_currency(1000)
u'1,000'
>>> format_currency(100)
u'100'
>>> format_currency(999.95)
u'999.95'
>>> f... |
def compute_hashes(to_compute):
"""
"""
hasharr = []
for arr in to_compute:
hashval = hash(bytes(arr))
hasharr.append(hashval)
return hasharr |
def eval_print_fn(val, print_fn):
"""Evaluate a print function, and return the resulting string."""
# The generated output from explain contains the string "\n" (two characters)
# replace them with a single EOL character so that GDB prints multi-line
# explains nicely.
pp_result = print_fn(val)
... |
def shaping_by_fields(fields: list) -> str:
"""
Creating a shaping for the request which is from the fields and seperated by comma's
Args:
fields: List of fields that would be part of the shaping.
Returns:
str of the shaping.
"""
shaping = 'hd_ticket all'
for field in fields:... |
def format_schedule(sched):
"""
Formats a schedule (as list of Operations) for printing in HTML
"""
s = ''
for op in sched:
if op.type!='READ' and op.type!='WRITE':
s += '<b>'+str(op)+' </b>'
else:
s += str(op)+' '
return s+'\n' |
def remove_prefix(text, prefix):
""" If a particular prefix exists in text string, This function
removes that prefix from string and then returns the remaining string
"""
if text.startswith(prefix):
return text[len(prefix):]
return text |
def bool_converter(value):
"""Simple string to bool converter (0 = False, 1 = True)."""
return value == "1" |
def sig_indicator(pvalue):
"""Return a significance indicator string for the result of a t-test.
Parameters
----------
pvalue: float
the p-value
Returns
-------
str
`***` if p<0.001, `**` if p<0.01, `*` if p<0.05, `ns` otherwise.
"""
return (
'***' if p... |
def sediment_delivery_ratio(area_sq_km):
"""
Calculate Sediment Delivery Ratio from the basin area in square km
Original at Class1.vb@1.3.0:9334-9340
"""
if area_sq_km < 50:
return (0.000005 * (area_sq_km ** 2) -
(0.0014 * area_sq_km) + 0.198)
else:
return 0.451... |
def list_to_str(seq, sep="-"):
"""Transform the input sequence into a ready-to-print string
Parameters
----------
seq : list, tuple, dict
Input sequence that must be transformed
sep : str
Separator that must appears between each `seq` items
Returns
-------
str
P... |
def _format_return_message(results):
"""
Formats and eliminates redundant return messages from a failed geocoding result.
:param results: the returned dictionary from Geoclient API of a failed geocode.
:return: Formatted Geoclient return messages
"""
out_message = None
if 'message' in resul... |
def trim(item, max_len=75):
"""Return string representation of item, trimmed to max length."""
string = str(item)
string = string[:max_len] + '...' if len(string) > max_len else string
return string |
def get_format_invocation(f, clang_format_binary):
"""Gets a command line for clang-tidy."""
start = [clang_format_binary, "-i", f]
return start |
def low_pass_filter(X_room_act: float, X_filt_last: float):
"""
This function is a low pass filter for data pretreatment to filter out the high frequency data
:param X_room_act: float: current absolute humidity (mixing ratio kg_moisture/kg_dry-air)
:param X_filt_last: float: last filtered value of absol... |
def edgeList(G):
"""convert list-of-sets graphs representation to a list of edges"""
V = len(G)
E = []
for v in range(V):
for u in G[v]:
if v < u and v != 0 and u != 0:
E += [(v, u)]
return E |
def count_nt(string):
"""Count A, T, C, G"""
string = string.upper()
counts = []
for nt in ['A', 'C', 'G', 'T']:
counts.append(string.count(nt))
s_counts = " ".join([str(x) for x in counts])
return s_counts |
def heredoc(s, inputs_dict):
"""
Use docstrings to specify a multi-line string literal.
Args:
s (str): docstring with named placeholders for replacement.
inputs_dict (dict): dict with keys corresponding to placeholders
in docstring `s` and values to insert.
Returns:
... |
def parStringToIntList(parString):
"""
Convert a space delimited string to a list of ints
"""
return [int(x) for x in parString.split()] |
def to_word(word: int) -> int:
"""
>>> hex(to_word(0x1234ABCD))
'0xabcd'
>>> hex(to_word(0))
'0x0'
This size should never happen!
>>> hex(to_word(0x12345678ABCD))
'0xabcd'
Masks the given value to the size of a word (16 bits)
:param word:
:return:
"""
assert isinst... |
def get_index(refname, indices, max_order):
"""Get the index of a monomial."""
if refname == "interval":
return indices[0]
if refname == "triangle":
return sum(indices) * (sum(indices) + 1) // 2 + indices[1]
if refname == "quadrilateral":
return indices[1] * (max_order + 1) + ind... |
def weed_out_short_notes(pairs, **kwargs):
"""Remove notes from pairs whose duration are smaller than the threshold"""
duration_threshold = kwargs.get('duration_threshold', 0.25)
return [(n, d) for (n, d) in pairs if d > duration_threshold] |
def merge(left, right):
""" Merge helper
Complexity: O(n)
"""
arr = []
left_cursor, right_cursor = 0,0
while left_cursor < len(left) and right_cursor < len(right):
# Sort each one and place into the result
if left[left_cursor] <= right[right_cursor]:
arr.... |
def last_index(L, value):
"""
Find the final occurrence of value in L.
"""
val = next(iter(
filter(lambda x: x[1] == value, reversed(list(enumerate(L))))))
if val:
return(val[0])
else:
raise(ValueError("{} is not in the list.".format(value))) |
def _async_unique_id_to_mac(unique_id: str) -> str:
"""Extract the MAC address from the registry entry unique id."""
return unique_id.split("_")[0] |
def expected_headers(auth_token='my-auth-token'):
"""
Return an expected set of headers, given an auth token
"""
return {
'content-type': ['application/json'],
'accept': ['application/json'],
'x-auth-token': [auth_token],
'User-Agent': ['OtterScale/0.0']
} |
def getWorldRegion(regionID):
"""
Creates a array of all the world regions
"""
world_region = {
0: "us", #US West
1: "use", #US East
2: "eu", #Europe
3: "jp" #Japan
}
return world_region[regionID - 1] |
def p3sat_h(h):
"""
*4.2 Region 3. pSat_h & pSat_s
Revised Supplementary Release on Backward Equations for the functions
T(p,h), v(p,h) & T(p,s), v(p,s) for Region 3 of the IAPWS Industrial formulation 1997
for the Thermodynamic Properties of Water & Steam 2004
Section 4 Boundary Eq... |
def factorizable(n, factors, sort_factors=True):
"""
Check if there is a way to factorize n by the factors passed as a second argument.
Factors could be non-prime.
As the factors could be non-prime, we can't just divide by all the factors one by one
until there are no factors left or we got 1. ... |
def get_tags_asset(tag_assets):
"""
Iterate over tag assets list from response and retrieve details of tag assets
:param tag_assets: List of tag assets from response
:return: List of detailed elements of tag assets
:rtype: list
"""
return [{
'ID': tag_asset.get('id', ''),
'N... |
def slice(seq, indices):
"""Performs a Perl-style slice, substituting None for out-of-range
indices rather than raising an exception.
"""
sliced = []
for index in indices:
try:
sliced.append(seq[int(index)])
except IndexError:
sliced.append(None)
return sl... |
def _dotted_path(segments):
"""Convert a LUA object path (``['dir/', 'file/', 'class#',
'instanceMethod']``) to a dotted style that Sphinx will better index."""
segments_without_separators = [s[:-1] for s in segments[:-1]]
segments_without_separators.append(segments[-1])
return '.'.join(segments_wit... |
def read_file(file_path):
"""
Open the file and return the contents
Parameters
----------
file_path : str
The path of the file.
Returns
----------
file_data : str
Data in the file
"""
try:
with open(file_path, 'r', encoding="utf-8_sig") as target_file:
... |
def perm2cycles_without_fixed(perm):
"""
Convert permutation in one-line notation to permutation in cycle notation without fixed points
:param perm: Permutation in one-line notation
:type perm: list
:return: Returns permutation in cycle notation without fixed points
:rtype: list
"""
cy... |
def get_non_digit_prefix(characters):
"""
Return the non-digit prefix from a list of characters.
"""
prefix = []
while characters and not characters[0].isdigit():
prefix.append(characters.pop(0))
return prefix |
def get_empty_cells(grid):
"""Return a list of coordinate pairs corresponding to empty cells."""
empty = []
for j,row in enumerate(grid):
for i,val in enumerate(row):
if not val:
empty.append((j,i))
return empty |
def between(bound_min, bound_max, value):
"""Checks whether the value is between the min and max values, inclusive."""
return bound_min <= value and value <= bound_max |
def remove_key(dictionary, key):
"""Remove specified key from dictionary, do nothing if it does not exist."""
if key in dictionary:
del dictionary[key]
return dictionary |
def split_data(x, y):
"""
Split data into training and validation set
:return:
"""
training_percent = 0.7
split_idx = round(training_percent * len(y))
x_train = x[:split_idx]
x_val = x[split_idx:]
y_train = y[:split_idx]
y_val = y[split_idx:]
return x_train, y_train, x_va... |
def find_deltas(arr):
"""
Creates a new array that is the differences between consecutive elements in
a numeric series. The new array is len(arr) - 1
"""
return [j-i for i, j in zip(arr[:-1], arr[1:])] |
def sanitize(d):
"""Sanitize sensitive information, preventing it from being logged
Given a dictionary, look up all keys that may contain sensitive information
(eg. "authtoken", "Authorization"). Returns a dict with the value of these
keys replaced with "omitted"
Arguments:
d (dict): dicti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.