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), (... |
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
... |
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:
... |
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:
... |
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
... |
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 ne... |
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_import... |
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... |
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 t... |
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 ... |
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 = -b... |
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... |
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 + '!!!'
# Ret... |
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 ... |
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': ... |
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 <= ... |
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:`F... |
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,
... |
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:
ed... |
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
... |
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 ar... |
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.
"""
f... |
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 =... |
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
>>... |
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.endswit... |
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 ke... |
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('... |
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... |
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 cl... |
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 =... |
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)
... |
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, {})
... |
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.
... |
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_c... |
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] * costhe... |
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)
retu... |
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]
ret... |
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(a... |
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] ==... |
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 =... |
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 Ma... |
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 : gradi... |
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[... |
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 tim... |
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['numberOfSegm... |
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_break... |
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
T... |
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
>>> pep... |
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 = -... |
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 ... |
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
... |
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 siev... |
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... |
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 = in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.