content stringlengths 42 6.51k |
|---|
def _get_dev_port_var(backend, instance=None):
"""Return the environment variable for a backend port.
Backend ports are stored at GET_PORT_<backend> for backends
and GET_PORT_<backend>.<instance> for individual instances.
Args:
backend: The name of the backend.
instance: The backend instance (optional).
Returns:
string: The environment variable where the backend port is stored.
"""
port_var = 'BACKEND_PORT.%s' % str(backend).lower()
if instance is not None:
port_var = '%s.%d' % (port_var, instance)
return port_var |
def match_gene_txs_variant_txs(variant_gene, hgnc_gene):
"""Match gene transcript with variant transcript to extract primary and canonical tx info
Args:
variant_gene(dict): A gene dictionary with limited info present in variant.genes.
contains info on which transcript is canonical, hgvs and protein changes
hgnc_gene(dict): A gene object obtained from the database containing a complete list of transcripts.
Returns:
canonical_txs, primary_txs(tuple): columns containing canonical and primary transcript info
"""
canonical_txs = []
primary_txs = []
for tx in hgnc_gene.get("transcripts", []):
tx_id = tx["ensembl_transcript_id"]
# collect only primary of refseq trancripts from hgnc_gene gene
if not tx.get("refseq_identifiers") and tx.get("is_primary") is False:
continue
for var_tx in variant_gene.get("transcripts", []):
if var_tx["transcript_id"] != tx_id:
continue
tx_refseq = tx.get("refseq_id")
hgvs = var_tx.get("coding_sequence_name") or "-"
pt_change = var_tx.get("protein_sequence_name") or "-"
# collect info from primary transcripts
if tx_refseq in hgnc_gene.get("primary_transcripts", []):
primary_txs.append("/".join([tx_refseq or tx_id, hgvs, pt_change]))
# collect info from canonical transcript
if var_tx.get("is_canonical") is True:
canonical_txs.append("/".join([tx_refseq or tx_id, hgvs, pt_change]))
return canonical_txs, primary_txs |
def add_previous_traffic(index, incidents):
"""Adds traffic level for the preceeding hour to the incident"""
incidents[index]['previous_traffic'] = [incident['traffic_level'] for incident in reversed(incidents[index-6:index])]
return incidents[index] |
def get_locs(r1, c1, r2, c2):
"""Get ndarray locations of given bounds."""
rs = []
cs = []
for r in range(r1, r2 + 1):
for c in range(c1, c2 + 1):
rs.append(r)
cs.append(c)
return rs, cs |
def dimorphism_trunc(_):
"""Enrich the match."""
data = {'dimorphism': 'sexual dimorphism'}
return data |
def product(l1, l2):
"""returns the dot product of l1 and l2"""
return sum([i1 * i2 for (i1, i2) in zip(l1, l2)]) |
def scopes_to_string(scopes):
"""Converts scope value to a string.
If scopes is a string then it is simply passed through. If scopes is an
iterable then a string is returned that is all the individual scopes
concatenated with spaces.
Args:
scopes: string or iterable of strings, the scopes.
Returns:
The scopes formatted as a single string.
"""
if isinstance(scopes, str):
return scopes
else:
return ' '.join(scopes) |
def _warp_dir(intuple):
"""
Extract the ``restrict_deformation`` argument from metadata.
Example
-------
>>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "i-"}))
[[1, 0, 0], [1, 0, 0]]
>>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "j-"}))
[[0, 1, 0], [0, 1, 0]]
"""
pe = intuple[1]["PhaseEncodingDirection"][0]
return 2 * [[int(pe == ax) for ax in "ijk"]] |
def build_complement(dna):
"""
:param dna: str, a DNA sequence that users inputs.
:return: str, the complement DNA sequence of dna.
"""
ans = ''
for base in dna:
if base == 'A':
ans += 'T'
if base == 'T':
ans += 'A'
if base == 'C':
ans += 'G'
if base == 'G':
ans += 'C'
return ans |
def splittime(datetime_str=None, level=1):
"""Split a timeString
:param date_str: The ISO date string YYYY-DD-MM[ HH:MM:SS.UUU]
:param level: A value between 1 & 3 determining which part to remove -
date parts removed are replaced with '00
microsecond part is ALWAYS removed '
:return:
"""
return (':'.join(datetime_str.split(' ')[1].split(':')[0:level] + ['00'] * (3 - level)).split('.')[0]) if datetime_str else None |
def sliding_average(arr, k):
"""Find slinding averages of window size k for the elements of arr.
Time: O(n)
Space: O(1)
"""
averages = []
win_start = 0
win_sum = 0
for win_end in range(len(arr)):
win_sum += arr[win_end]
if win_end >= k - 1:
averages.append(win_sum / k)
win_sum -= arr[win_start]
win_start += 1
return averages |
def ngrams(text, n=3):
"""Return list of text n-grams of size n"""
return {text[i:i + n].lower() for i in range(len(text) - n + 1)} |
def _vcf_info(start, end, mate_id, info=None):
"""Return breakend information line with mate and imprecise location.
"""
out = "SVTYPE=BND;MATEID={mate};IMPRECISE;CIPOS=0,{size}".format(
mate=mate_id, size=end-start)
if info is not None:
extra_info = ";".join("{0}={1}".format(k, v) for k, v in info.iteritems())
out = "{0};{1}".format(out, extra_info)
return out |
def off_signal(obj, signal_type, func):
"""Disconnect a callback function from a signal."""
try:
# Disconnect from blocked functions not the temporary fake signal type used when blocked
if "blocked-" + signal_type in obj.event_signals:
sig = obj.event_signals["blocked-" + signal_type]
else:
sig = obj.event_signals[signal_type]
if func is None:
existed = len(sig) > 0
try:
sig.clear()
except AttributeError:
del sig[:] # Python 2.7
else:
existed = func in sig
try:
sig.remove(func)
except:
pass
return existed
except (KeyError, AttributeError):
return False |
def format_percent(d, t):
"""
Format a value as a percent of a total.
"""
return '{:.1%}'.format(float(d) / t) |
def replace_in_keys(src, existing='.', new='_'):
"""
Replace a substring in all of the keys of a dictionary (or list of dictionaries)
:type src: ``dict`` or ``list``
:param src: The dictionary (or list of dictionaries) with keys that need replacement. (required)
:type existing: ``str``
:param existing: substring to replace.
:type new: ``str``
:param new: new substring that will replace the existing substring.
:return: The dictionary (or list of dictionaries) with keys after substring replacement.
:rtype: ``dict`` or ``list``
"""
def replace_str(src_str):
if callable(getattr(src_str, "decode", None)):
src_str = src_str.decode('utf-8')
return src_str.replace(existing, new)
if isinstance(src, list):
return [replace_in_keys(x, existing, new) for x in src]
return {replace_str(k): v for k, v in src.items()} |
def spanish_to_english(dictionary, word):
"""Translates a Spanish word to English.
Current version this function is incapable of parsing translation
data within a metadata dict (see txt_to_dict documentation).
:param dict[str, str] dictionary:
Keys are an English word and the value is the respective Spanish
translation. Use this guideline when expanding an
English/Spanish dictionary or developing dictionaries for other
languages.
:param str word:
The Spanish word to be translated
:return:
The English translation of word if within dictionary, else None.
:rtype:
str or None
"""
for i in range(len(list(dictionary.values()))):
if list(dictionary.values())[i] == word:
return list(dictionary.keys())[i] |
def avg_guesses_smart(n):
"""
computes the avg. nr. of optimal-strategy guesses needed with n words
>>> avg_guesses_naive(100) - avg_guesses_smart(100)
0.0
"""
if n == 1:
return 1
pow2, k, sum_pow2, sum_guesses = 1, 1, 1, 1
while True:
rest = n - sum_pow2
pow2 *= 2
k += 1
if rest < pow2:
sum_guesses += rest * k
break
else:
sum_pow2 += pow2
sum_guesses += pow2 * k
return sum_guesses / n, sum_guesses |
def binary_search1(xs, x):
"""
Perform binary search for a specific value in the given sorted list
:param xs: a sorted list
:param x: the target value
:return: an index if the value was found, or None if not
"""
lft, rgt = 0, len(xs)
while lft < rgt:
mid = (lft + rgt) // 2
if xs[mid] == x:
return mid
if xs[mid] < x:
lft = mid + 1
else:
rgt = mid
return None |
def swap_namedtuple_dict(d):
"""
Turn {a:namedtuple(b,c)}
to namedtuple({a:b},{a:c})
"""
if not isinstance(d, dict):
return d
keys = list(d.keys())
for k, v in d.items():
assert v._fields == d[keys[0]]._fields
fields = d[keys[0]]._fields
t = []
for i in range(len(fields)):
t.append({key:d[key][i] for key in keys})
return d[keys[0]].__class__(*t) |
def make_payment(text):
"""Simply returns the args passed to it as a string"""
return "Made Payment! %s" % str(text) |
def luminance_to_contrast_ratio(luminance1, luminance2):
"""Calculate contrast ratio from a pair of relative luminance.
:param luminance1: Relative luminance
:type luminance1: float
:param luminance2: Relative luminance
:type luminance2: float
:return: Contrast ratio
:rtype: float
"""
(l1, l2) = sorted((luminance1, luminance2), reverse=True)
return (l1 + 0.05) / (l2 + 0.05) |
def expand_dict_lists(d):
"""Neat little function that expands every list in a dict. So instead of having one dict with
a list of 5 things + a list of 3 things, you get a list of 5x3=15 dicts with each dict
representing each possible permutation of things.
:param d: Dictionary that can contain some (or no) lists in the .values().
:returns: List of dictionaries with the lists in the .values() broken down.
"""
def _flatten(big_li):
"""Turns a list of lists into a single expanded list.
"""
flat_list = []
for sub_li in big_li:
if isinstance(sub_li, list): # make sure we only iterate over lists
for item in sub_li:
flat_list.append(item)
else:
flat_list.append(sub_li)
return flat_list
def _get_permutations(d):
"""Recursively breaks down each list in the .values() of the dict until there are no more
lists to break down.
"""
for key, val in d.items():
if isinstance(val, list):
return _flatten([
_get_permutations(
{**{key : i}, **{_k : _v for _k, _v in d.items() if _k != key}}
)
for i in val
])
return d
return _get_permutations(d) |
def get_version_without_patch(version):
"""
Return the version of Kili API removing the patch version
Parameters
----------
- version
"""
return '.'.join(version.split('.')[:-1]) |
def return_node_position(node_index):
"""Conversion of node_index to position tuple
:param node_index: id of respective node
:type: int
"""
return (node_index, None, None) |
def verify_rename_files(file_name_map):
"""
Each file name as key should have a non None value as its value
otherwise the file did not get renamed to something new and the
rename file process was not complete
"""
verified = True
renamed_list = []
not_renamed_list = []
for k, v in list(file_name_map.items()):
if v is None:
verified = False
not_renamed_list.append(k)
else:
renamed_list.append(k)
return (verified, renamed_list, not_renamed_list) |
def charCodeForNumber(i):
""" Returns a for 0, b for 1, etc. """
char = ""
while(i > 25):
char += chr(97 + (i % 25))
i = i - 25
char += chr(97 + i)
return char |
def split(l, sizes):
"""Split a list into sublists of specific sizes."""
if not sum(sizes) == len(l):
raise ValueError('sum(sizes) must equal len(l)')
sub_lists = []
ctr = 0
for size in sizes:
sub_lists.append(l[ctr:ctr+size])
ctr += size
return sub_lists |
def hsv_to_rgb(hue, sat, val):
"""
Convert HSV colour to RGB
:param hue: hue; 0.0-1.0
:param sat: saturation; 0.0-1.0
:param val: value; 0.0-1.0
"""
if sat == 0.0:
return (val, val, val)
i = int(hue * 6.0)
p = val * (1.0 - sat)
f = (hue * 6.0) - i
q = val * (1.0 - sat * f)
t = val * (1.0 - sat * (1.0 - f))
i %= 6
if i == 0:
return (val, t, p)
if i == 1:
return (q, val, p)
if i == 2:
return (p, val, t)
if i == 3:
return (p, q, val)
if i == 4:
return (t, p, val)
if i == 5:
return (val, p, q) |
def longest_bar_len(bars_in_frames):
"""
DEPRECATED
Returns the size of the longest bar among all, in number of frames.
Parameters
----------
bars_in_frames : list of tuples of integers
The bars, as tuples (start, end), in number of frames.
Returns
-------
max_len : integer
The size of the longest bar.
"""
max_len = 0
for bar in bars_in_frames:
if bar[1] - bar[0] > max_len:
max_len = bar[1] - bar[0]
return max_len |
def get_feature_suffix(feature_name: str) -> str:
"""Gets the suffix of a feature from its name."""
if "_" not in feature_name:
return ""
return feature_name.split("_")[-1] |
def get_non_empty_text_from_doc(doc) -> str:
"""
Build document text from title + abstract
:param doc: S2 paper
:return: Document text
"""
text = ''
if 'title' in doc:
text += doc['title']
if doc['abstract']:
text += '\n' + doc['abstract']
if doc['body_text']:
text += '\n' + doc['body_text']
if len(text) == 0:
# Ensure text is at least one char to make tokenizers work.
text = ' '
return text |
def factorial(n: int) -> int:
"""
Recursion function.
>>> factorial(0)
1
>>> factorial(1)
1
>>> factorial(5)
120
>>> factorial(6)
720
"""
return 1 if n == 0 or n == 1 else n * factorial(n - 1) |
def c_sum32(*args):
"""
Add all elements of *args* within the uint32 value range.
>>> c_sum32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF)
4294967293
"""
return sum(args) & 0xFFFFFFFF |
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return response
n = options['groups']
return list(zip(*[response[i::n] for i in range(n)])) |
def joinSet(itemSet, length):
"""Join a set with itself and returns the n-element itemsets"""
return set([i.union(j) for i in itemSet for j in itemSet if len(i.union(j)) == length]) |
def _is_int_expression(s):
"""
copied from
https://qiita.com/agnelloxy/items/137cbc8651ff4931258f
"""
try:
int(s)
return True
except ValueError:
return False |
def get_atoms_per_fu(doc):
""" Calculate and return the number of atoms per formula unit.
Parameters:
doc (list/dict): structure to evaluate OR matador-style stoichiometry.
"""
if 'stoichiometry' in doc:
return sum([elem[1] for elem in doc['stoichiometry']])
return sum([elem[1] for elem in doc]) |
def convert_datastores_to_hubs(pbm_client_factory, datastores):
"""Convert given datastore morefs to PbmPlacementHub morefs.
:param pbm_client_factory: Factory to create PBM API input specs
:param datastores: list of datastore morefs
:returns: list of PbmPlacementHub morefs
"""
hubs = []
for ds in datastores:
hub = pbm_client_factory.create('ns0:PbmPlacementHub')
hub.hubId = ds.value
hub.hubType = 'Datastore'
hubs.append(hub)
return hubs |
def fmt_msg(event, payload=None, serial=None):
"""
Packs a message to be sent to the server.
Serial is a function to call on the frame to serialize it, e.g:
json.dumps.
"""
frame = {
'e': event,
'p': payload,
}
return serial(frame) if serial else frame |
def trimText(message):
"""
This functions cleans the string
It removes all the characters without A-Z, a-z
:param message: The string which I want to trim
:return: returns a string
"""
trimmed_text = []
for i in range(len(message)):
if 'A' <= message[i] <= 'Z' or 'a' <= message[i] <= 'z':
trimmed_text.append(message[i])
return "".join(trimmed_text) |
def cmake_cache_entry(name, value):
"""
Helper that creates CMake cache entry strings used in
'host-config' files.
"""
return 'set({0} "{1}" CACHE PATH "")\n\n'.format(name, value) |
def distL1(x1,y1, x2,y2):
"""Compute the L1-norm (Manhattan) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
return int(abs(x2-x1) + abs(y2-y1)+.5) |
def sqrt(target):
"""
Find the square root of the given number
If the square root is not an integer, the next lowest integer is returned. If the square root cannot be determined,
None is returned.
:param target: The square
:return: int or None
"""
# Explicitly handle the edge-cases here
if target < 0:
return None
if target <= 1:
return target
lowest, highest = 2, target // 2
while lowest <= highest:
candidate = ((highest - lowest) // 2) + lowest
sq_candidate = candidate * candidate
if sq_candidate == target:
return candidate
if sq_candidate > target:
highest = candidate - 1
else:
# If the next largest number squared is greater than the target, return the current candidate
sq_candidate_plus = (candidate + 1) * (candidate + 1)
if sq_candidate_plus > target:
return candidate
lowest = candidate + 1
# If we got this far, all hope is lost
return None |
def fact(n):
"""doc"""
# r : Number
r = 1
# i : int
i = 2
while i <= n:
r = r * i
i = i + 1
print("i="+str(i))
return r |
def fields_to_batches(d, keys_to_ignore=[]):
"""
The input is a dict whose items are batched tensors. The output is a list of dictionaries - one
per entry in the batch - with the slices of the tensors for that entry. Here's an example.
Input:
d = {"a": [[1, 2], [3,4]], "b": [1, 2]}
Output:
res = [{"a": [1, 2], "b": 1}, {"a": [3, 4], "b": 2}].
"""
keys = [key for key in d.keys() if key not in keys_to_ignore]
# Make sure all input dicts have same length. If they don't, there's a problem.
lengths = {k: len(d[k]) for k in keys}
if len(set(lengths.values())) != 1:
msg = f"fields have different lengths: {lengths}."
# If there's a doc key, add it to specify where the error is.
if "doc_key" in d:
msg = f"For document {d['doc_key']}, " + msg
raise ValueError(msg)
length = list(lengths.values())[0]
res = [{k: d[k][i] for k in keys} for i in range(length)]
return res |
def extractLeafs(nt, leafDict):
"""Given a newick tree object, it returns a dict of
leaf objects. Operates recursively.
"""
if nt is None:
return None
nt.distance = 0
if nt.right is None and nt.left is None:
leafDict[nt.iD] = True
else:
extractLeafs(nt.right, leafDict = leafDict)
extractLeafs(nt.left , leafDict = leafDict) |
def Usable(entity_type, entity_ids_arr):
"""For a MSVC solution file ending with .sln"""
file_path = entity_ids_arr[0]
return file_path.endswith(".sln") |
def subs(task, key, val):
""" Perform a substitution on a task
Examples
--------
>>> subs((inc, 'x'), 'x', 1) # doctest: +SKIP
(inc, 1)
"""
type_task = type(task)
if not (type_task is tuple and task and callable(task[0])): # istask(task):
try:
if type_task is type(key) and task == key:
return val
except Exception:
pass
if type_task is list:
return [subs(x, key, val) for x in task]
return task
newargs = []
for arg in task[1:]:
type_arg = type(arg)
if type_arg is tuple and arg and callable(arg[0]): # istask(task):
arg = subs(arg, key, val)
elif type_arg is list:
arg = [subs(x, key, val) for x in arg]
elif type_arg is type(key):
try:
# Can't do a simple equality check, since this may trigger
# a FutureWarning from NumPy about array equality
# https://github.com/dask/dask/pull/2457
if len(arg) == len(key) and all(type(aa) == type(bb) and aa == bb
for aa, bb in zip(arg, key)):
arg = val
except (TypeError, AttributeError):
# Handle keys which are not sized (len() fails), but are hashable
if arg == key:
arg = val
newargs.append(arg)
return task[:1] + tuple(newargs) |
def quote(string: str) -> str:
"""
Wrap a string with quotes iff it contains a space. Used for interacting with command line scripts.
:param string:
:return:
"""
if ' ' in string:
return '"' + string + '"'
return string |
def make_divisible(v, divisor=8, min_value=None):
"""
make `v` divisible
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor/2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%
if new_v < 0.9 * v:
new_v += divisor
return new_v |
def square(n):
"""Returns the square of a number."""
squared = n ** 2
print ("%d squared is %d." % (n, squared))
return squared |
def jaccard_similarity(query, document):
"""Not used for now"""
intersection = set(query).intersection(set(document))
union = set(query).union(set(document))
return len(intersection)/len(union) |
def is_podcast_episode_id(item_id):
"""Validate if ID is in the format of a Google Music podcast episode ID."""
return len(item_id) == 27 and item_id.startswith('D') |
def _xypointlist(a):
"""formats a list of xy pairs"""
s = ''
for e in a: # this could be done more elegant
s += str(e)[1:-1] + ' '
return s |
def factorial_dp(n):
"""Nth number of factorial series by bottom-up DP.
- Time complexity: O(n).
- Space complexity: O(n).
"""
T = [0 for _ in range(n + 1)]
T[0] = 1
T[1] = 1
for k in range(2, n + 1):
T[k] = k * T[k - 1]
return T[n] |
def is_array_like(item):
"""
Checks to see if something is array-like.
>>> import numpy as np
>>> is_array_like([])
True
>>> is_array_like(tuple())
True
>>> is_array_like(np.ndarray([]))
True
>>> is_array_like("hello")
False
>>> is_array_like(1)
False
>>> is_array_like(2.3)
False
>>> is_array_like(np)
False
"""
return (not hasattr(item, "strip") and
(hasattr(item, "__getitem__") or
hasattr(item, "__iter__"))) |
def update_or_add_message(msg, name, sha):
"""
updates or builds the github version message for each new asset's sha256.
Searches the existing message string to update or create.
"""
new_text = '{0}: {1}\n'.format(name, sha)
start = msg.find(name)
if (start != -1):
end = msg.find("\n", start)
if (end != -1):
return msg.replace(msg[start:end+1], new_text)
back = msg.rfind("```")
if (back != -1):
return '{0}{1}```'.format(msg[:back], new_text)
return '{0} \n### SHA256 Checksums:\n```\n{1}```'.format(msg, new_text) |
def _GetIndentedString(indentation, msg):
""" Return `msg` indented by `indentation` number of spaces
"""
return ' ' * indentation + msg |
def unsplit(f):
""" join a list of strings, adds a linefeed """
ln = ""
for s in f:
ln = "%s %s" % (ln, s)
ln = ln + "\n"
return ln |
def teste(area):
"""Rederizando uma view com o decorador do jinja."""
return dict(nome=area) |
def _get_domain(email):
"""Get the domain of an email address (eg. gmail.com in hello@gmail.com)
"""
comps = email.split("@")
if len(comps) != 2:
return None
return comps[1] |
def formula2components(formula):
"""Convert a glass/any composition formula to component dictionary.
Parameters
----------
formula : string
Glass/any composition for e.g. 50Na2O-50SiO2.
Returns
-------
dictionary
Dictionary where keys are components of glass/any composition and values are their ratio.
"""
dict1 = {}
parts = formula.split('-')
if len(parts)==1:
dict1[parts[0]] = 1.0
else:
for i in parts:
k = ''
p = ''
for ind, j in enumerate(i):
try:
float(j)
p += j
except:
if j == '.':
p += j
else:
k = i[ind:]
break
dict1[k] = float(p)
if sum(dict1.values())==100:
for k,v in dict1.items():
dict1[k] = dict1[k]/100
return dict1
elif sum(dict1.values())==1.0:
return dict1
else:
try:
raise Exception("Invalid Formula: {}.".format(formula))
except Exception as e:
print(e)
raise |
def duration_formatted(seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '):
"""
Takes an amount of seconds (as an into or float) and turns it into a human-readable amount of time.
"""
# the formatted time string to be returned
time = []
# the pieces of time to iterate over (days, hours, minutes, etc)
# - the first piece in each tuple is the suffix (d, h, w)
# - the second piece is the length in seconds (a day is 60s * 60m * 24h)
parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52),
(suffixes[1], 60 * 60 * 24 * 7),
(suffixes[2], 60 * 60 * 24),
(suffixes[3], 60 * 60),
(suffixes[4], 60),
(suffixes[5], 1)]
# for each time piece, grab the value and remaining seconds,
# and add it to the time string
for suffix, length in parts:
if length == 1:
value = seconds
else:
value = int(seconds / length)
if value > 0 or length == 1:
if length == 1:
if isinstance(value, int):
svalue = "{}".format(value)
else:
svalue = "{:.2f}".format(value)
else:
svalue = str(int(value))
seconds = seconds % length # Remove the part we are printing now
time.append('%s%s' % (svalue, (suffix, (suffix, suffix + 's')[value > 1])[add_s]))
return separator.join(time) |
def style_category(category):
"""Return predefined Boostrap CSS classes for each banner category."""
css_class = "alert alert-{}"
if category == "warning":
css_class = css_class.format("warning")
elif category == "other":
css_class = css_class.format("secondary")
else:
css_class = css_class.format("primary")
return css_class |
def create_api_host_url(host, endpoints):
""" create_api_host_url
Creates the endpoint url for the API call.
INPUTS
@host [str]: The base URL for the API call.
@endpoints [list]: The API endpoint names for the chosen method
RETURNS
@api_url [str]: The full endpoint url for the method.
"""
api_url = '/'.join((host, *endpoints))
return api_url |
def calculate_single_gpa(score):
"""
Calculate gpa with a score.
Use a lookup table to calculate a single gpa.
Empty scores or scores not between 0 and 100 will be regarded as 0.
"""
lookup_table = [0.0] * 60 + [1.0] * 4 + [1.5] * 4 + [2.0] * 4 + \
[2.3] * 3 + [2.7] * 3 + [3.0] * 4 + [3.3] * 3 + [3.7] * 5 + [4.0] * 11
return 0.0 if score is None or score < 0 or score > 100 else lookup_table[
int(score)] |
def fixedsplit(text, separator=None, maxsplit=-1):
"""Split a string and return a fixed number of parts"""
parts = text.split(separator, maxsplit)
maxparts = maxsplit + 1
missing = maxparts - len(parts)
if missing > 0:
parts = parts + (missing * [""])
return parts |
def stationary(t):
"""Probe is stationary at location h = 2, v = 0"""
return 0.*t, 2/16 + 0*t, 0*t |
def check_permutation(s, t):
"""
Check if s and t are permutations of each other
Check if each character in s is in t
this solution is incorrect because there can be a situation when s and t
are the same length but have different number of a character.
Ex. aarp != arrp
but efficiency is O(n^2) space is O(1)
"""
if len(s) is not len(t):
return False
for r in s:
if r not in t:
return False
return True |
def norm_angle(a):
"""Return the given angle normalized to -180 < *a* <= 180 degrees."""
a = (a + 360) % 360
if a > 180:
a = a - 360
return a |
def valid_operation(x: str) -> bool:
"""
Whether or not an opcode is valid
:param x: opcode
:return: whether or not the supplied opcode is valid
"""
return not x.startswith("__") and not x == "bytecode_format" |
def name_of_variable(var):
"""Return the name of an object"""
for n,v in globals().items():
print(n)
if id(v) == id(var):
return n
return None |
def count_digits(n: int) -> int:
"""Counts the digits of number in base 10.
Args:
n: A non-negative integer.
Returns:
The number of digits in the base-10 representation of ``n``.
"""
return len(str(n)) |
def itofm(i):
"""Converts midi interval to frequency multiplier."""
return 2 ** (i / 12.0) |
def is_year_leap(year):
"""Checks if year is leap, and returns result"""
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False |
def _validate_dataset_id(dataset_id, parent):
"""Ensure the dataset ID is set appropriately.
If ``parent`` is passed, skip the test (it will be checked / fixed up
later).
If ``dataset_id`` is unset, attempt to infer the ID from the environment.
:type dataset_id: string
:param dataset_id: A dataset ID.
:type parent: :class:`gcloud.datastore.key.Key` or ``NoneType``
:param parent: The parent of the key or ``None``.
:rtype: string
:returns: The ``dataset_id`` passed in, or implied from the environment.
:raises: :class:`ValueError` if ``dataset_id`` is ``None`` and no dataset
can be inferred from the parent.
"""
if parent is None:
if dataset_id is None:
raise ValueError("A Key must have a dataset ID set.")
return dataset_id |
def start_point(upper_int):
""" Get the circle that this element is in, and its first elem """
n, last, start = 1, 1, 2
while start < upper_int:
last = start
start = (4*pow(n, 2)) + (4*n) + 2
n += 1
return (last, n) |
def if_not_null(data, f):
"""
Execute the given function if the data is not null
:param data:
:param f:
:return: f(data) if data != None, else None
"""
if data:
return f(data)
return None |
def make_initial_state(supporters):
"""
Creates a string of alternating Tottenham(T) and Arsenal(A) supporters
of length 'supporters' with two blank seats represented by two underscores
at the end of the string.
make_initial_state(int) -> str
"""
return "TA"*supporters + "__" |
def isIn(char, aStr):
"""
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
"""
if len(aStr) <= 1:
return char == aStr
middle_index = len(aStr) // 2
middle_char = aStr[middle_index]
if char == middle_char:
return True
elif char < middle_char:
return isIn(char, aStr[:middle_index])
else:
return isIn(char, aStr[middle_index:]) |
def _get_rekey_ddi_data(ddi_data):
"""Takes a list of lists of dict's and converts to a list of dict's, of
dicts. As well as rekey's the dict's with the network address."""
for enum, item in enumerate(ddi_data):
ddi_data[enum] = dict((d['network'],
dict(d, index=index))
for (index, d) in enumerate(item))
return ddi_data |
def find_nested_key(my_json, find_key):
"""Search in a nested dict for a key or None."""
if find_key in my_json:
return my_json[find_key]
for _, vval in my_json.items():
if isinstance(vval, dict):
item = find_nested_key(vval, find_key)
if item is not None:
return item
return None |
def parse_name(name):
"""
extract the important stuff from the array filename.
Returning the parent image the file is from.
Parameters:
------------
name: string
file path of the numpy array
Returns:
---------
string:
e.g "MCF7_img_13_90.npy"
will return "MCF7_13"
"""
# remove the file suffix
assert name.endswith(".npy")
cell_line, _, img_num, _ = name.split(".")[0].split("_")
return "_".join([cell_line, img_num]) |
def _self_interactions(num_qubits):
"""Return the indices corresponding to the self-interactions."""
interactions = []
for qubit in range(num_qubits):
for pindex in range(1, 4):
term = [0] * num_qubits
term[qubit] = pindex
interactions.append(tuple(term))
return interactions |
def convert(s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if len(s) <= 0 or len(s) <= numRows or numRows == 1:
return s
list = {}
row = 0
add = True
for i in range(len(s)):
s1 = ''
if row in list:
s1 = list[row]
list[row] = s1 + s[i]
if add:
row += 1
else:
row -= 1
if row == numRows - 1:
add = False
elif row == 0:
add = True
return ''.join(list.values()) |
def cleanup_code(content):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
return content.strip('` \n') |
def derive_param_default(obj_param):
"""Derive a parameter default
Parameters
----------
obj_param : dict
* parameter dict from TaniumPy object
Returns
-------
def_val : str
* default value derived from obj_param
"""
# get the default value for this param if it exists
def_val = obj_param.get('defaultValue', '')
# get requireSelection for this param if it exists (pulldown menus)
req_sel = obj_param.get('requireSelection', False)
# get values for this param if it exists (pulldown menus)
values = obj_param.get('values', [])
# if this param requires a selection and it has a list of values
# and there is no default value, use the first value as the
# default value
if req_sel and values and not def_val:
def_val = values[0]
return def_val |
def inverse_hybrid_transform(value):
"""
Transform back from the IRAF-style hybrid log values.
This takes the hybrid log value and transforms it back to the
actual value. That value is returned. Unlike the hybrid_transform
function, this works on single values not a numpy array. That is because
one is not going to have a data array in the hybrid transformation form.
Parameters
----------
value : A real number to be transformed back from the hybrid
log scaling
Returns
-------
newvalue : The associated value that maps to the given hybrid
log value.
"""
if value < 0.:
workvalue = -1.0*value
sign = -1.0
else:
workvalue = value
sign = +1.0
if workvalue < 1.0:
newvalue = 10.*workvalue
else:
newvalue = 10.**workvalue
newvalue = sign * newvalue
return newvalue |
def fast_exponentiation(a, p, n):
"""Calculates r = a^p mod n
"""
result = a % n
remainders = []
while p != 1:
remainders.append(p & 1)
p = p >> 1
while remainders:
rem = remainders.pop()
result = ((a ** rem) * result ** 2) % n
return result |
def float_repr(value, precision_digits):
"""Returns a string representation of a float with the
the given number of fractional digits. This should not be
used to perform a rounding operation (this is done via
:meth:`~.float_round`), but only to produce a suitable
string representation for a float.
:param int precision_digits: number of fractional digits to
include in the output
"""
# Can't use str() here because it seems to have an intrinsic
# rounding to 12 significant digits, which causes a loss of
# precision. e.g. str(123456789.1234) == str(123456789.123)!!
return ("%%.%sf" % precision_digits) % value |
def filestorage_to_binary(file_list):
"""
Transform a list of images in Flask's FileStorage format to binary format.
"""
binary_list = []
for f in file_list:
binary_list.append(f.read())
return binary_list |
def strip_suffixes(s, suffixes):
"""
Helper function to remove suffixes from given string.
At most, a single suffix is removed to avoid removing portions
of the string that were not originally at its end.
:param str s: String to operate on
:param iter<str> tokens: Iterable of suffix strings
:rtype: str
:return: String without any of the given suffixes
"""
for suffix in suffixes:
if s.endswith(suffix):
s = s[: -len(suffix)]
break
return s |
def in_ranges(value, ranges):
"""Check if a value is in a list of ranges"""
return all(low <= value <= high for low, high in ranges) |
def find_greater_numbers(nums):
"""Return # of times a number is followed by a greater number.
For example, for [1, 2, 3], the answer is 3:
- the 1 is followed by the 2 *and* the 3
- the 2 is followed by the 3
Examples:
>>> find_greater_numbers([1, 2, 3])
3
>>> find_greater_numbers([6, 1, 2, 7])
4
>>> find_greater_numbers([5, 4, 3, 2, 1])
0
>>> find_greater_numbers([])
0
"""
count = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[j] > nums[i]:
count += 1
return count |
def fields_string(field_type, field_list, sep):
"""Create an error string for <field_type> field(s), <field_list>.
<sep> is used to separate items in <field_list>"""
indent = ' '*11
if field_list:
if len(field_list) > 1:
field_str = "{} Fields: ".format(field_type)
else:
field_str = "{} Field: ".format(field_type)
# end if
fmsg = "\n{}{}{}".format(indent, field_str, sep.join(field_list))
else:
fmsg = ""
# end if
return fmsg |
def disorder_rate(values):
"""i.e. Inversion count calculation"""
dr = 0
for i in range(len(values)-1):
for j in range(i+1,len(values)):
if values[i] > values[j]:
dr += 1
return dr |
def clamp(value: float, mini: float, maxi: float) -> float:
"""
it clamps a value between mini and maxi
:param value: the value that will be clamped
:param mini: the floor value
:param maxi: the ceil value
:type value: float
:type mini: float
:type maxi: float
:return: Union[int, float]
"""
return mini if value < mini else value if value < maxi else maxi |
def collatz_seq(start):
""" Algorithm returning whole Collatz sequence
starting from a given interger. """
n = start
seq = [start]
while n > 1:
if n % 2 == 0:
n = n // 2
seq.append(n)
else:
n = (n * 3 + 1) // 2
seq.extend([n * 2, n])
return seq |
def taille(arbre):
"""Fonction qui renvoie la taille d'un arbre binaire"""
if arbre is None:
return 0
tg = taille(arbre.get_ag())
td = taille(arbre.get_ad())
return tg + td + 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.