content
stringlengths 42
6.51k
|
---|
def convert_to_list_of_words(lyrics):
"""Returns a list of words
Parameters:
lyrics (string)
Returns:
list: a list of words
"""
return lyrics.replace(',','').lower().strip().split()
|
def is_infinite(x, y):
""" Determind is the pair will play indefinitly
"""
# sort x and y such that x < y
(x, y) = (x, y) if x < y else (y, x)
while x != y:
# x wins while x < y
y -= x
x *= 2
# if the numbers x becomes larger than y, we will keep playing indefitely
if x > y:
return True
return False
|
def scrubPrefixes(name):
"""
Removes commonly seen prefixes.
"""
prefixes = ["Mr.", "Ms.", "Mrs.", "Dr.", "Mr", "Ms", "Mrs", "Dr", "Miss"]
names = name.split()
if names[0] in prefixes:
names = names[1:]
else:
names = names[0:]
return ' '.join(names)
|
def value_to_dict(val, val_type):
"""given the value and its type, dump it to a dict
the helper function to dump values into dict ast
"""
return {"type": val_type, "value": val}
|
def help_enhancer(_h):
"""A simple helper to validate the ``enhance_help`` kwarg."""
return ''.join(reversed(_h))
|
def encode_shortform_block_annotation(d):
"""Creates the shortform version of the block annotation
using information from the sequence dictionary.
Parameters
----------
d : dict
Dictionary representation individuals entries in a FASTA file.
Returns
-------
str
"""
# Sample: 'Dm528_2L_3_+_8366009_1_1:1773'
template = '{ref_version}_{chr_loc}_{chr_scaffold}_{ori}_{gpos_oneb}_' \
'{num_blocks}_{blocks}'
try:
return template.format(
ref_version=d['ref_version'],
chr_loc=d['chromosome'],
chr_scaffold=d['chromosome_scaffold'],
ori=d['orientation'],
gpos_oneb=d['genome_pos'] + 1,
num_blocks=len(d['blocks']),
blocks=';'.join(
['{}:{}'.format(s[0].start + 1, s[0].stop) for s in d['blocks']]
),
)
except KeyError:
# If any one of the keys is not found, returns an empty string
# Because "marker" will not have any extra keys in its per sequence dict
return ''
|
def js_time(python_time: float) -> int:
"""Convert python time to js time, as the mephisto-task package expects"""
return int(python_time * 1000)
|
def list_in_list(a,b):
"""
Determines whether list a is part of list b, either forwards or backwards
"""
if any(a == b[offset:offset+len(a)] for offset in range(len(b)-len(a)+1)):
return True
else:
a.reverse()
if any(a == b[offset:offset+len(a)] for offset in range(len(b)-len(a)+1)):
return True
else: return False
|
def LengthAdjust(bstr, width=0):
"""Adjust the length of a byte-string to meet the byte-width with leading padding "0" regardless of its endianess.
bstr - the byte string.\n
width - the data length, counted in byte."""
blen = width*2 if width else len(bstr)
if blen%2:
bstr = '0' + bstr
blen += 1
if blen > len(bstr):
bstr = '0' * (blen - len(bstr)) + bstr
return bstr, blen
|
def get_batch_scales(X_all, X):
"""
Description: Returns proportions of batches w.r.t. the total number of samples for the stochastic gradient scaling.
"""
batch_scales = []
for t, X_all_task in enumerate(X_all):
batch_scales.append(float(X_all_task.shape[0]) / float(X[t].shape[0]))
return batch_scales
|
def apply_spacing(l, m, n, spacing=(None, 0,0,0)):
"""Position of array elements in relation to each other."""
recipe, l_f, m_f, n_f = spacing
if recipe not in [None, 'even', 'l', 'm', 'n']:
raise TypeError("BAD")
if recipe is None:
return (0,0,0)
elif recipe == 'even':
return (l*l_f, m*m_f, n*n_f)
elif recipe == 'l':
return (l*l_f, l*m_f, l*n_f)
elif recipe == 'm':
return (m*l_f, m*m_f, m*n_f)
elif recipe == 'n':
return (n*l_f, n*m_f, n*n_f)
else:
raise TypeError("Unknown recipe[%s]" % recipe)
|
def pick_wm_2(probability_maps):
"""
Returns the white matter probability map from the list of segmented probability maps
Parameters
----------
probability_maps : list (string)
List of Probability Maps
Returns
-------
file : string
Path to segment_prob_2.nii.gz is returned
"""
if isinstance(probability_maps, list):
if len(probability_maps) == 1:
probability_maps = probability_maps[0]
for filename in probability_maps:
if filename.endswith("seg_2.nii.gz"):
return filename
return None
|
def _build_response_credential_filter_one_credential(credential_items, status_code):
""" Method to build the response if the API user
chose to return only the first credential
"""
return {
"status": status_code,
"data": {
"id": credential_items[0]["id"],
"name": credential_items[0]["name"]
}
}
|
def strip_none(dic):
"""
Returns a dictionary stripped of any keys having values of None
"""
return {k: v for k, v in dic.items() if v is not None}
|
def to_varname(string):
"""Converts string to correct Python variable name.
Replaces unavailable symbols with _ and insert _ if string starts with digit.
"""
import re
return re.sub(r'\W|^(?=\d)','_', string)
|
def _ArgbToRgbaTuple(argb):
"""Convert from a single ARGB value to a tuple containing RGBA.
Args:
argb: Signed 32 bit integer containing an ARGB value.
Returns:
RGBA tuple.
"""
unsigned_argb = argb % 0x100000000
return ((unsigned_argb >> 16) & 0xFF,
(unsigned_argb >> 8) & 0xFF,
unsigned_argb & 0xFF,
(unsigned_argb >> 24) & 0xFF)
|
def sizeformat(num, suffix='B'):
"""Format bytes as human readable size."""
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Yi', suffix)
|
def pitch_to_midi_pitch(step, alter, octave):
"""Convert MusicXML pitch representation to MIDI pitch number."""
pitch_class = 0
if step == 'C':
pitch_class = 0
elif step == 'D':
pitch_class = 2
elif step == 'E':
pitch_class = 4
elif step == 'F':
pitch_class = 5
elif step == 'G':
pitch_class = 7
elif step == 'A':
pitch_class = 9
elif step == 'B':
pitch_class = 11
else:
pass
pitch_class = (pitch_class + int(alter))
midi_pitch = (12 + pitch_class) + (int(octave) * 12)
return midi_pitch
|
def validate_window_size(candidate_window_size: int) -> int:
"""Return validated window size candidate, raising a meaningful error otherwise.
Parameters
-----------------
candidate_window size: int,
The candidate window size value to validate.
Raises
-----------------
ValueError,
If the provided window size parameter is not within
the allowed set of values.
Returns
-----------------
The validated value.
"""
if not isinstance(candidate_window_size, int):
raise ValueError(
(
"The window size parameter must be an integer.\n"
"You have provided `{}`, which is of type `{}`."
).format(
candidate_window_size,
type(candidate_window_size)
)
)
if candidate_window_size < 1:
raise ValueError(
(
"The window size parameter must a strictly positive "
"integer value. You have provided `{}`."
).format(
candidate_window_size
)
)
return candidate_window_size
|
def has_options(cli):
"""
Checks if the cli command contains any options (e.g. --regex $REGEX).
"""
for item in cli:
if '--' in item:
return True
return False
|
def is_dictionary(obj):
"""Helper method for testing if the object is a dictionary.
>>> is_dictionary({'key':'value'})
True
"""
return type(obj) is dict
|
def catchErr(fun, *args, **kwargs):
"""Function to catch RTErrs raised from list comprehensions"""
try:
return fun(*args, **kwargs)
except:
return None
|
def input_plasmid_mass(target_len, plasmid_len, target_mass):
"""
Computes the mass of total input plasmid mass required to get a given mass
of target DNA.
Silently assumes that the units are:
- target_len: bp (base pairs)
- plasmid_len: bp (base pairs)
- target_mass: ng (nanograms)
"""
return target_mass * plasmid_len / target_len
|
def pad_frames(signal, n_frames, how='replicate'):
"""
Pad a signal to n_frames.
:param signal: input to pad. Shape is frames X n_features where frames < n_frames
:param n_frames: number of frames to pad to
:param how: replicate the beginning of the signal or 0 padding
:return: padded signal
"""
n_features = len(signal[0])
if how == '0':
return signal + (n_frames - len(signal)) * [n_features*[0]]
if how == 'replicate':
while len(signal) != n_frames:
signal += signal[:(n_frames - len(signal))]
return signal
|
def f1_score_prob(precision, recall):
"""
this function use to caculate f1 score
:param precision:
:param recall:
:return:
"""
f1_scores = []
for x, y in zip(precision,recall):
f1 = 2.0 * (x * y) / (x + y)
f1_scores.append(f1)
return f1_scores
|
def write_rows_in_worksheet(worksheet, rows):
"""
Write rows into a given worksheet
:param worksheet:
:param rows:
:return:
"""
# Start from the first cell. Rows and columns are zero indexed.
row_index = 0
col_index = 0
# Iterate over the data and write it out row by row.
for row in rows:
for item in row:
worksheet.write(row_index, col_index, item)
col_index += 1
row_index += 1
col_index = 0
return worksheet
|
def convert_acl_to_iam_policy(acl):
"""Converts the legacy ACL format to an IAM Policy proto."""
owners = acl.get('owners', [])
readers = acl.get('readers', [])
if acl.get('all_users_can_read', False):
readers.append('allUsers')
writers = acl.get('writers', [])
bindings = []
if owners:
bindings.append({'role': 'roles/owner', 'members': owners})
if readers:
bindings.append({'role': 'roles/viewer', 'members': readers})
if writers:
bindings.append({'role': 'roles/editor', 'members': writers})
return {'bindings': bindings}
|
def unique_decompo_prime_factors(nb, l_nb_p):
"""
This function take a number and a list of
prime number (supposed to go farter than nb)
and give the different prime numbers involved in
the prime decomposition of the number.
"""
decompo = []
for elt in l_nb_p:
if nb % elt == 0:
decompo.append(elt)
return decompo
|
def init(strKernel, iKernelPar=1, iALDth=1e-4, iMaxDict=1e3):
"""
Function initializes krls dictionary. |br|
Args:
strKernel (string): Type of the kernel
iKernelPar (float): Kernel parameter [default = 1]
iALDth (float): ALD threshold [default = 1e-4]
iMaxDict (int): Max size of the dictionary [default = 1e3]
Returns:
dAldKRLS (dictionary): Python dictionary which contains all the data of the current KRLS algorithm.
Fields in the output dictionary:
- a. **iALDth** (*int*): ALD threshold
- b. **iMaxDt** (*float*): Max size of the dictionary
- c. **strKernel** (*string*): Type of the kernel
- d. **iKernelPar** (*float*): Kernel parameter
- e. **bInit** (*int*): Initialization flag = 1. This flag is cleared with a first call to the 'train' function.
"""
dAldKRLS = {} # Initialize dictionary with data for aldkrls algorithm
# Store all the parameters in the dictionary
dAldKRLS['iALDth'] = iALDth; # ALD threshold
dAldKRLS['iMaxDt'] = iMaxDict; # Maximum size of the dictionary
dAldKRLS['strKernel'] = strKernel # Type of the kernel
dAldKRLS['iKernelPar'] = iKernelPar # Kernel parameter
dAldKRLS['bInit'] = 0 # Clear 'Initialization done' flag
return dAldKRLS
|
def model_tempmin(Sdepth_cm = 0.0,
prof = 0.0,
tmin = 0.0,
tminseuil = 0.0,
tmaxseuil = 0.0):
"""
- Name: TempMin -Version: 1.0, -Time step: 1
- Description:
* Title: Minimum temperature calculation
* Author: STICS
* Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002
* Institution: INRA
* Abstract: recalculation of minimum temperature
- inputs:
* name: Sdepth_cm
** description : snow depth
** inputtype : variable
** variablecategory : state
** datatype : DOUBLE
** default : 0.0
** min : 0.0
** max : 500.0
** unit : cm
** uri :
* name: prof
** description : snow cover threshold for snow insulation
** inputtype : parameter
** parametercategory : constant
** datatype : DOUBLE
** default : 0.0
** min : 0.0
** max : 1000
** unit : cm
** uri :
* name: tmin
** description : current minimum air temperature
** inputtype : variable
** variablecategory : auxiliary
** datatype : DOUBLE
** default : 0.0
** min : 0.0
** max : 100.0
** unit : degC
** uri :
* name: tminseuil
** description : minimum temperature when snow cover is higher than prof
** inputtype : parameter
** parametercategory : constant
** datatype : DOUBLE
** default : 0.0
** min : 0.0
** max : 5000.0
** unit : degC
** uri :
* name: tmaxseuil
** description : maximum temperature when snow cover is higher than prof
** inputtype : parameter
** parametercategory : constant
** datatype : DOUBLE
** default : 0.0
** min :
** max :
** unit : degC
** uri :
- outputs:
* name: tminrec
** description : recalculated minimum temperature
** variablecategory : state
** datatype : DOUBLE
** min : 0.0
** max : 500.0
** unit : degC
** uri :
"""
tminrec = tmin
if Sdepth_cm > prof:
if tmin < tminseuil:
tminrec = tminseuil
else:
if tmin > tmaxseuil:
tminrec = tmaxseuil
else:
if Sdepth_cm > 0.0:
tminrec = tminseuil - ((1 - (Sdepth_cm / prof)) * (abs(tmin) + tminseuil))
return tminrec
|
def make_list(v):
"""
If the object is not a list already, it converts it to one
Examples:
[1, 2, 3] -> [1, 2, 3]
[1] -> [1]
1 -> [1]
"""
if not isinstance(v, list):
return [v]
return v
|
def _get_qtr(datetime_in):
"""
Return the quarter (1-4) based on the month.
Input is either a datetime object (or object with month attribute) or the month (1-12).
"""
try:
return int((datetime_in.month-1)/3)+1
except AttributeError:
pass
return int((datetime_in-1)/3)+1
|
def normalise_whitespace(text):
"""
Normalise the whitespace in the string
:param text: string
:return: string with whitespace normalised to single space
"""
return " ".join(text.strip().split())
|
def get_python_module_names(file_list, file_suffix='.py'):
""" Return a list of module names from a filename list. """
module_names = [m[:m.rfind(file_suffix)] for m in file_list
if m.endswith(file_suffix)]
return module_names
|
def unit(p, th):
"""
Calculate and return the value of unit using given values of the parameters
How to Use:
Give arguments for p and th parameters
*USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE
IT'LL BE HARD TO UNDERSTAND AND USE
Parameters:
p (int):power in Watt
t (int): time in hour
*TIME SHOULD GIVE IN HOUR, OTHERWISE
IT'LL BE MISCALCULATE THE FUNCTION
Returns:
int: the value of unit as unit
"""
u = (p * th) / 1000
return u
|
def flatten_columns(columns):
""" Transforms hierarchical column names to concatenated single-level
columns
"""
return ['_'.join(col).strip() for col in columns]
|
def show_dictionary(name,d):
"""
Print the contents of a dictionary
"""
text = ["[%s]" % name]
for key in d:
text.append("\t%s = %s" % (key,(d[key] if d[key] is not None
else '<Not set>')))
return '\n'.join(text)
|
def getdiffbyindex(inputlist,indexlist):
"""can get durations using timestamp list for inputlist
and appropriate crossvals Ti,Te,Ttot
"""
diffbyindexlist=[inputlist[indexlist[i+1]]-
inputlist[indexlist[i]]
for i in range(len(indexlist)-1)]
return diffbyindexlist
|
def n_undefined(variables_d, popset):
"""
Checks the identification of the problem
:param variables_d:
:param popset:
:return:
"""
n_pop = len(popset)
return len(variables_d) - (n_pop*(n_pop-1)/2)
|
def get_service_from_action(action):
"""
Returns the service name from a service:action combination
:param action: ec2:DescribeInstance
:return: ec2
"""
service, action_name = action.split(':')
return str.lower(service)
|
def lcg_generator(
state: int,
multiplier: int = 1140671485,
addend: int = 12820163,
pmod: int = 2 ** 24,
) -> int:
"""
Performs one step in a pseudorandom sequence from state (the input argument)
to state the return value.
The return value is an integer, uniformly distributed in [0, pmod).
See https://en.wikipedia.org/wiki/Linear_congruential_generator
"""
state = (multiplier * state + addend) % pmod
return state
|
def _get_val_list(obj, path_list, reverse=False):
"""Extract values from nested objects by attribute names.
Objects contain attributes which are named references to objects. This will descend
down a tree of nested objects, starting at the given object, following the given
path.
Args:
obj: object
Any type of object
path_list: list
Attribute names
reverse: bool
Reverse the list of values before concatenation.
Returns:
list of objects
"""
try:
y = getattr(obj, path_list[0])
except AttributeError:
return []
if len(path_list) == 1:
return [y]
else:
val_list = [x for a in y for x in _get_val_list(a, path_list[1:], reverse)]
if reverse:
val_list.reverse()
return val_list
|
def get_sandbox_table_name(table_namer, base_name):
"""
A helper function to create a table in the sandbox dataset
:param table_namer: the string value returned from the table_namer setter method
:param base_name: the name of the cleaning rule
:return: the concatenated table name
"""
if table_namer and not table_namer.isspace():
return f'{table_namer}_{base_name}'
else:
return base_name
|
def normalize_acl(acl):
"""
Normalize the grant and/or revoke lists we were given. Handle single item, list of items, etc.
We want to end up with just a list of IDs. Used by Project object to handle modify_access function.
:param acl: a list of Person objects or just a Person object
:return: a list of integers representing the IDs of the Person objects in the list given
"""
try:
acl = [int(a) for a in acl] # convert Person objects to list of ID integers
except TypeError: # ok maybe we got a single Person instead of a list of them
acl = [int(acl)]
return acl
|
def is_a_header_path(filename: str) -> bool:
"""
Checks if the given filename conforms to standard C++ header
file naming convention.
"""
split_path = filename.split('.')
if len(split_path) > 0 and split_path[-1] in ['h', 'hpp', 'hxx']:
return True
return False
|
def check_auth(username, password):
"""This function is called to check if the login info is valid.
"""
return password == 'password'
|
def isatty(file):
"""
Returns `True` if `file` is a tty.
Most built-in Python file-like objects have an `isatty` member,
but some user-defined types may not, so this assumes those are not
ttys.
"""
if hasattr(file, 'isatty'):
return file.isatty()
return False
|
def _config_info(mode, config):
"""Generate info about the config."""
return {
"mode": mode,
"views": len(config.get("views", [])),
}
|
def timeCount(cur_time, start_time):
"""
Calculate elapsed time.
Returns:
format_t (string): Elapsed time in format "D/H/M"
abs_t (float): Elapsed time in seconds
"""
abs_t = cur_time - start_time
temp = abs_t
d_unit, h_unit, m_unit = 24*3600, 3600, 60
days = int(temp//d_unit)
temp -= days*d_unit
hours = int(temp//h_unit)
temp -= hours*h_unit
mins = int(temp//m_unit)
format_t = ":".join([str(days), str(hours), str(mins)])
return format_t, abs_t
|
def _choose_most_important_network(properties, prefix, importance_fn):
"""
Use the `_network_importance` function to select any road networks from
`all_networks` and `all_shield_texts`, taking the most important one.
"""
all_networks = 'all_' + prefix + 'networks'
all_shield_texts = 'all_' + prefix + 'shield_texts'
networks = properties.pop(all_networks, None)
shield_texts = properties.pop(all_shield_texts, None)
country_code = properties.get('country_code')
if networks and shield_texts:
def network_key(t):
return importance_fn(*t)
tuples = sorted(set(zip(networks, shield_texts)), key=network_key)
# i think most route designers would try pretty hard to make sure that
# a segment of road isn't on two routes of different networks but with
# the same shield text. most likely when this happens it's because we
# have duplicate information in the element and relations it's a part
# of. so get rid of anything with network=None where there's an entry
# with the same ref (and network != none).
seen_ref = set()
new_tuples = []
for network, ref in tuples:
if network:
if ref:
seen_ref.add(ref)
new_tuples.append((network, ref))
elif ref is not None and ref not in seen_ref:
# network is None, fall back to the country code
new_tuples.append((country_code, ref))
tuples = new_tuples
if tuples:
# expose first network as network/shield_text
network, ref = tuples[0]
properties[prefix + 'network'] = network
if ref is not None:
properties[prefix + 'shield_text'] = ref
if 0 < len(ref) <= 7:
properties[prefix + 'shield_text_length'] = str(len(ref))
# replace properties with sorted versions of themselves
properties[all_networks] = [n[0] for n in tuples]
properties[all_shield_texts] = [n[1] for n in tuples]
return properties
|
def _argsort(seq):
"""The numpy sort is inconistent with the matlab version for values that
are the same
"""
# http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
return sorted(range(len(seq)), key=seq.__getitem__)
|
def headtail(values, classes=5):
"""
New head tails classification scheme,
claimed to better highlight a few very
large values than natural breaks.
See: http://arxiv.org/ftp/arxiv/papers/1209/1209.2801.pdf
"""
# if too few values, just return breakpoints for each unique value, ignoring classes
if len(values) == 1:
return values * 2
def _mean(values):
return sum(values)/float(len(values))
def _mbreak(values):
m = _mean(values)
head = [v for v in values if v >= m]
tail = [v for v in values if v < m]
return head,m,tail
breaks = []
head,m,tail = _mbreak(values)
while len(tail) > len(head):
breaks.append(m)
if len(head) > 1:
head,m,tail = _mbreak(head)
else:
break
# add first and last endpoints
breaks.insert(0, values[0])
breaks.append(values[-1])
# merge top breaks until under maxclasses
if classes and len(breaks) > classes:
pass
return breaks
|
def __is_quote_record_valid(record) -> bool:
"""[summary]
Arguments:
record {[type]} -- [description]
Returns:
bool -- [description]
"""
if "fields" not in record:
print("Quote record has no fields")
return False
if "Quote" not in record["fields"]:
print("Quote record has no 'Quote' field")
return False
if "Source" not in record["fields"]:
print("Quote record has no 'Source' field")
return False
return True
|
def func_bfca667e3c6c48a0856c692d8a707e80(N, S, psum):
"""mingain = psum
for i in range(N):
for j in range(i+1):
gain = max(S[j],S[i]-S[j],psum-S[i])
mingain = min(mingain,gain)
return float(psum-mingain)/psum"""
mingain = psum
minpgain = psum
hpi = 0
for i in range(N):
j = hpi
while j <= i:
pgain = max(S[j], S[i] - S[j])
gain = max(S[j], S[i] - S[j], psum - S[i])
mingain = min(mingain, gain)
if 2 * S[j] > S[i]:
break
if pgain <= minpgain:
hpi = j
j = j + 1
return float(psum - mingain) / psum
|
def cred_def_id2seq_no(cd_id: str) -> int:
"""
Given a credential definition identifier, return its schema sequence number.
:param cd_id: credential definition identifier
:return: sequence number
"""
return int(cd_id.split(':')[-2])
|
def parse_typename(typename):
"""parses a string of type namespace/type into a tuple of (namespace, type)"""
if typename is None:
raise ValueError("function type must be provided")
idx = typename.rfind("/")
if idx < 0:
raise ValueError("function type must be of the from namespace/name")
namespace = typename[:idx]
if not namespace:
raise ValueError("function type's namespace must not be empty")
type = typename[idx + 1:]
if not type:
raise ValueError("function type's name must not be empty")
return namespace, type
|
def read_table (lines):
"""Reads to the next divider line.
Read lines are returned, 'lines' is reduced to everything remaining.
"""
table_lines = []
while len(lines):
popline = lines[0]
lines = lines[1:]
if popline[:6] == "======":
break
table_lines += [popline]
return table_lines
|
def egcd(a, b):
"""Computes x, y such that gcd(a,b) = ax + by"""
if not b:
return 1, 0
x, y = egcd(b, a % b)
return y, x - (a // b * y)
|
def _json_mask(compcor_cols_filt, confounds_json, mask):
"""Extract anat compcor components from a given mask."""
return [
compcor_col
for compcor_col in compcor_cols_filt
if confounds_json[compcor_col]["Mask"] in mask
]
|
def detect_binary_blocks(vec_bin):
""" detect the binary object by beginning, end and length in !d signal
:param list(bool) vec_bin: binary vector with 1 for an object
:return tuple(list(int),list(int),list(int)):
>>> vec = np.array([1] * 15 + [0] * 5 + [1] * 20)
>>> detect_binary_blocks(vec)
([0, 20], [15, 39], [14, 19])
"""
begins, ends, lengths = [], [], []
# in case that it starts with an object
if vec_bin[0]:
begins.append(0)
length = 0
# iterate over whole array, skip the first one
for i in range(1, len(vec_bin)):
if vec_bin[i] > vec_bin[i - 1]:
begins.append(i)
elif vec_bin[i] < vec_bin[i - 1]:
ends.append(i)
lengths.append(length)
length = 0
elif vec_bin[i] == 1:
length += 1
# in case that it ends with an object
if vec_bin[-1]:
ends.append(len(vec_bin) - 1)
lengths.append(length)
return begins, ends, lengths
|
def not_followed_by(pattern):
""" matches if the current position is not followed by the pattern
:param pattern: an `re` pattern
:type pattern: str
:rtype: str
"""
return r'(?!{:s})'.format(pattern)
|
def dict_to_namevec(process_dict):
"""
Converts a process dict to a name vec
"""
name_vec = ''
name_vec += process_dict['type']
if 'environment' in process_dict:
name_vec += process_dict['environment']
if 'dataset' in process_dict:
name_vec += process_dict['dataset']
name_vec += process_dict['experiment']
return name_vec
|
def from_string_to_bytes(a):
"""
Based on project: https://github.com/chaeplin/dashmnb.
"""
return a if isinstance(a, bytes) else bytes(a, 'utf-8')
|
def _get_time(string):
"""
helper method which takes string of YYYY-MM-DD format, removes dashes so
relative times can be compared for plotting
also removes day, so we have data split by months
"""
string = string[0:7] # Drop day
return string.replace("-", "")
|
def sanitize_id(value):
"""Takes first non-whitespace as ID, replaces pipes with underscore
Cribbed from https://stackoverflow.com/a/295466/1628971
"""
value = value.split()[0].replace("|", "__")
return value
|
def _canonicalizePath(path):
"""
Support passing in a pathlib.Path-like object by converting to str.
"""
import sys
if sys.version_info[0] >= 3:
return str(path)
else:
# On earlier Python versions, str is a byte string, so attempting to
# convert a unicode string to str will fail. Leave it alone in this case.
return path
|
def rosenbrock(individual):
"""Rosenbrock test objective function.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- none
* - Global optima
- :math:`x_i = 1, \\forall i \in \\lbrace 1 \\ldots N\\rbrace`, :math:`f(\mathbf{x}) = 0`
* - Function
- :math:`f(\\mathbf{x}) = \\sum_{i=1}^{N-1} (1-x_i)^2 + 100 (x_{i+1} - x_i^2 )^2`
.. plot:: code/benchmarks/rosenbrock.py
:width: 67 %
"""
return sum(100 * (x * x - y)**2 + (1. - x)**2 \
for x, y in zip(individual[:-1], individual[1:])),
|
def edit_args_dict(key, new_value):
"""Edit defaulted argument dictionary and return it.
Args:
key (str): Key of the dictionary to change from default.
new_value (str, boolean): New value to set key dictionary entry to.
Returns:
Args dictionary with argument specified modification applied
"""
defaulted_args_dict = {
'begin': None,
'finish': False,
'current': False,
'summary': None,
'list': False,
'tag': None,
'edit': None,
'remove': None,
}
defaulted_args_dict[key] = new_value
return defaulted_args_dict
|
def validate_number(number_str, a, b):
"""
return float(number_str) if number_str is a number and is in the range [a, b],
otherwise return None
"""
try:
n = float(number_str)
if a <= n <= b:
return n
else: return None
except ValueError:
return None
|
def handler_ix(dest: list, el) -> int:
"""Returns the index of element in dest, with some app.yaml awareness.
Specifically, it checks if el has the attributes of an handler and if it
does, it will consider two elements to be the same and override one another
if they have the same url and apply the same strategy to serve files.
This is important as - for a given url - there can only be a single
handler, so the configurations need to be merged.
"""
if not isinstance(el, dict) or not "url" in el:
try:
return dest.index(el)
except ValueError:
return -1
for ix, existing in enumerate(dest):
# See docstring for explanation. Tl;Dr: one url config overrides
# another if the url is the same, and if both configs are static_files
# or both configs are static_dir.
# A static_dir and a static_files entry can coexist for the same
# even if they refer to the same url.
if ("url" in existing and existing["url"] == el["url"] and
(("static_dir" in existing and "static_dir" in el) or
("static_files" in existing and "static_files" in el))):
return ix
return -1
|
def truncate(value,arg):
"""Truncates a string of a given length, adds three dots at the end."""
try:
if len(value) > arg:
return "%s..." % value[0:arg-3]
else:
return value
except ValueError:
pass
|
def is_int(v):
"""Return True of v is an integer, False otherwise."""
# From https://stackoverflow.com/questions/1265665/python-check-if-a-string-represents-an-int-without-using-try-except
v = str(v).strip()
return v=='0' or (v if v.find('..') > -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit()
|
def _SubMethodArgs(cExpr, knownMethods):
""" alters the arguments of calls to calculator methods
*Not intended for client use*
This is kind of putrid (and the code ain't so pretty either)
The general idea is that the various special methods for atomic
descriptors need two extra arguments (the composition and the atomic
dict). Rather than make the user type those in, we just find
invocations of these methods and fill out the function calls using
string replacements.
"""
res = cExpr
for method in knownMethods:
p = 0
while p != -1 and p < len(res):
p = res.find(method, p)
if p != -1:
p = p + len(method) + 1
start = p
parenCount = 1
while parenCount and p < len(res):
if res[p] == ')':
parenCount = parenCount - 1
elif res[p] == '(':
parenCount = parenCount + 1
p = p + 1
if p <= len(res):
res = res[0:start] + "'%s',compos,atomDict" % (res[start:p - 1]) + res[p - 1:]
return res
|
def get_line_cache_pattern(row, nbands, regex=False):
""" Returns a pattern for a cache file from a certain row
This function is useful for finding all cache files from a line, ignoring
the number of images in the file.
Args:
row (int): line of the dataset for output
nbands (int): number of bands in dataset
regex (bool, optional): return a regular expression instead of glob
style (default: False)
Returns:
str: filename pattern for cache files from line ``row``
"""
wildcard = '.*' if regex else '*'
pattern = 'yatsm_r{l}_n{w}_b{b}.npy.npz'.format(
l=row, w=wildcard, b=nbands)
return pattern
|
def strip_line_comment(line: str):
"""
Finds the start of a comment in the line, if any, and returns the line
up to the comment, the token that started the comment (#, //, or /*),
and the line after the comment token
"""
comment_tokens = ['#', '//', '/*']
# manual iteration; trying to avoid a bunch of repeated "in" searches
index = 0
while index < len(line):
for token in comment_tokens:
if index > len(line) - len(token):
continue
if line[index:index + len(token)] == token and \
line[0:index].replace('\\"', '').count('"') % 2 == 0:
# we are not in a string, so this marks the start of a comment
return line[0:index], token, line[index + len(token):]
index += 1
# abcd#
return line, None, None
|
def parse_head_pruning_descriptors(
descriptors,
reverse_descriptors=False,
n_heads=None
):
"""Returns a dictionary mapping layers to the set of heads to prune in
this layer (for each kind of attention)"""
to_prune = {
"E": {},
"A": {},
"D": {},
}
for descriptor in descriptors:
attn_type, layer, heads = descriptor.split(":")
layer = int(layer) - 1
heads = set(int(head) - 1 for head in heads.split(","))
if layer not in to_prune[attn_type]:
to_prune[attn_type][layer] = set()
to_prune[attn_type][layer].update(heads)
# Reverse
if reverse_descriptors:
if n_heads is None:
raise ValueError("You need to specify the total number of heads")
for attn_type in to_prune:
for layer, heads in to_prune[attn_type].items():
to_prune[attn_type][layer] = set([head for head in range(n_heads)
if head not in heads])
return to_prune
|
def FormatIntegralLastKey(value):
"""Formats an integral last key as a string, zero-padding up to 15 digits of precision.
15 digits is enough precision to handle any conceivable values we'll need to return.
"""
assert value < 1000000000000000, value
return '%015d' % value
|
def ListToStr(val):
""" Takes a list of ints and makes it into a string """
return ''.join(['%c' % c for c in val])
|
def title_case(sentence):
"""
Convert a string to title case.
Title case means that the first letter of each word is capitalized, and all other letters in the word are lowercase.
Parameters
----------
sentence: str
String to be converted to title case
Returns
-------
ret: str
String converted to title case.
Example
-------
>>> title_case('ThIS is a STRinG to BE ConVerTeD.')
'This Is A String To Be Converted.'
"""
# Check that input is string
if not isinstance(sentence, str):
raise TypeError('Invalid input, type %s - Input must be type string' %(type(sentence)))
# Capitalize first letter
ret = sentence[0].upper()
# Loop through the rest of the characters
for i in range(1, len(sentence)):
if sentence[i - 1] == ' ':
ret = ret + sentence[i].upper()
else:
ret = ret + sentence[i].lower()
return ret
|
def build_complement(base):
"""
:param base: str, the DNA sequence users input.
:return: str, the complement of the entered DNA sequence.
"""
strand = ''
for i in range(len(base)):
ch = base[i]
if ch == 'A':
strand += 'T'
if ch == 'T':
strand += 'A'
if ch == 'C':
strand += 'G'
if ch == 'G':
strand += 'C'
return strand
|
def dim(rgb, mul=0.6):
"""Returns a dimmer version of a color. If multiplier > 1, a lighter color
can be produced as well."""
return tuple(map(lambda x: min(1000, round(x * mul)), rgb))
|
def sparsify(d):
"""
http://code.activestate.com/recipes/198157-improve-dictionary-lookup-performance/
Created by Raymond Hettinger on Sun, 4 May 2003 (PSF)
Reduce average dictionary lookup time by making the internal tables more sparse.
Improve dictionary sparsity.
The dict.update() method makes space for non-overlapping keys.
Giving it a dictionary with 100% overlap will build the same
dictionary in the larger space. The resulting dictionary will
be no more that 1/3 full. As a result, lookups require less
than 1.5 probes on average.
Example:
>>> sparsify({1: 3, 4: 5})
{1: 3, 4: 5}
"""
e = d.copy()
d.update(e)
return d
|
def manhatten_distance(first, second):
"""
Given two vectors, returns the manhatten distance between them
Requires that they are the same dimension
:param first: a vector
:param second: a vector
:return: the distance as a double
"""
if len(first) != len(second):
raise Exception("These vectors must be the same size")
return sum([abs(x - y) for x, y in zip(first, second)])
|
def rstrip_special(line, JUNK="\n \t"):
"""
Returns the given line stripped of specific trailing characters
(spaces, tabs, and newlines by default).
Note that line.rstrip() would also strip sundry control characters,
the loss of which can interfere with Emacs editing, for one thing.
(Used by tab-to-spaces converter code, for example.)
"""
i = len(line)
while i > 0 and line[i - 1] in JUNK:
i -= 1
return line[:i]
|
def multiply(t, p, n=6):
"""Multiply x and y"""
p += 1
print (t, p, n)
pepe = t * p * n
print (pepe)
return pepe
|
def is_error(splunk_record_key):
"""Return True if the given string is an error key.
:param splunk_record key: The string to check
:type splunk_record_key: str
:rtype: bool
"""
return splunk_record_key == 'error'
|
def levenshtein_distance(s1, s2):
"""from https://stackoverflow.com/a/32558749"""
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2+1]
for i1, c1 in enumerate(s1):
if c1 == c2:
distances_.append(distances[i1])
else:
distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1])))
distances = distances_
return distances[-1]
|
def determine_modules_for_dashboard(summaries, tx_id):
"""
Inspect the summary data for a given tx_id and determine
whether modules should be created for the different data types.
"""
module_types = {
'transactions_per_year': True,
'transactions_per_quarter': True
}
service_data = [data for data in summaries if data['service_id'] == tx_id]
quarterly_data = [datum for datum in service_data
if datum['type'] == 'quarterly']
seasonal_data = [datum for datum in service_data
if datum['type'] == 'seasonally-adjusted']
for datum in seasonal_data:
if datum.get('total_cost') is not None:
module_types['total_cost'] = True
break
for datum in seasonal_data:
if datum.get('cost_per_transaction') is not None:
module_types['cost_per_transaction'] = True
break
digital_takeup = False
for datum in seasonal_data:
if datum.get('digital_takeup') is not None:
digital_takeup = True
break
for datum in quarterly_data:
if datum.get('digital_takeup') is not None:
digital_takeup = True
break
if digital_takeup:
module_types['digital_takeup'] = True
return module_types
|
def check_required_param(param, data):
"""Check if `data` contains mandatory parameter `param`"""
if not data:
return error("Missing mandatory parameter {}".format(param))
try:
data[param]
except KeyError:
return error("Missing mandatory parameter {}".format(param))
return None
|
def replace_negative(l, default_value=0):
"""
Replaces all negative values with default_value
:param l: Original list
:param default_value: The value to replace negatives values with. Default is 0.
:return: Number of values replaced
"""
n_replaced = 0
for i in range(len(l)):
if l[i] < 0:
l[i] = default_value
n_replaced += 1
return n_replaced
|
def FivePointsDiff(fx, x, h=0.001):
"""
FivePointsDiff(@fx, x, h);
Use five points difference to approximatee the derivative of function fx
in points x, and with step length h
The function fx must be defined as a function handle with input
parameter x and the derivative as output parameter
Parameters
----------
fx : function
A function defined as fx(x)
x : float, list, numpy.ndarray
The point(s) of function fx to compute the derivatives
h : float, optional
The step size
Returns
-------
float, list, numpy.ndarray: The numerical derivatives of fx at x with
the same size as x and the type if from fx()
"""
return (-fx(x+2*h) + 8*fx(x+h) - 8*fx(x-h) + fx(x-2*h)) / (12.0*h)
|
def prime_factors(n):
"""Prime factorication.
Parameters
----------
n : int
Value which should be factorized into primes.
"""
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 is_admissible(action: int, x: int) -> bool:
""" Determine whether the `action` (0 or 1 corresponding to T0 or T1) is feasible\
for x. T0 is feasible for `x` iff `x` is even and T1 iff `x` is odd. """
return x%2 == action
|
def buildTickDistAndSubTicks(mintime, maxtime, minticks=3):
"""Calculates tick distance and subticks for a given domain."""
good = [1, 2, 5, 10, 30, # s
60, 2*60, 5*60, 10*60, 15*60, 30*60, # m
3600, 2*3600, 3*3600, 6*3600, 12*3600, # h
24*3600, 2*24*3600, 3*24*3600, 7*24*3600] # d
divs = [5, 4, 5, 5, 6,
6, 4, 5, 5, 3, 6,
6, 4, 6, 6, 6,
6, 6, 6, 7]
upscaling = [1, 2, 5, 10]
downscaling = [1, 0.5, 0.2, 0.1]
# calculate maxticks, depends on 'good' values
maxticks = minticks
for i in range(len(good)-1):
if maxticks < minticks * good[i+1]/good[i]:
maxticks = minticks * good[i+1]/good[i]
# determine ticking range
length = maxtime - mintime
maxd = length / minticks
mind = length / (maxticks+1)
# scale to useful numbers
scale_ind = 0
scale_fact = 1
scale = 1
while maxd * scale < good[0]: # too small ticking, increase scaling
scale_ind += 1
if scale_ind >= len(upscaling):
scale_fact *= upscaling[-1]
scale_ind = 1
scale = scale_fact * upscaling[scale_ind]
scale_ind = 0
while mind * scale > good[-1]: # too big ticking, decrease scaling
scale_ind += 1
if scale_ind >= len(downscaling):
scale_fact *= downscaling[-1]
scale_ind = 1
scale = scale_fact * downscaling[scale_ind]
# find a good value for ticking
tickdist = 0
subticks = 0
for i, d in enumerate(good):
if mind * scale <= d <= maxd * scale:
tickdist = d / scale
subticks = divs[i]
# check ticking
assert tickdist > 0
return tickdist, int(subticks)
|
def F_to_C(F):
"""
Convert Fahrenheit to Celsius
Args:
F : (float, or array of floats) temperature in degrees fahrenheit
Returns:
The input temperature in degrees celsius
"""
return (F-32) * 5/9
|
def get_image_mime_type(data: bytes) -> str:
"""Returns the image type from the first few bytes."""
if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
return "image/png"
elif data[0:3] == b"\xff\xd8\xff" or data[6:10] in (b"JFIF", b"Exif"):
return "image/jpeg"
elif data.startswith((b"\x47\x49\x46\x38\x37\x61", b"\x47\x49\x46\x38\x39\x61")):
return "image/gif"
elif data.startswith(b"RIFF") and data[8:12] == b"WEBP":
return "image/webp"
else:
raise ValueError("Unsupported image type given")
|
def autocorrect(user_word, valid_words, diff_function, limit):
"""Returns the element of VALID_WORDS that has the smallest difference
from USER_WORD. Instead returns USER_WORD if that difference is greater
than LIMIT.
"""
# BEGIN PROBLEM 5
"*** YOUR CODE HERE ***"
if user_word in valid_words:
return user_word
tmp_word = user_word
tmp_diff = limit
for w in valid_words:
curr_diff = diff_function(user_word, w, limit)
# decrease the lowest diff (tmp_diff) if necessary
# and deal with the situation when only one 'diff' reaches limit while others all above
if curr_diff < tmp_diff or curr_diff == tmp_diff == limit:
tmp_word = w
tmp_diff = curr_diff
return tmp_word
# END PROBLEM 5
|
def zchk(target):
"""Check if the input is zero"""
if target == 0:
return target + 1
return target
|
def find_hcf(a, b) :
""" Finds the Highest Common Factor among two numbers """
#print('HCF : ', a, b)
if b == 0 :
return a
return find_hcf(b, a%b)
|
def determine_is_fatal_error(current_error_message: str) -> bool:
""" Determine if a pipx error message is truly fatal """
acceptable_error_messages = [
'(_copy_package_apps:66): Overwriting file',
'(_symlink_package_apps:95): Same path'
]
for message in acceptable_error_messages:
if message in current_error_message:
return False
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.