content
stringlengths 42
6.51k
|
|---|
def build_targets_from_builder_dict(builder_dict):
"""Return a list of targets to build, depending on the builder type."""
return ['most']
|
def byte_alignment (bytes) :
"""Returns alignment in powers of two of data with length `bytes`
>>> [(i, byte_alignment (i)) for i in range (-3, 3)]
[(-3, 1), (-2, 2), (-1, 1), (0, 0), (1, 1), (2, 2)]
>>> [(i, byte_alignment (i)) for i in range (3, 10)]
[(3, 1), (4, 4), (5, 1), (6, 2), (7, 1), (8, 8), (9, 1)]
"""
return (bytes ^ (bytes - 1)) & bytes
|
def verbose_boolean(boolean, object_source):
"""
This function returns "NO" if `boolean` is False, and
returns "YES" if `boolean` is True.
:param boolean:
:param object_source:
:return:
"""
return 'YES' if boolean else 'NO'
|
def split_tokens(tokens, separator):
"""
:rtype: list[list[formatcode.lexer.tokens.Token]]
"""
out = [[]]
for token in tokens:
if isinstance(token, separator):
out.append([])
else:
out[-1].append(token)
return out
|
def get_pg_point(geometry):
"""
Output the given point geometry in WKT format.
"""
return 'SRID=4326;Point({x} {y})'.format(**geometry)
|
def get_test_file_name(index):
"""Get name of the test file for the given index.
"""
return "test{0}.txt".format(index + 1)
|
def add_metadata(infile, outfile, sample_metadata):
"""Add sample-level metadata to a biom file. Sample-level metadata
should be in a format akin to
http://qiime.org/tutorials/tutorial.html#mapping-file-tab-delimited-txt
:param infile: String; name of the biom file to which metadata
shall be added
:param outfile: String; name of the resulting metadata-enriched biom file
:param sample_metadata: String; name of the sample-level metadata
tab-delimited text file. Sample attributes are
taken from this file. Note: the sample names in
the `sample_metadata` file must match the sample
names in the biom file.
External dependencies
- biom-format: http://biom-format.org/
"""
return {
"name": "biom_add_metadata: " + infile,
"actions": [("biom add-metadata"
" -i "+infile+
" -o "+outfile+
" -m "+sample_metadata)],
"file_dep": [infile],
"targets": [outfile]
}
|
def toposort(graph):
"""Kahn toposort.
"""
from collections import deque
in_degree = {u: 0 for u in graph} # determine in-degree
for u in graph: # of each node
for v in graph[u]:
in_degree[v] += 1
Q = deque() # collect nodes with zero in-degree
for u in in_degree:
if in_degree[u] == 0:
Q.appendleft(u)
L = [] # list for order of nodes
while Q:
u = Q.pop() # choose node of zero in-degree
L.append(u) # and 'remove' it from graph
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
Q.appendleft(v)
if len(L) == len(graph):
return L
else: # if there is a cycle,
print("Circular dependence! Will not do anything.")
return []
|
def get_from_info(info, to_get='collectors'):
"""Take in an info response and pull back something interesting from it.
:param info:
:param to_get:
:return:
"""
if to_get == 'collectors':
res = ['__'.join((p.get('plugin'), p.get('module'))) for p in info.get('collectors')]
else:
raise NotImplementedError(f"... to_get='{to_get}' not implemented ...")
return res
|
def _get_mul_scalar_output_quant_param(input_scale, input_zero_point, scalar):
"""
Determine the output scale and zp of quantized::mul_scalar op
This is used for mobilenet v3
Refer to aten/src/ATen/native/quantized/cpu/qmul.cpp
The names of variables are the same as torch impl
"""
q_min = 0
q_max = 255
self_scale = input_scale
self_zero_point = input_zero_point
other_val = scalar
if other_val > 0.0:
s_prime = other_val * self_scale
z_prime = self_zero_point
elif other_val == 0.0:
s_prime = 1.0
z_prime = 0
else:
s_prime = abs(other_val) * self_scale
z_prime = q_max - (self_zero_point - q_min)
return s_prime, z_prime
|
def SnakeToCamelString(snake):
"""Change a snake_case string into a camelCase string.
Args:
snake: str, the string to be transformed.
Returns:
str, the transformed string.
"""
parts = snake.split('_')
if not parts:
return snake
# Handle snake with leading '_'s by collapsing them into the next part.
# Legit field names will never look like this, but completeness of the
# function is important.
leading_blanks = 0
for p in parts:
if not p:
leading_blanks += 1
else:
break
if leading_blanks:
parts = parts[leading_blanks:]
if not parts:
# If they were all blanks, then we over-counted by one because of split
# behavior.
return '_' * (leading_blanks - 1)
parts[0] = '_' * leading_blanks + parts[0]
return ''.join(parts[:1] + [s.capitalize() for s in parts[1:]])
|
def _split_byte(bs):
"""Split the 8-bit byte `bs` into two 4-bit integers."""
mask_msb = 0b11110000
mask_lsb = 0b00001111
return (mask_msb & bs[0]) >> 4, mask_lsb & bs[0]
|
def nplc2ms(nplc:str):
"""
Convert nplc for 50 Hz to ms.
"""
ms = float(nplc) * 20
return ms
|
def check_rgb(rgb):
"""
check if the rgb is in legal range.
"""
if rgb >= 255:
return 255
if rgb <= 0:
return 0
return rgb
|
def _IsLegacyMigration(platform_name):
"""Determines if the platform was migrated from FDT impl.
Args:
platform_name: Platform name to be checked
"""
return platform_name in ['Coral', 'Fizz']
|
def extract_most_important(tf_idf, terms_needed):
""" tf_idf = {'a': 2, 'b': 0.5, 'c': 3, 'd': 1}
extract_most_important(tf_idf, 2) => returns "c:3 a:2"
extract_most_important(tf_idf, 3) => returns "c:3 a:2 d:1"
"""
sort_by_value = sorted(tf_idf, key=tf_idf.get, reverse=True)
most_important = sort_by_value[:terms_needed]
return ' '.join([str(item) + ":" + str(tf_idf[item]) for item in most_important])
|
def tohex(value, nbytes=4):
"""Improved version of hex."""
return ("0x%%0%dX" % (2*nbytes)) % (int(str(value)) & (2**(nbytes*8)-1))
|
def fill_color(color: str):
"""
Returns an SVG fill color attribute using the given color.
:param color: `string` fill color
:return: fill="<color>"
"""
return f'fill="{color}"'
|
def str2intlist(v):
"""Converts a string of comma separated values to a list of int."""
if len(v) == 0:
return []
return [int(item) for item in v.split(",")]
|
def text_to_words(the_text):
""" return a list of words with all punctuation removed,
and all in lowercase.
"""
my_substitutions = the_text.maketrans(
# If you find any of these
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
# Replace them by these
"abcdefghijklmnopqrstuvwxyz ")
# Translate the text now.
cleaned_text = the_text.translate(my_substitutions)
wds = cleaned_text.split()
return wds
|
def remove_min_line (matrix, list_min_line):
"""Soustraction des min par ligne"""
for y, y_elt in enumerate(matrix):
for x, x_elt in enumerate(y_elt):
matrix[y][x] = x_elt - list_min_line[y]
return matrix
|
def kineticEnergy(mass,velocity):
"""1 J = 1 N*m = 1 Kg*m**2/s**2
Usage: Energy moving an object"""
K = 0.5*mass*velocity**2
return K
|
def select_bboxes(selection_bbox: dict, page_bboxes: list, tolerance: int = 10) -> list:
"""
Filter the characters bboxes of the document page according to their x/y values.
The result only includes the characters that are inside the selection bbox.
:param selection_bbox: Bounding box used to select the characters bboxes.
:param page_bboxes: Bounding boxes of the characters in the document page.
:param tolerance: Tolerance for the coordinates values.
:return: Selected characters bboxes.
"""
selected_char_bboxes = [
char_bbox
for char_bbox in page_bboxes
if int(selection_bbox["x0"]) - tolerance <= char_bbox["x0"]
and int(selection_bbox["x1"]) + tolerance >= char_bbox["x1"]
and int(selection_bbox["y0"]) - tolerance <= char_bbox["y0"]
and int(selection_bbox["y1"]) + tolerance >= char_bbox["y1"]
]
return selected_char_bboxes
|
def transformed_name(key):
"""Name for the transformed feature."""
return key + "_xf"
|
def wpm(typed, elapsed):
"""Return the words-per-minute (WPM) of the TYPED string.
Arguments:
typed: an entered string
elapsed: an amount of time in seconds
>>> wpm('hello friend hello buddy hello', 15)
24.0
>>> wpm('0123456789',60)
2.0
"""
assert elapsed > 0, 'Elapsed time must be positive'
# BEGIN PROBLEM 4
type_len = len(typed) / 5.0
ans = type_len / (elapsed / 60)
return ans
# END PROBLEM 4
|
def riccati_inverse_normal(y, x, b1, b2, bp=None):
"""
Inverse transforming the solution to the normal
Riccati ODE to get the solution to the Riccati ODE.
"""
# bp is the expression which is independent of the solution
# and hence, it need not be computed again
if bp is None:
bp = -b2.diff(x)/(2*b2**2) - b1/(2*b2)
# w(x) = -y(x)/b2(x) - b2'(x)/(2*b2(x)^2) - b1(x)/(2*b2(x))
return -y/b2 + bp
|
def import_deep_distortion_by_type(
defect_list: list,
fancy_defects: dict,
) -> list:
"""
Imports the ground-state distortion found for a certain charge state in order to \
try it for the other charge states.
Args:
defect_list (list):
defect dict in doped format of same type (vacancies, antisites or interstitials)
fancy_defects (dict):
dict containing the defects for which we found E lowering distortions (vacancies, or antisites or interstitials)
"""
list_deep_distortion = []
for i in defect_list:
if i['name'] in fancy_defects.keys(): # if defect underwent a deep distortion
defect_name = i['name']
print(defect_name)
i['supercell']['structure'] = fancy_defects[defect_name]['structure'] #structure of E lowering distortion
print("Using the distortion found for charge state(s) {} with BDM distortion {}".format(fancy_defects[defect_name]['charges'],
fancy_defects[defect_name]["BDM_distortion"] ) )
#remove the charge state of the E lowering distortion distortion
if len(fancy_defects[i['name']]['charges']) > 1:
print("Intial charge states of defect:", i['charges'], "Will remove the ones where the distortion was found...")
[i['charges'].remove(charge) for charge in fancy_defects[defect_name]['charges']]
print("Trying distortion for charge states:", i['charges'])
else:
i['charges'].remove(fancy_defects[defect_name]['charges'][0])
if i['charges']: #if list of charges to try deep distortion not empty, then add defect to the list
list_deep_distortion.append(i)
return list_deep_distortion
|
def shout_echo(word1, echo=1):
"""Concatenate echo copies of word1 and three
exclamation marks at the end of the string."""
# Concatenate echo copies of word1 using *: echo_word
echo_word = word1 * echo
# Concatenate '!!!' to echo_word: shout_word
shout_word = echo_word + '!!!'
# Return shout_word
return shout_word
|
def pretty_args(args):
"""pretty prints the arguments in a string
"""
return ", ".join([repr(arg) for arg in args])
|
def truncate(text, maxlen=128, suffix='...'):
"""Truncates text to a maximum number of characters."""
if len(text) >= maxlen:
return text[:maxlen].rsplit(" ", 1)[0] + suffix
return text
|
def extract_want_line_capabilities(text):
"""Extract a capabilities list from a want line, if present.
Note that want lines have capabilities separated from the rest of the line
by a space instead of a null byte. Thus want lines have the form:
want obj-id cap1 cap2 ...
Args:
text: Want line to extract from
Returns: Tuple with text with capabilities removed and list of capabilities
"""
split_text = text.rstrip().split(b" ")
if len(split_text) < 3:
return text, []
return (b" ".join(split_text[:2]), split_text[2:])
|
def str_to_list(val, separator=','):
"""
Split one string to a list by separator.
"""
if val is None:
return None
return val.split(separator)
|
def format_out(string_name, forecast_hour, value):
"""
formats polygon output
:param string_name: name of output field
:param forecast_hour: forecast hour of output
:param value: value of output
:returns: dict forecast hour, field name, and value
"""
return [{
'Forecast Hour': forecast_hour,
string_name: value
}]
|
def bubble_sort(numbers: list) -> list:
"""
Algorithm that implement buble sort ordering
Parameters
----------
numbers : list
The numbers list
Returns
-------
list
"""
_numbers = [ number for number in numbers ]
swaped = True
n = 1
while swaped and n <= len(numbers):
swaped = False
for i in range(len(_numbers) - 1):
if _numbers[i] > _numbers[i+1]:
_numbers[i], _numbers[i+1] = _numbers[i+1],_numbers[i]
swaped = True
n += 1
return _numbers
|
def iter_split(buf, delim, func):
"""
Invoke `func(s)` for each `delim`-delimited chunk in the potentially large
`buf`, avoiding intermediate lists and quadratic string operations. Return
the trailing undelimited portion of `buf`, or any unprocessed portion of
`buf` after `func(s)` returned :data:`False`.
:returns:
`(trailer, cont)`, where `cont` is :data:`False` if the last call to
`func(s)` returned :data:`False`.
"""
dlen = len(delim)
start = 0
cont = True
while cont:
nl = buf.find(delim, start)
if nl == -1:
break
cont = not func(buf[start:nl]) is False
start = nl + dlen
return buf[start:], cont
|
def most_prolific(dict):
"""
Takes a dict formatted like "book->published year"
{"Please Please Me": 1963, "With the Beatles": 1963,
"A Hard Day's Night": 1964, "Beatles for Sale": 1964, "Twist and Shout": 1964,
"Help": 1965, "Rubber Soul": 1965, "Revolver": 1966,
"Sgt. Pepper's Lonely Hearts Club Band": 1967,
"Magical Mystery Tour": 1967, "The Beatles": 1968,
"Yellow Submarine": 1969 ,'Abbey Road': 1969,
"Let It Be": 1970}
and returns the year in which the most albums were released.
If you call the function on the Beatles_Discography it should return 1964,
which saw more releases than any other year in the discography.
If there are multiple years with the same maximum number of releases,
the function should return a list of years.
"""
# Make map: value -> count
# For example: 1963 -> 3, 1963 -> 2 .
value_counts = {}
for key in dict:
value = dict[key]
current_count = value_counts.get(value, 0)
current_count += 1
value_counts[value] = current_count
# Make map: count -> list of key
# For example: 3 -> {1964}, 2 -> {1963, 1969, 1965, 1967}
count_rankings = {}
for key in value_counts:
count = value_counts[key]
ranking_bucket = count_rankings.get(count, [])
ranking_bucket.append(key)
count_rankings[count] = ranking_bucket
max_count = sorted(count_rankings).pop()
result_list = count_rankings[max_count]
if len(result_list) > 1: return result_list
else: return result_list[0]
|
def topological_sort(graph):
"""Topological sort algorithm to return a list of keys to a dictionary
of lists of dependencies. The returned keys define an order so
that all dependent items are in front of the originating item.
"""
def recurse(node, path):
if node not in path:
edges = graph[node]
for edge in edges:
if edge not in path:
path = recurse(edge, path)
path = path + [node]
return path
path = []
for node in sorted(graph):
path = recurse(node, path)
return path
|
def convert_number(s):
"""Convert a string to an integer, '123' to 123, or return None."""
try:
return int(s)
except ValueError:
return None
|
def make_mapping(args):
"""Make a mapping from the name=value pairs."""
mapping = {}
if args:
for arg in args:
name_value = arg.split('=', 1)
mapping[name_value[0]] = (name_value[1]
if len(name_value) > 1
else None)
return mapping
|
def chr2num(chr_name):
"""
Returns a numerical mapping for a primary chromosome name
Assumes names are prefixed with "chr"
"""
chr_id = chr_name[3:]
if chr_id == 'X':
return 23
elif chr_id == 'Y':
return 24
elif chr_id == 'M':
return 25
return int(chr_id)
|
def corrected_pas(partitionA, partitionB, taxlen=None, excluded=None):
"""
Computed corrected partition agreement score.
The corrected partition agreement score corrects for singleton character
states and for character states that recur in all the taxonomic units in
the data. These extreme cases are successively ignored when computing the
partition agreement score.
@param partitionA, partitionB: set partitions to be compared
@param taxlen: if set to None, the number of taxa will be computed from
partitionA
@param excluded: how to return excluded characters (defaults to None)
"""
links, matches = [], []
# prune by getting number of taxa described by partition
if not taxlen:
all_taxa = set()
for prt in partitionA:
for taxon in prt:
all_taxa.add(taxon)
taxlenA = len(all_taxa)
all_taxa = set()
for prt in partitionB:
for taxon in prt:
all_taxa.add(taxon)
taxlenB = len(all_taxa)
else:
taxlenA, taxlenB = taxlen, taxlen
for i, prtB in enumerate(partitionB):
for j, prtA in enumerate(partitionA):
if taxlenA > len(prtA) > 1 and taxlenB > len(prtB) > 1:
if prtA.intersection(prtB):
links += [1]
if prtB.issubset(prtA):
matches += [1]
if matches:
return sum(matches)/sum(links)
elif links:
return 0
return excluded
|
def index_with(l, cb):
"""Find the index of a value in a sequence using a callback.
:param l: The sequence to search.
:param cb: Function to call, should return true if the given value matches
what you are searching for.
:returns: Returns the index of the match, or -1 if no match.
"""
for i, v in enumerate(l):
if cb(v):
return i
return -1
|
def format_version(version):
"""Converts a version specified as a list of integers to a string.
e.g. [1, 2, 3] -> '1.2.3'
Args:
version: ([int, ...]) Version as a list of integers.
Returns:
(str) Stringified version.
"""
return '.'.join(str(x) for x in version)
|
def compare_h(new, high):
"""
Compare the latest temperature with the highest temperature.
If higher, replace it. If not, remain the same.
:param new: Integer, new!=EXIT, The lasted temperature input
:param high: Integer, high!=EXIT, the highest temperature of all time
:return: high
"""
if new > high:
high = new
return high
else:
high += 0
return high
|
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5',\
'*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215',\
'*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215',\
'*35214*', '*41532*', '*2*1***'])
False
"""
for i in board:
if '?' in i:
return False
return True
|
def getVal(item):
"""
Get value of an item, as weight / value, used for sorting
Args:
item: A dictionary with entries "weight" and "value"
Returns:
The item's weight per value
"""
return item["weight"] / item["value"]
|
def filter_list(func, alist):
""" Filters a list using a function.
:param func: A function used for filtering.
:param alist: The list to filter.
:returns: The filtered list.
>>> from dautils import collect
>>> alist = ['a', 'a.color', 'color.b']
>>> collect.filter_list(lambda x: x.endswith('color'), alist)
['a.color']
"""
return [a for a in alist if func(a)]
|
def _generateKey(package, subdir):
"""Generate a key for a path inside a package.
The key has the quality that keys for subdirectories can be derived by
simply appending to the key.
"""
return ':'.join((package, subdir.replace('\\', '/')))
|
def triangle_area(base, height):
"""Returns the area of a triangle"""
return (base * height)/2
|
def get_options(options):
"""
Get options for dcc.Dropdown from a list of options
"""
opts = []
for opt in options:
opts.append({'label': opt, 'value': opt})
return opts
|
def update_keeper(keeper, next_point):
"""
Update values of the keeper dict.
"""
keeper["prev_point"] = keeper["curr_point"]
keeper["curr_point"] = next_point
keeper["coverage_path"].append(next_point)
# If everything works this conditional
# should evaluate to True always
if not keeper["is_visited"][next_point]:
keeper["is_visited"][next_point] = True
return True
return False
|
def encode(tstr):
""" Encodes a unicode string in utf-8
"""
if not tstr:
return ''
# this is _not_ pretty, but it works
try:
return tstr.encode('utf-8', "xmlcharrefreplace")
except UnicodeDecodeError:
# it's already UTF8.. sigh
return tstr.decode('utf-8').encode('utf-8')
|
def property_quote_if(alias, name):
"""
Make a property reference, escaping it if necessary
:param alias: object alias
:param name: property name
:return: property reference
:rtype: str
"""
if ' ' in name:
# This syntax is useful to escape a property that contains spaces, special characters, or has the same name as a
# SQL keyword or reserved word.
prop = f'["{name}"]'
else:
prop = f'.{name}'
return f'{alias}{prop}'
|
def not_contains(a, b):
"""Evaluates a does not contain b"""
result = False if b in a else True
return result
|
def add_class(add, class_):
"""Add to a CSS class attribute.
The string `add` will be added to the classes already in `class_`, with
a space if needed. `class_` can be None::
>>> add_class("foo", None)
'foo'
>>> add_class("foo", "bar")
'bar foo'
Returns the amended class string.
"""
if class_:
class_ += " "
else:
class_ = ""
return class_ + add
|
def doDent(d, p=0, style=' '):
"""
Creates an indent based on desired level
@ In, d, int, number of indents to add nominally
@ In, p, int, number of additional indents
@ In, style, str, optional, characters for indenting
@ Out, dent, str, indent string
"""
return style * (d + p)
|
def is_sha1_sum(s):
"""
SHA1 sums are 160 bits, encoded as lowercase hexadecimal.
"""
return len(s) == 40 and all(c in '0123456789abcdef' for c in s)
|
def _basic_str(obj):
"""
Handy for writing quick and dirty __str__() implementations.
"""
return obj.__class__.__name__ + ': ' + obj.__repr__()
|
def populate_list(my_list, dir_list):
"""converts a listing of dir into list containing html selection option tags"""
for f in dir_list:
my_list.append((f,f))
return my_list
|
def dotprod(a, b):
""" Compute dot product
Args:
a (dictionary): first dictionary of record to value
b (dictionary): second dictionary of record to value
Returns:
dotProd: result of the dot product with the two input dictionaries
"""
# get commong dict keys:
common_keys = set(a).intersection(set(b))
dotproduct = 0
for key in common_keys:
prod = a[key] * b[key]
dotproduct += prod
return dotproduct
|
def plural(word, items):
"""Returns "N words" or "1 word"."""
count = len(items) if isinstance(items, (dict, list, set, tuple)) else items
return "%s %s%s" % (count, word, "s" if count != 1 else "")
|
def get_magnitude_range(magnitudes):
"""
Determine magnitude span of events trying to be matched.
Args:
magnitudes (array):
Array of event magnitudes.
Returns:
mag_range (list): Integer range of event magnitudes.
"""
max_m = max(magnitudes)
max_l = min(magnitudes)
mag_range = list(range(int(max_l), int(max_m) + 1))
return mag_range
|
def _sum_counters(*counters_list):
"""Combine many maps from group to counter to amount."""
result = {}
for counters in counters_list:
for group, counter_to_amount in counters.items():
for counter, amount in counter_to_amount.items():
result.setdefault(group, {})
result[group].setdefault(counter, 0)
result[group][counter] += amount
return result
|
def breaks(n=0):
"""Return n number of newline characters"""
return "\n"*n
|
def get_prefix_count(prefix, arr):
"""Counts how many strings in the array start with the prefix.
Args:
prefix: The prefix string.
arr: An array of strings.
Returns:
The number of strings in arr starting with prefix.
"""
# This code was chosen for its elegance not its efficiency.
return len([elt for elt in arr if elt.startswith(prefix)])
|
def tableify(table):
"""Takes a list of lists and converts it into a formatted table
:arg table: list (rows) of lists (columns)
:returns: string
.. Note::
This is text formatting--not html formatting.
"""
num_cols = 0
maxes = []
for row in table:
num_cols = max(num_cols, len(row))
if len(maxes) < len(row):
maxes.extend([0] * (len(row) - len(maxes)))
for i, cell in enumerate(row):
maxes[i] = max(maxes[i], len(str(cell)))
def fix_row(maxes, row):
return ' '.join([
str(cell) + (' ' * (maxes[i] - len(str(cell))))
for i, cell in enumerate(row)
])
return '\n'.join(
[
fix_row(maxes, row)
for row in table
]
)
|
def r_p(n, costheta):
"""Fresnelreflectivity for two interfaces.
**Arguments:**
- **n**: iterable with two entries for (n_0, n_1)
- **costheta:** iterable with two entries for (costheta_0, costheta_1)
costheta is used, because it can be complex.
"""
i, j = 0, 1
a = n[j] * costheta[i] - n[i] * costheta[j]
b = n[j] * costheta[i] + n[i] * costheta[j]
return a/b
|
def format_time(time):
""" Format a given integer (UNIX time) into a string.
Convert times shorter than a minute into seconds with four decimal places.
Convert longer times into rounded minutes and seconds, separated by a colon. """
if time >= 60:
minutes, seconds = divmod(time, 60)
return f"{round(minutes)}:{round(seconds):02d}min"
return f"{time:.4f}sec"
|
def _get_description(var, parameters):
"""
Get the description for the variable from the parameters.
This was manually added in the driver to the viewer_descr parameter.
"""
if hasattr(parameters, "viewer_descr") and var in parameters.viewer_descr:
return parameters.viewer_descr[var]
return var
|
def validate_ranges(ranges):
"""
Validate ASN ranges provided are valid and properly formatted
:param ranges: list
:return: bool
"""
errors = []
for asn_range in ranges:
if not isinstance(asn_range, list):
errors.append("Invalid range: must be a list")
elif len(asn_range) != 2:
errors.append("Invalid range: must be a list of 2 members")
elif any(map(lambda r: not isinstance(r, int), asn_range)):
errors.append("Invalid range: Expected integer values")
elif asn_range[1] <= asn_range[0]:
errors.append("Invalid range: 2nd element must be bigger than 1st")
return errors
|
def return_an_int(param):
"""Returns an int"""
if param == 0:
return 1
return 0
|
def count_pattern_in_list(lst, seq):
"""
Counts a specific pattern of objects within a list.
Usage:
count_pattern_in_list([1,0,1,2,0,1], [0,1]) = 2
"""
count = 0
len_seq = len(seq)
upper_bound = len(lst) - len_seq + 1
for i in range(upper_bound):
if lst[i:i + len_seq] == seq:
count += 1
return count
|
def translate(s, N):
"""Shift the bits of the state `s` one position to the right (cyclically for N bits)."""
bs = bin(s)[2:].zfill(N)
return int(bs[-1] + bs[:-1], base=2)
|
def format_time(t):
"""Return a formatted time string 'HH:MM:SS
based on a numeric time() value"""
m, s = divmod(t, 60)
h, m = divmod(m, 60)
return f'{h:0>2.0f}:{m:0>2.0f}:{s:0>2.0f}'
|
def get_attachments_path_from_id(id: int, *, min_length=6) -> str:
"""
converts int to str of min_length and then splits each digit with "/"
:param id:
:param min_length:
:return: str
"""
if id <= 0:
return ""
id_str = str(id)
if len(id_str) < min_length:
concat_str = "".join(['0' for i in range(0, min_length-len(id_str))])
id_str = concat_str+id_str
path = "/".join([id_str[i] for i in range(0, len(id_str))])
path = f"{path}/{id}"
return path
|
def expand_locations_and_make_variables(ctx, attr, values, targets = []):
"""Expands the `$(location)` placeholders and Make variables in each of the given values.
Args:
ctx: The rule context.
values: A list of strings, which may contain `$(location)`
placeholders, and predefined Make variables.
targets: A list of additional targets (other than the calling rule's
`deps`) that should be searched for substitutable labels.
Returns:
A list of strings with any `$(location)` placeholders and Make
variables expanded.
"""
return_values = []
for value in values:
expanded_value = ctx.expand_location(
value,
targets = targets,
)
expanded_value = ctx.expand_make_variables(
attr,
expanded_value,
{},
)
return_values.append(expanded_value)
return return_values
|
def dichotomy_grad (f, arg_before, z_e, arg_after, w_0, de, grad):
"""
f : function for f(*in_first,z,*in_after) = w
arg_before, arg_after : f function arguments that come before and after z_e
z_e : firstguess for the value to be tested
w_0: target value for w
de : delta error
grad : gradient
"""
w_i = f(*arg_before, z_e, *arg_after)
di = w_0 - w_i
z_i = z_e
c = 0
# print(f"dicho start\nw_0={w_0:.2f}; z_i={z_i:.2f}; w_i={w_i:.2f}; di={di:.2f}; add={(di/grad):.2f}; ");
while (abs(di) >= de):
c+=1
z_i += di/grad
w_i = f(*arg_before, z_i, *arg_after)
di = w_0 - w_i
# sleep(1);
# print(f"w_0={w_0:.2f}; z_i={z_i:.2f}; w_i={w_i:.2f}; di={di:.2f}; add={(di/grad):.2f}; ");
# print(f"dichotomy_grad: {c} steps")
return z_i
|
def checkpoints(period, total):
"""
A helpful function for individual train method.
to generate checkpoint list with integers
for every PERIOD time steps and TOTAL time steps in total.
"""
ckps = [
period * x for x in range(1, total // period)
]
return ckps
|
def num(a, p):
"""Return a / 10^p"""
a = int(a)
m = str(a % 10**p)
m = '0'*(p-len(m))+m
return str(a // 10**p) + "." + m
|
def using(join_string, *parts):
"""return parts joined using the given string"""
return join_string.join(parts)
|
def to_flags(value):
"""Convert an opcode to a value suitable for ORing into DNS message
flags.
*value*, an ``int``, the DNS opcode value.
Returns an ``int``.
"""
return (value << 11) & 0x7800
|
def merge_sort(items):
"""Merge sort in Python
>>> merge_sort([])
[]
>>> merge_sort([1])
[1]
>>> merge_sort([2,1])
[1, 2]
>>> merge_sort([6,1,4,2,3,5])
[1, 2, 3, 4, 5, 6]
"""
# Base case
if len(items) <= 1:
return items
mid = len(items)//2
l = items[:mid]
r = items[mid:]
merge_sort(l)
merge_sort(r)
i = 0
j = 0
k = 0
while i < len(l) and j < len(r):
if l[i] < r[j]:
items[k] = l[i]
i += 1
else:
items[k] = r[j]
j += 1
k += 1
while i < len(l):
items[k] = l[i]
i += 1
k += 1
while j < len(r):
items[k] = r[j]
j += 1
k += 1
return items
|
def AB2_step(f, tcur, ucur, h, fold):
"""
Usage: unew, fcur = AB2_step(f, tcur, ucur, h, fold)
Adams-Bashforth method of order 2 for one step of the ODE
problem,
u' = f(t,u), t in tspan,
u(t0) = u0.
Inputs: f = function for ODE right-hand side, f(t,u)
tcur = current time
ucur = current solution
h = time step size
fold = RHS evaluated at previous time step
Outputs: unew = updated solution
fcur = RHS evaluated at current time step
"""
# get ODE RHS at this time step
fcur = f(tcur, ucur)
# update solution in time, and return
unew = ucur + h/2*(3*fcur - fold)
return [unew, fcur]
|
def format_results_by_model(results, model):
"""
Format results dictionary to print different calculated model parameters,
depending on model used.
:return Multiline string of model parameter name: values.
"""
text = ''
if model == 'exponential':
for i in range(results['numberOfSegments']):
text += 'Segment {} Bt: {:.3f}\n'.format(
i, results['segmentBts'][i])
text += 'Segment {} Coefficient: {:.3f}\n'.format(
i, results['segmentCoefficients'][i])
text += 'Segment {} Exponent: {:.3f}\n'.format(
i, results['segmentExponents'][i])
text += 'Segment {} Limit: {:.3f}\n'.format(
i, results['segmentLimits'][i + 1])
text += 'Segment {} Volume: {:.1f}\n'.format(
i, results['segmentVolumes'][i])
elif model == 'power_law':
text += 'Coefficient: {:.3f}\n'.format(results['coefficient'])
text += 'Exponent: {:.3f}\n'.format(results['exponent'])
text += 'Suggested Proximal Limit: {:.1f}\n'.format(
results['suggestedProximalLimit'])
elif model == 'weibull':
text += 'k: {:.3f}\n'.format(results['k'])
text += 'lambda: {:.0f}\n'.format(results['lambda'])
text += 'theta: {:.5f}\n'.format(results['theta'])
text += 'MRSE of fit: {:.03f}\n'.format(results['mrse'])
text += 'Total Volume: {:.2f}\n'.format(results['estimatedTotalVolume'])
return text
|
def boolean_function(bool_variable):
""" A function with one parameter which is used to determine what to return """
if bool_variable:
return "The boolean variable is True"
else:
return "The boolean variable is False"
|
def split_age_parameter(age_breakpoints, parameter):
"""
creates a dictionary to request splitting of a parameter according to age breakpoints, but using values of 1 for
each age stratum
allows that later parameters that might be age-specific can be modified for some age strata
:param age_breakpoints: list
list of the age breakpoints to be requested, with breakpoints as string
:param parameter: str
name of parameter that will need to be split
:return: dict
dictionary with age groups as string as keys and ones for all the values
"""
age_breakpoints = ["0"] + age_breakpoints if "0" not in age_breakpoints else age_breakpoints
return {parameter: {str(age_group): 1.0 for age_group in age_breakpoints}}
|
def binstringToBitList(binstring):
"""Converts a string of '0's and '1's to a list of 0's and 1's"""
bitList = []
for bit in binstring:
bitList.append(int(bit))
return bitList
|
def sum_clones(subset, state):
"""
Sums the number of cells in clones belonging to ``subset`` for ``state``.
Parameters
----------
subset : tuple
Clonotypes in the subset.
state : list[int]
Number of cells per clonotype.
Returns
-------
total_cells : float
Total number of cells in subset for state.
"""
total_cells = 0.0
for s in subset:
total_cells += float(state[s])
return float(total_cells)
|
def pept_diff(p1, p2):
"""
Return the number of differences betweeen 2 peptides
:param str p1: Peptide 1
:param str p2: Peptide 2
:return: The number of differences between the pepetides
:rtype: int
>>> pept_diff('ABCDE', 'ABCDF')
1
>>> pept_diff('ABCDE', 'ABDFE')
2
>>> pept_diff('ABCDE', 'EDCBA')
4
>>> pept_diff('ABCDE', 'ABCDE')
0
"""
if len(p1) != len(p2):
return -1
else:
return sum([p1[i] != p2[i] for i in range(len(p1))])
|
def var_radrad(tsclass):
""" Return boolean to see if fake wells are needed
"""
rad_rad = 'radical-radical' in tsclass
low_spin = 'high' not in tsclass
return bool(rad_rad and low_spin)
|
def gcd(num1: int, num2: int) -> int:
"""
Returns the greatest common divisor of `num1` and `num2`.
Examples:
>>> gcd(12, 30)
6
>>> gcd(0, 0)
0
>>> gcd(-1001, 26)
13
"""
if num1 == 0:
return num2
if num2 == 0:
return num1
if num1 < 0:
num1 = -num1
if num2 < 0:
num2 = -num2
# This is the Euclidean algorithm
while num2 != 0:
num1, num2 = num2, num1 % num2
return num1
|
def _GetSSHKeyListFromMetadataEntry(metadata_entry):
"""Returns a list of SSH keys (without whitespace) from a metadata entry."""
keys = []
for line in metadata_entry.split('\n'):
line_strip = line.strip()
if line_strip:
keys.append(line_strip)
return keys
|
def has_trigger_lemmas(metadata,
lemmas=["infection", "death", "hospitalization"]):
"""
Return True if any lemmas in the metadata dict match lemmas of interest.
By default, lemmas of interest are "infection", "death", and "hospitalization".
Written to improve readability, since this is used a lot in the annotation functions.
"""
return any([lemma in metadata["attributes"] for lemma in lemmas])
|
def cipher(text, shift, encrypt=True):
"""Secure message through encryption.
Message is encrypted by shifting each letter by the
specified amount and direction.
Parameters
----------
text : str
message to be encrypted.
shift : int
number of shifts added to each letter
encrypt : bool
direction of shift. (default = True)
Returns
-------
str
message encrypted by cipher technique
Examples
--------
>>> cipher("quiet! It's a secret", 2, True)
"swkgv! Kv'u c ugetgv"
"""
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
new_text = ''
for c in text:
index = alphabet.find(c)
if index == -1:
new_text += c
else:
new_index = index + shift if encrypt == True else index - shift
new_index %= len(alphabet)
new_text += alphabet[new_index:new_index+1]
return new_text
|
def has_prim_rou(modulus: int, degree: int) -> bool:
"""
Test whether Z/qZ has a primitive 2d-th root of unity.
"""
return modulus % (2 * degree) == 1
|
def primes_sieve2(n):
""" Sieve method 2: Returns a list of primes < n
>>> primes_sieve2(100)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
"""
sieve = [True] * n
upper = int(n**0.5)+1
for i in range(3, upper, 2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
# must assign iterable to extended slice sieve[i*i::2*i]
return [2] + [i for i in range(3, n, 2) if sieve[i]]
|
def circled_number(number, bold_circle=True):
"""Provide a Unicode representation of the specified number.
:param int number: The positive number to convert to a string.
:param bool bold_circle: If ``True``, return a white number on a black
circle; return a black number on a white circle otherwise.
:return: A string that is the specified number enclosed in a circle. For
integers that have no such representation in Unicode, return the number
enclosed in parentheses.
"""
if number <= 0:
raise ValueError()
elif number < 10:
return chr((0x2775 if bold_circle else 0x245f) + number)
elif number < 21 and not bold_circle:
return chr(0x245f + number)
elif number == 10 and bold_circle:
return chr(0x277f)
elif number < 21 and bold_circle:
return chr(0x24e0 + number)
elif bold_circle:
return '[%s]' % (number,) # raise ValueError()
elif number < 30:
return chr(0x323c + number)
elif number == 30:
return chr(0x325a)
elif number < 36:
return chr(0x323c + number)
elif number < 51:
return chr(0x328d + number)
else:
return '(%s)' % (number,)
|
def _join_url_prefix(*parts):
"""Join prefixes."""
parts = [part.strip("/") for part in parts if part and part.strip("/")]
if parts:
return "/" + "/".join(parts)
|
def delete_doubles(arr):
"""
:param arr: list()
:return: Given list, without duplicated entries
"""
arr2 = []
for element in arr:
if not arr2.__contains__(element):
arr2.append(element)
return arr2
|
def UT2TOW(UT):
"""Universal Time (UT) to Time Of Week (TOW)
Converts time of the day in Universal Time to time in seconds measured since the start of the week.
Args:
UT (str): Universal Time
Returns:
int: Time Of Week (TOW)
"""
hrs, mins, sec = UT.split(':')
hrs = int(hrs)
mins = int(mins)
sec = int(sec)
TOW = hrs*3600 + mins*60 + sec
return TOW
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.