content
stringlengths 42
6.51k
|
---|
def concat_name_county(name):
"""
This function is used to concat a string of words by putting underscore between words
example: "new york steuben" --> "new_york_steuben"
@param name: string of raw name
@return concat_name: concated words of string by underscore
"""
try:
assert name != ""
except AssertionError as exp:
exp.args += ('input must not be a empty string', "check concat_name_county function")
raise
name_vector = str(name).split(" ")
concat_name = ""
for i in name_vector:
if i in [" ", ""]:
continue
else:
concat_name = concat_name + "_" + str(i)
return concat_name[1:].strip()
|
def clear_bit_k(int_val, k):
"""Clears the bit at offset k"""
return int_val & ~(1 << k)
|
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circuits when they
have different lengths.
"""
if len(val1) != len(val2):
return False
result = 0
for x, y in zip(val1, val2):
result |= x ^ y
return result == 0
|
def parse_vars(variables):
"""Parse variables passed as args to list of tuples
If variable has required value then
it'll be appended in format (key, value).
If variable has no variable (it should just exist)
then it'll be appended as (key,)
:param variables: string of variables in args format 'key:value,key2:value2,key3'
:type variables: str
:return: List of parsed variables
:rtype: list
"""
list_of_items = variables.split(',') if variables else []
parsed_variables = []
for variable in list_of_items:
if ':' in variable:
parsed_variables.append(tuple(variable.split(':')))
else:
parsed_variables.append((variable, None))
return parsed_variables
|
def safety_check_first_line(first_line: str) -> None:
"""Inspects first line of lineage_notes.txt to perform safety check.
We pull all of our Pango lineages from a human-edited .txt file.
The format has been stable so far, but if things ever change significantly,
the planned loading process will probably explode. In case of changes,
we will need to investigate and alter the loading process.
This check exists to avoid ever accidentally loading a file where the
format has (probably) changed. Assumption is that if the first line has
changed from what it used to be, the file format has probably changed.
Will print the problem and raise an exception.
Raises:
RuntimeError -- If first line of file not what was expected.
"""
EXPECTED_FIRST_LINE = "Lineage\tDescription\n"
if first_line != EXPECTED_FIRST_LINE:
print("First line of imported lineages file has changed!")
print("Loading script was originally written for previous version.")
print(f"Expected: '{EXPECTED_FIRST_LINE}'")
print(f"Actually got first line: '{first_line}'")
print("Very likely you need to rewrite loading script. Aborting.")
raise RuntimeError("Format of lineage file has likely changed")
return None
|
def is_big(label: str) -> bool:
"""Returns whether or not a cave is large based on its label"""
return label.isupper()
|
def snapshot_expval_counts(shots):
"""SnapshotExpectationValue test circuits reference counts."""
targets = []
# State |+1>
targets.append({'0x1': shots / 2, '0x3': shots / 2})
# State |00> + |11>
targets.append({'0x0': shots / 2, '0x3': shots / 2})
# State |01> -i|01>
targets.append({'0x1': shots / 2, '0x2': shots / 2})
return targets
|
def addUnits(metric_name):
"""Add units according to the input metric
PARAMETERS
----------
metric_name : string
name of the metric to plot
RETURNS
-------
label : string
name of the metric to plot with the units that were added to it
"""
if "energy" in metric_name.lower():
label = metric_name + " ($kcal/mol$)"
elif "energies" in metric_name.lower():
label = metric_name + " ($kcal/mol$)"
elif "distance" in metric_name.lower():
label = metric_name + " ($\AA$)"
elif "rmsd" in metric_name.lower():
label = metric_name + " ($\AA$)"
else:
label = metric_name
return label
|
def constraint(n, j, d):
"""
This function returns the DoF of a system according to the Constraint
Formulation.
@Input:
n - Number of links
j - List:
len(j) = number of joints
ith element of j = DoF of the ith joint
d - 3 dimensional or 2 dimensional system
@Output:
degree of freedom of the whole system
"""
if not isinstance(j, list):
raise ValueError("Invalid Input")
if d == 3:
l = 6
elif d == 2:
l = 3
else:
raise ValueError("Invalid dimension")
for i in range(len(j)):
j[i] = l - j[i]
return l * (n - 1) - sum(j)
|
def pad_list(orig_list, pad_length):
"""
Pads a list with empty items
Copied from http://stackoverflow.com/a/3438818/3710392
:param orig_list: the original list
:param pad_length: the length of the list
:return: the resulting, padded list
"""
return orig_list + [''] * (pad_length - len(orig_list))
|
def fstr(value):
"""Canonical xml float value output"""
int_value = int(value)
if int_value == value:
return str(int_value)
return str(value)
|
def flax_cond(pred, true_operand, true_fun,
false_operand, false_fun): # pragma: no cover
"""
for debugging purposes, use this instead of jax.lax.cond
"""
if pred:
return true_fun(true_operand)
else:
return false_fun(false_operand)
|
def pipe_hoop_stress(P, D, t):
"""Calculate the hoop (circumferential) stress in a pipe
using Barlow's formula.
Refs: https://en.wikipedia.org/wiki/Barlow%27s_formula
https://en.wikipedia.org/wiki/Cylinder_stress
:param P: the internal pressure in the pipe.
:type P: float
:param D: the outer diameter of the pipe.
:type D: float
:param t: the pipe wall thickness.
:type t: float
:returns: the hoop stress in the pipe.
:rtype: float
"""
return P * D / 2 / t
|
def truncate(number, decimals=0):
"""
truncate a given number to the chosen decimal place
"""
multiplier = 10**decimals
return int(number * multiplier) / multiplier
|
def percent_flicker(v_max:float, v_pp:float) -> float:
"""Computes the flicker percentage of the waveform
Parameters
----------
v_max : float
The max voltage
v_pp : float
The peak-to-peak voltage
Returns
-------
float
The flicker percentage
"""
return v_pp / v_max * 100
|
def validate_calendar(calendar):
"""Validate calendar string for CF Conventions.
Parameters
----------
calendar : str
Returns
-------
out : str
same as input if the calendar is valid
Notes
-----
1. The 'none' value for the calendar attribute is not supported anywhere
in this code presently, so NotImplementedError is raised.
2. NetCDFError is raised for invalid calendars.
"""
if calendar in ['gregorian', 'standard', 'proleptic_gregorian', 'noleap',
'365_day', 'all_leap', '366_day', '360_day', 'julian']:
return calendar
elif calendar == 'none':
raise NotImplementedError("calendar is set to 'none'")
else:
# should be a better error...
raise NotImplementedError("Unknown calendar: {0}".format(calendar))
|
def a2z(a):
""" converts from scale factor to redshift """
return 1.0/a - 1.0
|
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
try:
if str(arg) in value:
return value[str(arg)]
except:
if hasattr(value,str(arg)):
return getattr(value,str(arg))
return ''
|
def af_subtraction(ch1, ch2, m, c):
"""
Subtract ch2 from ch1
ch2 is first adjusted to m * ch2 + c
:param ch1:
:param ch2:
:param m:
:param c:
:return:
"""
af = m * ch2 + c
signal = ch1 - af
return signal
|
def _remove_script_from_dependencies(executed_script, script_dependencies):
""" Builds new dependencies dict skipping the executed script """
new_dependencies = dict()
for script_path, dependencies in script_dependencies.items():
if script_path != executed_script:
new_dependencies[script_path] = [d for d in dependencies if d != executed_script]
return new_dependencies
|
def evaluated_profile_li(profileli):
""" Return a list of synapses which were parsed and evaluated
w/o errors so far
"""
return [pro for pro in profileli if not pro.errflag]
|
def str_to_tup(lonlat_str):
"""
'123.45,-144.41' -> (123.45, -144.41)
"""
try:
tup = tuple(float(s) for s in lonlat_str.split(','))
return tup
except:
raise Exception((f'Could not parse lon lat string: {lonlat_str}'
' Ensure lon, lat are in correct order and no spaces.'))
|
def _ReorderMapByTypTags(result_map):
"""Rearranges|result_map| to use typ tags as the top level keys.
Args:
result_map: Aggregated query results from results.AggregateResults
Returns:
A dict containing the same contents as |result_map|, but in the following
format:
{
typ_tags (tuple of str): {
suite (str): {
test (str): build_url_list (list of str),
},
},
}
"""
reordered_map = {}
for suite, test_map in result_map.items():
for test, tag_map in test_map.items():
for typ_tags, build_url_list in tag_map.items():
reordered_map.setdefault(typ_tags,
{}).setdefault(suite,
{})[test] = build_url_list
return reordered_map
|
def get_file_name(path):
"""Converts file path to file name"""
file_name = path.split("\\")
file_name = file_name[len(file_name) - 1]
file_name = file_name[:-len(".txt")]
file_name = file_name.title()
file_name += " file"
return file_name
|
def wall_long_mono_to_string(mono, latex=False):
"""
Alternate string representation of element of Wall's basis.
This is used by the _repr_ and _latex_ methods.
INPUT:
- ``mono`` - tuple of pairs of non-negative integers (m,k) with `m
>= k`
- ``latex`` - boolean (optional, default False), if true, output
LaTeX string
OUTPUT: ``string`` - concatenation of strings of the form
``Sq^(2^m)``
EXAMPLES::
sage: from sage.algebras.steenrod.steenrod_algebra_misc import wall_long_mono_to_string
sage: wall_long_mono_to_string(((1,2),(3,0)))
'Sq^{1} Sq^{2} Sq^{4} Sq^{8}'
sage: wall_long_mono_to_string(((1,2),(3,0)),latex=True)
'\\text{Sq}^{1} \\text{Sq}^{2} \\text{Sq}^{4} \\text{Sq}^{8}'
The empty tuple represents the unit element::
sage: wall_long_mono_to_string(())
'1'
"""
if latex:
sq = "\\text{Sq}"
else:
sq = "Sq"
if len(mono) == 0:
return "1"
else:
string = ""
for (m,k) in mono:
for i in range(k,m+1):
string = string + sq + "^{" + str(2**i) + "} "
return string.strip(" ")
|
def divisible_by(numbers: list, divisor: int) -> list:
"""This function returns all numbers which are divisible by the given divisor."""
if numbers is None:
return []
res = []
for item in numbers:
if item % divisor == 0:
res.append(item)
return res
|
def get_full_version(package_data):
"""
Given a mapping of package_data that contains a version and may an epoch and
release, return a complete version.
For example::
>>> get_full_version(dict(version='1.2.3'))
'1.2.3'
>>> get_full_version(dict(version='1.2.3', epoch='2'))
'2~1.2.3'
>>> get_full_version(dict(version='1.2.3', epoch='2', release='23'))
'2~1.2.3-23'
"""
version = package_data['version']
release = package_data.get('release', '')
if release:
release = f'-{release}'
epoch = package_data.get('epoch', '')
if epoch:
epoch = f'{epoch}~'
version = f'{epoch}{version}{release}'
return version
|
def link_handler(tag, post_html):
"""
This function switches from a specific {tag} to a specific
markdown link syntax
Example:
<a href=URL>CAPTION</a> => [CAPTION](URL)
"""
old_tag = tag
close_tag = "</{0}>".format(tag)
tag = "<{0}".format(tag)
start = post_html.find(tag)
end = post_html.find(close_tag) + len(close_tag)
link_html = post_html[start:end]
link_markdown = ""
link = ""
caption = ""
caption = link_html[link_html.find(">") + 1: link_html.find("</a>")]
if link_html.find("href=") >= 0:
link = link_html[link_html.find(
"href=") + 6:link_html.find("\" data-href=")]
if len(caption) == 0:
caption = link
if len(link) > 0:
link_markdown = "[{0}]({1})".format(caption, link)
post_html = post_html[:start] + link_markdown + post_html[end:]
if (post_html.find(tag) >= 0):
post_html = link_handler(old_tag, post_html)
return post_html
|
def timefmt(thenumber):
"""
Parameters
----------
thenumber
Returns
-------
"""
return "{:10.2f}".format(thenumber)
|
def _kwargs(kwargs):
"""
Used to forward common arguments for postgres module
"""
return {k: v for k, v in kwargs.items() if k in (
'user', 'host', 'port', 'maintenance_db', 'password', 'runas')}
|
def jaccard_index(a, b):
"""
Jaccard similarity of sets a and b
"""
intsize = len(set.intersection(a, b))
unionsize = len(set.union(a, b))
if unionsize == 0:
return 1
else:
return float(intsize) / float(unionsize)
|
def get_dict_season():
"""Return dictionary for conversion (to integers) of season strings."""
dict_season = {'DJF': 1,
'MAM': 2,
'JJA': 3,
'SON': 4,
}
return dict_season
|
def get_start_and_end(clips):
"""Get start and end time of a clip list in seconds."""
if len(clips) == 0:
return (0, 0)
else:
return (
min(clip.start for clip in clips),
max(clip.start + clip.length for clip in clips),
)
|
def ParseDeviceBlocked(blocked, enable_device):
"""Returns the correct enabled state enum based on args."""
if enable_device is None and blocked is None:
return None
elif enable_device is None or blocked is None:
# In this case there are no default arguments so we should use or.
return blocked is True or enable_device is False
else:
# By default blocked is false, so any blocked=True value should override
# the default.
return not enable_device or blocked
|
def mpath(path):
"""Converts a POSIX path to an equivalent Macintosh path.
Works for ./x ../x /x and bare pathnames.
Won't work for '../../style/paths'.
Also will expand environment variables and Cshell tilde
notation if running on a POSIX platform.
"""
import os
if os.name == 'mac' : #I'm on a Mac
if path[:3] == '../': #parent
mp = '::'
path = path[3:]
elif path[:2] == './': #relative
mp = ':'
path = path[2:]
elif path[0] == '/': #absolute
mp = ''
path = path[1:]
else: # bare relative
mp = ''
pl = string.split(path, '/')
mp = mp + string.join(pl, ':')
return mp
elif os.name == 'posix': # Expand Unix variables
if path[0] == '~' :
path = os.path.expanduser( path )
if '$' in path:
path = os.path.expandvars( path )
return path
else: # needs to take care of dos & nt someday
return path
|
def _hex(x):
"""Formatting integer as two digit hex value."""
return '0x{:02X}'.format(x)
|
def get_genome_dir(infra_id, genver=None, annver=None, key=None):
"""Return the genome directory name from infra_id and optional arguments."""
dirname = f"{infra_id}"
if genver is not None:
dirname += f".gnm{genver}"
if annver is not None:
dirname += f".ann{annver}"
if key is not None:
dirname += f".{key}"
return dirname
|
def remove_blanks(letters: list):
"""Given a list of letters, remove any empty strings.
>>> remove_blanks(['a', '', 'b', '', 'c'])
['a', 'b', 'c']
"""
cleaned = []
for letter in letters:
if letter != "":
cleaned.append(letter)
return cleaned
|
def strip_trailing_whitespace(lines):
"""Removes trailing whitespace from the given lines."""
return [line.rstrip() + '\n' for line in lines]
|
def _adjust_lines(lines):
"""Adjust linebreaks to match ';', strip leading/trailing whitespace.
list_of_commandlines=_adjust_lines(input_text)
Lines are adjusted so that no linebreaks occur within a commandline
(except matrix command line)
"""
formatted_lines = []
for l in lines:
# Convert line endings
l = l.replace('\r\n', '\n').replace('\r', '\n').strip()
if l.lower().startswith('matrix'):
formatted_lines.append(l)
else:
l = l.replace('\n', ' ')
if l:
formatted_lines.append(l)
return formatted_lines
|
def combValue(comb, value):
"""
Bir kombinasyonun sahip oldugu value degerini dondurur
"""
total = 0
for i in comb:
total = total + value[i]
return total
|
def kelvin_to_celsius(kelvin):
"""Convert kelvin to celsius."""
celsius = kelvin - 273.15
return celsius
|
def is_nested(value):
"""Returns true if the input is one of: ``list``, ``unnamedtuple``, ``dict``,
or ``namedtuple``. Note that this definition is different from tf's is_nested
where all types that are ``collections.abc.Sequence`` are defined to be nested.
"""
return isinstance(value, (list, tuple, dict))
|
def insertion_sort(lst: list) -> list:
"""Sort a list in ascending order. The original list is mutated and
returned. The sort is stable.
Design idea: Iterate over the list. After i iterations, the first i elements
of the list should be sorted. Insert the i+1'th element in the appropriate
spot in the sorted sublist. Note that this idea differs from selection sort
in that the first i elements are sorted, but not necessarily in their final
order.
Complexity: O(n^2) time, O(1) space. Stable and in-place.
"""
for i in range(1, len(lst)):
v = lst[i]
j = i - 1
# Keep shifting elements over until we hit an element equal to or less
# than `v`.
while j >= 0 and lst[j] > v:
lst[j+1] = lst[j]
j -= 1
lst[j+1] = v
return lst
|
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\'s", " \'s", string)
string = re.sub(r"\'ve", " \'ve", string)
string = re.sub(r"n\'t", " n\'t", string)
string = re.sub(r"\'re", " \'re", string)
string = re.sub(r"\'d", " \'d", string)
string = re.sub(r"\'ll", " \'ll", string)
string = re.sub(r",", " , ", string)
string = re.sub(r"!", " ! ", string)
string = re.sub(r"\(", " \( ", string)
string = re.sub(r"\)", " \) ", string)
string = re.sub(r"\?", " \? ", string)
string = re.sub(r"\s{2,}", " ", string)
return string.strip().lower()
"""
#just return string if already cleaned
return string
|
def _int_conv(string):
"""
Convenience tool to convert from string to integer.
If empty string return None rather than an error.
>>> _int_conv('12')
12
>>> _int_conv('')
"""
try:
intstring = int(string)
except Exception:
intstring = None
return intstring
|
def validate_nag_function_name(name):
"""
Check wether a NAG function name is valid
"""
if (
name is not None and
isinstance(name, str) and
len(name) > 1 and
name[1:].isdigit() and
(
name[0:1] in ['i','n','o'] or
name in ['c0','c1']
) and
name[0:2] not in ['i0','n0','o0']
):
return True
else:
return False
|
def _digit_to_hex(string_of_digit):
"""Convert string of digits to string of hex."""
return "".join(
[
hex(int(i))[2:]
for i in [
string_of_digit[i : i + 2] for i in range(0, len(string_of_digit), 2)
]
]
)
|
def handleSentenceChild(child, tokenList):
"""Recursively walk the given DOM object to extract all tokens in it
"""
if child == None:
return tokenList
elif child.localName == u'cons':
tokenList = handleSentenceChild(child.firstChild, tokenList)
return handleSentenceChild(child.nextSibling, tokenList)
elif child.localName == u'tok':
tokenList.append(child.firstChild.nodeValue)
return handleSentenceChild(child.nextSibling, tokenList)
elif child.nodeValue == u' ':
tokenList.append(' ')
return handleSentenceChild(child.nextSibling, tokenList)
else:
raise Exception("Unknown element:" + child.localName)
|
def mean(data: list):
"""
:param data: a list of int
:return: the average of integers in data
"""
res = sum(data) / len(data)
return res
|
def t_gid_parse(gid):
"""
Parse the GID given and return a tuple with the following values:
- The real GID without bitwise flags.
- Whether or not the tile is horizontally flipped.
- Whether or not the tile is vertically flipped.
- Whether or not the tile is "diagonally" flipped.
This is a low-level function used internally by this library; you
don't typically need to use it.
"""
rgid = (gid - (gid & 1<<31) - (gid & 1<<30) - (gid & 1<<29))
hflip = bool(gid & 1<<31)
vflip = bool(gid & 1<<30)
dflip = bool(gid & 1<<29)
return rgid, hflip, vflip, dflip
|
def pwvalid(minCount, maxCount, char, pw):
""" Password Validation
>>> pwvalid(1, 3, "a", "abcde")
True
>>> pwvalid(1, 3, "b", "cdefg")
False
>>> pwvalid(2, 9, "c", "ccccccccc")
True
"""
return int(minCount) <= pw.count(char) <= int(maxCount)
|
def find_furthest_room(distances):
"""Find furthest room from the distances grid."""
return max(max(row) for row in distances)
|
def normalize_raw(raw_line):
"""Replace hard tabs with 4 spaces.
"""
return raw_line.replace('\t', ' ')
|
def prettify_logger_message(msg):
"""Prettifies logger messages by breaking them up into multi lines"""
from textwrap import wrap
linewidth = 75 - 13
indent = "\n" + " " * 13
temp = wrap(msg, width=linewidth)
return indent.join(temp)
|
def coast(state):
"""
Ignore the state, go right.
"""
print("COAST :::: " )
action = {"command": 1}
return action
|
def string(s):
"""
Convert a string to a escaped ASCII representation including quotation marks
:param s: a string
:return: ASCII escaped string
"""
ret = ['"']
for c in s:
if ' ' <= c < '\x7f':
if c == "'" or c == '"' or c == '\\':
ret.append('\\')
ret.append(c)
continue
elif c <= '\x7f':
if c in ('\r', '\n', '\t'):
# unicode-escape produces bytes
ret.append(c.encode('unicode-escape').decode("ascii"))
continue
i = ord(c)
ret.append('\\u')
ret.append('%x' % (i >> 12))
ret.append('%x' % ((i >> 8) & 0x0f))
ret.append('%x' % ((i >> 4) & 0x0f))
ret.append('%x' % (i & 0x0f))
ret.append('"')
return ''.join(ret)
|
def AND(*expressions):
"""
Evaluates one or more expressions and returns true if all of the expressions are true.
See https://docs.mongodb.com/manual/reference/operator/aggregation/and/
for more details
:param expressions: An array of expressions
:return: Aggregation operator
"""
return {'$and': list(expressions)}
|
def calculate_area(chart, n_var, m_var):
"""Calculates the area under graph"""
area = 0
# boolean list to check whether we have seen the graph in a col or not:
seen_graph = [False] * m_var
# iterate over chart:
for row in range(n_var):
for col in range(m_var):
point = chart[row][col]
# if seen the graph:
if point in '_/\\':
seen_graph[col] = True
if seen_graph[col]:
if point != '_': # because area under "_" is zero
area += 0.5 if point in '/\\' else 1.0
return f"{area:.3f}"
|
def argmin(list, score_func=None):
"""
If a score function is provided, the element with the lowest score AND the score is returned.
If not, the index of lowest element in the list is returned.
If the list is empty, None is returned.
"""
if len(list) == 0:
return None
scores = list if score_func is None else [score_func(e) for e in list]
best_index = 0
best_score = scores[0]
for i, score in enumerate(scores):
if score < best_score:
best_index = i
best_score = score
if score_func is None:
return best_index
return list[best_index], best_score
|
def is_iterable(obj):
# QualityCheckTags: DOCS,INPUTCHECK,RETURNVALUEDOCS,OVERALL
"""Check if given object is iterable.
Arguments:
- obj: object to check
Return:
True if given object is iterable, else False.
"""
if '__iter__' in dir(obj): return True
else: return False
|
def example(foo, bar, baz):
"""An example entry point for testing.
The rest of the function __doc__ is ignored by the entrypoint library.
foo -> a foo value.
bar -> a bar value.
baz -> a baz value.
Returns a string indicating what was passed in."""
return f'foo={foo}, bar={bar}, baz={baz}'
|
def _format_author(url, full_name):
""" Helper function to make author link """
return u"<a class='more-info' href='%s'>%s</a>" % (url, full_name)
|
def create_list_attr_operation(var_attribute_list_name):
"""Return request string for a single operation to create an attribute of type array/list."""
return '{"op":"CreateAttributeValueList","attributeName":"' + var_attribute_list_name + '"},'
|
def series(n, bool=False):
"""
:param bool: If bool=True, then the function will return the boolean list of the prime numbers.
If bool=False, then the function will return the list of prime number less than n+1.
:param n: Prime Number less than n.
:return: returns None if n is 0 or 1 otherwise returns the list of prime numbers less than n.
"""
# If n is less than 2, return None because no prime number is less than 2.
if n<2:
return None
prime = [True]*(n+1)
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, n+1, p):
prime[i] = False
p += 1
if bool:
return prime
else:
list_ = []
for i in range(2, n+1):
if prime[i]:
list_.append(i)
return list_
|
def make_biplot_scores_output(taxa):
"""Create convenient output format of taxon biplot coordinates
taxa is a dict containing 'lineages' and a coord matrix 'coord'
output is a list of lines, each containing coords for one taxon
"""
output = []
ndims = len(taxa['coord'][1])
header = '#Taxon\t' + '\t'.join(['pc%d' %(i+1) for i in range(ndims)])
output.append(header)
for i, taxon in enumerate(taxa['lineages']):
line = taxon + '\t'
line += '\t'.join(map(str, taxa['coord'][i]))
output.append(line)
return output
|
def levenshtein(string1, string2):
""" Measures the amount of difference between two strings.
The return value is the number of operations (insert, delete, replace)
required to transform string a into string b.
"""
# http://hetland.org/coding/python/levenshtein.py
n, m = len(string1), len(string2)
if n > m:
# Make sure n <= m to use O(min(n,m)) space.
string1, string2, n, m = string2, string1, m, n
current = list(range(n + 1))
for i in range(1, m + 1):
previous, current = current, [i] + [0] * n
for j in range(1, n + 1):
insert, delete, replace = previous[j] + 1, current[j - 1] + 1, previous[j - 1]
if string1[j - 1] != string2[i - 1]:
replace += 1
current[j] = min(insert, delete, replace)
return current[n]
|
def first(word, k=1):
"""Returns FIRST_k(word).
The implied grammar is taken to be empty and all symbols are treated as terminals.
See <http://www.jambe.co.nz/UNI/FirstAndFollowSets.html> for more information.
>>> first('hello, world', k=7)
'hello, '
>>> first(('list', 'item', 'item', 'item', 'item'), k=2)
('list', 'item')
"""
return word[:k]
|
def general(x, n):
"""Represent a float in general form.
This function is merely a wrapper around the 'g' type flag in the
formatting specification.
"""
n = int(n)
x = float(x)
if n < 1: raise ValueError("1+ significant digits required.")
return ''.join(('{:#.', str(n), 'g}')).format(x)
|
def node_spec():
"""Used in tests that have recursive $refs
"""
return {
'type': 'object',
'properties': {
'name': {
'type': 'string'
},
'child': {
'$ref': '#/definitions/Node',
},
},
'required': ['name']
}
|
def validation_simple(value, obj=None):
"""
Validates that at least one character has been entered.
Not change is made to the value.
"""
if len(value) >= 1:
return True, value
else:
return False, value
|
def reduce_lists(ids, metric, verbose=False):
"""
This function reduces nearby basis functions of the same sign
to a single representative basis function for that feature.
"""
ids = list(ids)
temp = ids.copy()
for j in temp:
if (j-1) in ids and metric[j] > metric[j-1]:
if verbose:
print('j-1 removed from id list for', j)
ids.remove(j-1)
if (j+1) in ids and metric[j] > metric[j+1]:
if verbose:
print('j+1 removed from id list for', j)
ids.remove(j+1)
return ids
|
def get_dimensions(corners):
"""
Gets the dimension of a position based on the 4 corners of a position
:param corners: list with 4 elements containg pairs of xy coordinates
:return: (x_length, y_length)
"""
x0, y0 = corners[0]
x1, y1 = corners[1]
x2, y2 = corners[2]
x3, y3 = corners[3]
x = max([abs(x0 - x1), abs(x0 - x2), abs(x0 - x3)])
y = max([abs(y0 - y1), abs(y0 - y2), abs(y0 - y3)])
return x, y
|
def firstPartOfGlyphName(name):
"""Returns the glyph name until the first dot."""
dotPosition = name.find(".")
if dotPosition != -1: # found a dot
return name[:dotPosition]
else: # no dot found
return name
|
def _compute_split_boundaries(split_probs, n_items):
"""Computes boundary indices for each of the splits in split_probs.
Args:
split_probs: List of (split_name, prob), e.g. [('train', 0.6), ('dev', 0.2),
('test', 0.2)]
n_items: Number of items we want to split.
Returns:
The item indices of boundaries between different splits. For the above
example and n_items=100, these will be
[('train', 0, 60), ('dev', 60, 80), ('test', 80, 100)].
"""
if len(split_probs) > n_items:
raise ValueError('Not enough items for the splits. There are {splits} '
'splits while there are only {items} items'.format(splits=len(split_probs), items=n_items))
total_probs = sum(p for name, p in split_probs)
if abs(1 - total_probs) > 1E-8:
raise ValueError('Probs should sum up to 1. probs={}'.format(split_probs))
split_boundaries = []
sum_p = 0.0
for name, p in split_probs:
prev = sum_p
sum_p += p
split_boundaries.append((name, int(prev * n_items), int(sum_p * n_items)))
# Guard against rounding errors.
split_boundaries[-1] = (split_boundaries[-1][0], split_boundaries[-1][1],
n_items)
return split_boundaries
|
def is_sorted(a):
"""Evaluates if a is sorted or not."""
a_sorted = sorted(a)
if a_sorted == a:
return True
else:
return False
|
def calculate_average_since(hrs_after_time):
""" Calculate average heart rate after specified date
This function first sums all of the heart rates after the specified date.
It then divides the summed heart rates by the total number of heart rate
entries. The result is the sum of the heart rates after the entered time.
:param hrs_after_time: a list of heart rate values that were entered after
the specified time ("heart_rate_average_since")
:returns: an integer indicating the average heart rate of the patient after
a certain date
"""
total_entries = len(hrs_after_time)
average_since = sum(hrs_after_time) / total_entries
return average_since
|
def abort(transactionid):
"""STOMP abort transaction command.
Rollback whatever actions in this transaction.
transactionid:
This is the id that all actions in this transaction.
"""
return "ABORT\ntransaction: %s\n\n\x00\n" % transactionid
|
def validity_of_currencytype(ctype, ftype):
"""This function checks if the user input of Cryptocurrency type
or Fiat Money type are truly the latter.
Returns 1 if found an error in the input, else returns 0."""
available_cryptocurrencies = ['ADA', 'BTC', 'BSV', 'ETH',
'ETC', 'BCH', 'LINK', 'LTC',
'DOGE', 'ZEC', 'SHIB', 'ZRX', 'MKR',
'MATIC', 'USDC', 'XRP', 'DOT', 'XLM']
if ctype not in available_cryptocurrencies:
return 1, f"\n{ctype} is not a Cryptocurrency. Try Again!\n"
elif ftype in available_cryptocurrencies:
return 1, f"\n{ftype} is not a Fiat Money. Try Again!\n"
else:
return 0, "\nAll Good!"
|
def convert_bot_name_to_environmental_name(bot_name):
"""
Coverts the given bot name to environmental variable name.
Parameters
----------
bot_name : `str`
The bot name to convert.
Return
------
environmental_name : `str`
"""
return bot_name.lower()
|
def fib(n): # return Fibonacci series up to n ...
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a) # see below ...
a, b = b, a+b
return result
|
def load_grid(input_grid):
"""
Convert the text form of the grid into an array form. For now this input is
always the same. If this changes then this code would need to be replaced.
"""
grid = [".#.", "..#", "###"]
return grid
|
def QueryTupleListToList(var):
""" Take the result of a SQL fetchall single variable query tuple list and make a regular python list """
list = []
for i in var:
list.append(i[0])
return list
|
def format_time(seconds: float) -> str:
"""Formats time into mm:ss:xx"""
minutes, seconds = divmod(seconds, 60)
centi = "{:.2f}".format(seconds % 1)[1:]
return "{:02d}:{:02d}{}".format(int(minutes), int(seconds), centi)
|
def countRun(s, c, maxRun, count):
"""parameter s: a string
parameter c: what we're counting
parameter maxRun: maximum length of run
returns: the number of times that string occurs in a row
This is the first step in the run sequence"""
"""
trial:
def countRunHelp(s,c,maxRun, count):
if count == maxRun:
return c
if s[count] == s[count+1]:
c+=1
return countRunHelp(s, c, maxRun, count+1)
return countRunHelp(s, c, maxRun, 0)
"""
if s == '':
return 0
if count >= maxRun:
return 0
if s[:len(c)] != c:
return 0
return 1 + countRun(s[len(c):], c, maxRun, count + 1)
|
def _parse_gateway(gw_data):
"""
compute the amount of ressource unit use by a gateway service
:return: dict containing the number of ressource unit used
:rtype: [type]
"""
return {"hru": 0, "sru": 0, "mru": 0.1, "cru": 0.1}
|
def option_set(fp):
"""set of all the options in a fingerprint"""
return set(fp.split(','))
|
def __is_picture(file):
"""
It returns whether the processed file is a jpg picture or not.
All arguments must be of equal length.
:param file: longitude of first place
:return: A boolean indicating whether the file is a jpg image or not
"""
if file.lower().endswith("jpg") or file.lower().endswith("jpeg"):
return True
else:
return False
|
def get_pixel_brightness_matrix(pixel_matrix):
"""
Convert each RGB tuple of a pixel matrix into a brightness number matrix.
Parameters:
pixel_matrix (list): A 2D matrix of RGB tuples
Returns:
pixel_brightness_matrix (list): A 2D matrix of brightness values
There are numerous ways to convert RGB to brightness, all generating a
slightly different style of transformed image. Here are 3 examples:
Average (average the R, G and B values):
-> (R + G + B) / 3
Lightness (average the maximum and minimum values out of R, G and B):
-> max(R, G, B) + min(R, G, B) / 2
Luminosity (take weighted average of RGB to account for human perception):
-> 0.2126 * R + 0.7152 * G + 0.0722 * B
More information can be found here:
https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
"""
def get_pixel_brightness(rgb_tuple):
# Use Luminosity
r, g, b = rgb_tuple
# return (r + g + b) / 3
# return (max(r, g, b) + min(r, g, b)) / 2
return 0.2126 * r + 0.7152 * g + 0.0722 * b
pixel_brightness_matrix = [list(map(get_pixel_brightness, row)) for row in pixel_matrix]
# print('Successfully constructed pixel brightness matrix. First row:')
# print(pixel_brightness_matrix[0])
return pixel_brightness_matrix
|
def find_matches(list_of_fragments, anchor_fragment, fixed_length
, verify_left=True, verify_right=True):
"""
Description:
Using an anchor fragment find the best matches from the list of fragments to the right, left or left&right
of the anchor fragment.
:param list_of_fragments: list[[str]] the list of fragment strings with the anchor fragment removed
:param anchor_fragment: [str] the anchor fragment string that we are using as a reference for matching
:param fixed_length: [int] is the most common substring length
:param verify_left: [bool] try to find matches to the left of the anchor, defaults to True
:param verify_right: [bool] try to find matches to the right of the anchor, defaults to True
"""
max_overlap = fixed_length - 1 if len(anchor_fragment) >= fixed_length else len(anchor_fragment)
info = {"anchor": anchor_fragment,
"num_of_left_matches": 0,
"left_matches": [],
"num_of_right_matches": 0,
"right_matches": [],
"duplicate": False}
space_check = set(" ")
acceptable_spaces = [4, 8, 12, 16]
for i, frag in enumerate(list_of_fragments): # check every fragment to see if they fit to the anchor fragment
duplicate_count = 0
if verify_left: # check for matches left of the anchor
for j in range(max_overlap, 2, -1):
anchor_overlap = anchor_fragment[:j]
left_overlap = frag[-j:]
spliced_frag = frag[:-j]
if left_overlap == anchor_overlap:
if set(left_overlap) == space_check: # check if the overlap is only spaces
anchor_spaces = 0
frag_spaces = 0
for k in range(len(spliced_frag)-1, 0, -1):
if spliced_frag[k] == " ":
frag_spaces += 1
else:
break
for k in range(0, len(anchor_fragment)):
if anchor_fragment[k] == " ":
anchor_spaces += 1
else:
break
total_spaces = frag_spaces + anchor_spaces
if total_spaces in acceptable_spaces:
info["num_of_left_matches"] += 1
info["left_matches"].append({"frag": frag, "spliced_frag": spliced_frag})
duplicate_count += 1
break
else:
continue
info["num_of_left_matches"] += 1
info["left_matches"].append({"frag": frag, "spliced_frag": spliced_frag})
duplicate_count += 1
break
if verify_right: # check for matches right of the anchor
for j in range(max_overlap, 2, -1):
anchor_overlap = anchor_fragment[-j:]
right_overlap = frag[:j]
spliced_frag = frag[j:]
if anchor_overlap == right_overlap:
if set(right_overlap) == space_check: # check if the overlap is only spaces
anchor_spaces = 0
frag_spaces = 0
for k in range(len(anchor_fragment)-1, 0, -1):
if anchor_fragment[k] == " ":
anchor_spaces += 1
else:
break
for k in range(0, len(spliced_frag)):
if spliced_frag[k] == " ":
frag_spaces += 1
else:
break
total_spaces = anchor_spaces + frag_spaces
if total_spaces in acceptable_spaces:
# the total spaces need to be a tab worth of spaces i.e. 4, 8, 12 etc..
info["num_of_right_matches"] += 1
info["right_matches"].append({"frag": frag, "spliced_frag": spliced_frag})
duplicate_count += 1
break
else:
continue
info["num_of_right_matches"] += 1
info["right_matches"].append({"frag": frag, "spliced_frag": spliced_frag})
duplicate_count += 1
break
if duplicate_count == 2:
info["duplicate"] = True
return info
|
def _replace_refs_in_field(fld, shelf):
""" Replace refs in fields"""
if "ref" in fld:
ref = fld["ref"]
if ref in shelf:
# FIXME: what to do if you can't find the ref
fld = shelf[ref]["field"]
else:
# Replace conditions and operators within the field
if "buckets" in fld:
for cond in fld["buckets"]:
if "ref" in cond:
# Update the condition in place
cond_ref = cond.pop("ref")
# FIXME: what to do if you can't find the ref
# What if the field doesn't have a condition
new_cond = shelf[cond_ref]["field"].get("condition")
if new_cond:
for k in list(cond.keys()):
cond.pop(k)
cond.update(new_cond)
if "label" not in cond:
cond["label"] = cond_ref
if "condition" in fld and isinstance(fld["condition"], dict):
cond = fld["condition"]
if "ref" in cond:
cond_ref = cond["ref"]
# FIXME: what to do if you can't find the ref
# What if the field doesn't have a condition
new_cond = shelf[cond_ref]["field"].get("condition")
if new_cond is None:
fld.pop("condition", None)
else:
fld["condition"] = new_cond
if "operators" in fld:
# Walk the operators and replace field references
new_operators = [
{
"operator": op["operator"],
"field": _replace_refs_in_field(op["field"], shelf),
}
for op in fld["operators"]
]
fld["operators"] = new_operators
return fld
|
def h_f(v):
""""humanize float"""
return "{:.1f}".format(v)
|
def coding_problem_02(l):
"""
Given an array of integers, return a new array such that each element at index i of
the new array is the product of all the numbers in the original array except the one at i.
Solve it without using division and in O(n).
Example:
>>> coding_problem_02([1, 2, 3, 4, 5])
[120, 60, 40, 30, 24]
"""
forward = [1] * len(l)
backward = [1] * len(l)
for idx in range(1, len(l)):
forward[idx] = forward[idx - 1] * l[idx - 1]
backward[-idx - 1] = backward[-idx] * l[-idx]
return [f * b for f, b in zip(forward, backward)]
|
def between(s, start, end):
"""
Extracts contents between 2 bookend strings, non-inclusive.
>>> s = 'from numpy import my_array, my_matrix'
>>> start,end = 'from','import'
>>> between(s,start,end)
'numpy'
@param: s <str> the string to be extracted from
@param: start <str> opening capture
@param: end <str> closing capture
"""
return (s.split(start))[1].split(end)[0].strip()
# --[EOF]--
|
def fix_expense_report(list_of_expenses):
"""
brute force solution
and expecting an ideal dataset i.e. one and only one pair is exists
"""
for i in range(len(list_of_expenses)):
for j in range(i, len(list_of_expenses)):
summ = list_of_expenses[i] + list_of_expenses[j]
if summ == 2020:
print(list_of_expenses[i], list_of_expenses[j])
return list_of_expenses[i]*list_of_expenses[j]
|
def custom_formatwarning(msg, *a):
"""Given a warning object, return only the warning message."""
return str(msg) + '\n'
|
def time_from_midnight(update_time: str) -> int:
"""[The time from midnight to the specified time passed to the function, used to repeat events
effectively]
Args:
update_time (str): [The time the event is scheduled]
Returns:
int: [The number of seconds it would take from midnight to reach the time specified in
update_time]
"""
update_hour = int(update_time[0:2:])
update_minute = int(update_time[3:5:])
seconds = ((update_hour*(60*60)) + (update_minute*(60)))
return seconds
|
def disable() -> dict:
"""Disables database tracking, prevents database events from being sent to the client."""
return {"method": "Database.disable", "params": {}}
|
def toFloat(val):
"""Converts the given value (0-255) into its hexadecimal representation"""
hex = "0123456789abcdef"
return float(hex.find(val[0]) * 16 + hex.find(val[1]))
|
def where(flag_list):
""" takes flags returns indexes of True values """
return [index for index, flag in enumerate(flag_list) if flag]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.