content stringlengths 42 6.51k |
|---|
def is_overlapping(segment_time, previous_segments):
"""
Checks if the time of a segment overlaps with the times of existing segments.
Arguments:
segment_time -- a tuple of (segment_start, segment_end) for the new segment
previous_segments -- a list of tuples of (segment_start, segment_end) for the... |
def get_area(coords):
"""
get area of enclosed coordinates- determines clockwise or counterclockwise order
:param coords:
:return:
"""
n = len(coords) # of corners
area = 0.0
for i in range(n):
j = (i + 1) % n
area += coords[i][1] * coords[j][0]
area -= coords[j][... |
def query_id_to_osm(query_id, what='node', layer_code='M'):
"""
Ask openstreetmap.org to show a particular node, way, or relation.
References:
http://wiki.openstreetmap.org/wiki/Browsing
http://wiki.openstreetmap.org/wiki/Layer_URL_parameter
@param query_id: Id of node, way, or relation.
@... |
def _parse_const(obj, context):
"""
Check if string is a supported const
"""
if obj == "np.nan":
return context["nan"]
return obj |
def area_triangle(base, height):
"""
calculate area of triangle
parameters:
base, int
"""
A = base*0.5*height
return A |
def _check_pair(minterm1, minterm2):
"""
Checks if a pair of minterms differs by only one bit. If yes, returns
index, else returns -1.
"""
index = -1
for x, (i, j) in enumerate(zip(minterm1, minterm2)):
if i != j:
if index == -1:
index = x
else:
... |
def convert_diameter_sigma_to_fwhm(diameter):
"""
Converts a beam diameter expressed as the full with at half maximum (FWHM)
to a beam diameter expressed as 2-sigma of a Gaussian distribution
(radius = sigma).
:arg diameter: 2-sigma diameter diameter.
"""
# d_{FWHM} = 1.177411 (2\sigma)
... |
def lists_merge(main, patch, key):
"""Merges the list of dicts with same keys.
>>> lists_merge([{"a": 1, "c": 2}], [{"a": 1, "c": 3}], key="a")
[{'a': 1, 'c': 3}]
:param main: the main list
:type main: list
:param patch: the list of additional elements
:type patch: list
:param key: the... |
def _rol(val, num):
"""Rotates val to the left by num bits."""
return ((val << (num % 32)) & 0xffffffff) | (val >> (32 - (num % 32))) |
def format_mac(mac):
"""Format a MAC address."""
return ":".join([format(octet, "02x") for octet in mac]) |
def _pandas_in_schemas(schemas):
"""
Check if any schema contains pandas metadata
"""
has_pandas = False
for schema in schemas:
if schema.metadata and b"pandas" in schema.metadata:
has_pandas = True
return has_pandas |
def _make_canonical_headers(headers, headers_to_sign):
"""
Return canonicalized headers.
@param headers: The request headers.
@type headers: L{dict}
@param headers_to_sign: A sequence of header names that should be
signed.
@type headers_to_sign: A sequence of L{bytes}
@return: The... |
def removeFromEnd(text, toRemove, ignoreCase=None):
"""returns the text with "toRemove" stripped from the end if it matches
>>> removeFromEnd('a.jpg', '.jpg')
u'a'
>>> removeFromEnd('b.jpg', '.gif')
u'b.jpg'
working of ignoreCase:
>>> removeFromEnd('C.JPG', '.jpg')
u'C.JPG'
>>> removeFromEnd('D.JPG',... |
def step_lr(learning_rate, epoch):
"""Step Learning rate.
Args:
learning_rate: Initial learning rate.
epoch: Current epoch we are one. This is one based.
Returns:
The learning rate to be used for this current batch.
"""
if epoch < 80:
return learning_rate
elif epoch < 120:
... |
def device_to_host(request_type):
""" Check if the direction is device to host """
return (request_type & 0x80) == 0x80 |
def change_format(distractors):
""" change s2v format to fair readable form. Remove '|,_' and toggle case.
Args:
distractors (list[tuple(str,int)]): list of most similar words and their
similiarity.
Returns:
list[str]: human-readable format of distractors.
"""
output = []
... |
def parse_query(query_to_parse):
"""
Converts a comma or space-separated string of query terms into a list to use
as filters. The use of positional arguments on the CLI provides lists (which
we join and resplit to avoid any formatting issues), while strings passed
from pssh.py just get split since ... |
def password_okay_by_position(pwd_row):
"""
Pwd is only valid if the indicated character is found in either the first numbered
OR second numbered position. It is not valid if the character is found in both positions.
The password policy is 1-indexed.
E.g. 5-7 z: qhcgzzz
This pwd is invalid, si... |
def trim_and_check_pose_safety(position, fence):
"""
take in a position list [x,y,z] and ensure it doesn't violate the defined fence
"""
hit = False
safe_position = []
for ind, dim in enumerate(['x','y','z']):
if max(fence[dim]) < position[ind]:
out = max(fence[dim])
... |
def f(x):
"""does some math"""
return x + x * x |
def calc_check_digit(number):
"""Calculate the check digit for organisations. The number passed should
not have the check digit included."""
weights = (5, 4, 3, 2, 7, 6, 5, 4)
s = sum(w * int(n) for w, n in zip(weights, number))
return str((11 - s) % 11) |
def is_present(marks, text):
"""
return True, if all marks present in given text
"""
return all([mark in text for mark in marks]) |
def get_important_pages(important_pages, top=10, influenza_seasons=4):
"""
Get the most important feature selected by the model.
:param important_pages: a dictionary with, for each of the features,
a list of their weights in each of the models.
:param top: how many feature we want to return.
:r... |
def opponent(j):
"""
Returns the opponent of player j.
:param j: the player (0 or 1).
:return: its opponent.
"""
if j == 1:
return 0
else:
return 1 |
def is_comment(source_str, file_ext):
"""Returns True if the line appears to start with a comment, False otherwise."""
if file_ext in ['.c', '.cpp', '.cxx', '.h', '.m', '.java', '.rs']:
if source_str.find('//') == 0 or source_str.find('/*') == 0:
return True
elif file_ext in ['.py']:
if source_str.find('#') =... |
def _build_message(texts, gif=None):
""" Internal method """
base_dict = {
'$schema': 'http://adaptivecards.io/schemas/adaptive-card.json',
'type': 'MessageCard',
'version': '1.0',
'themeColor': 'FFA800',
'summary': 'Notification',
'sections': []
}
for te... |
def set_color_tuple(brick):
"""
Set up the color dict in which
(R, G, B): (the approximate half (for efficiency) number of the color, int)
:param brick, a list of tuples of RGB:
:return a tuple in which the first element is a dict and the second is an int:
"""
colors = {}
color_num = 0
... |
def create_variant_to_protein_sequence_read_names_dict(isovar_results):
"""
Create dictionary from variant to names of alt reads used to create
mutant protein sequence in an IsovarResult.
Parameters
----------
isovar_results : list of IsovarResult
Returns
-------
Dictionary from va... |
def get_percent_crowd_agreement(crowd_selection, selection_counts, total_responses, map_selection_field,
error_val=None):
"""
Figure out how well the crowd agreed and if two answers tied, figure out the agreement for both
:param crowd_selection: the winning selection for a ... |
def S(*regexps) -> str:
"""Just a shortcut to concatenate multiple regexps more easily"""
return ''.join(regexps) |
def sub(value, arg):
"""Add the arg to the value."""
try:
return int(value) - int(arg)
except (ValueError, TypeError):
try:
return value - arg
except Exception:
return '' |
def load_config_file(fname):
"""Load a JSON file from disk and return it as a string."""
try:
f = open(fname, 'r')
except OSError as e:
print("Failed to open {}", fname)
return ''
strList = f.readlines()
f.close()
return ''.join(strList) |
def format_p_value(p, use_stars=False):
"""Format P values"""
if not use_stars:
return "P = {:.1g}".format(p).replace("0.", ".")
else:
if p < 0.001:
return "***"
elif p < 0.01:
return "**"
if p < 0.05:
return "*"
else:
... |
def _without_command(results):
"""A helper to tune up results so that they lack 'command'
which is guaranteed to differ between different cmd types
"""
out = []
for r in results:
r = r.copy()
r.pop('command')
out.append(r)
return out |
def flatten(lst):
"""Flatten a list of lists into a list"""
return [l for ls in lst for l in ls] |
def is_close(a, b, rel_tol=1e-09, abs_tol=0):
"""Determines whether two numbers are nearly equal.
The maximum of the relative-based and absolute tolerances is used to test
equality.
This function is taken from `math.isclose` in Python 3 but is explicitly
implemented here for Python 2 compatibility... |
def encode(bytedata):
"""Convert a bytestring into a zerocoded bytestring"""
i = 0
l = len(bytedata)
c = 0
start = 0
while i < l:
if c > 253 or (bytedata[i] != 0 and c != 0):
bytedata = bytedata[:start+1] + bytes((c,)) + bytedata[i:]
i = i - c + 1
l = ... |
def encodedUNTL_to_UNTL(subject):
"""Return a normalized UNTL subject heading back to string."""
subject = subject.replace('/', '_-_')
subject = subject.replace('_', ' ')
return subject |
def test_id_formatter(*args, **kw):
"""
Format test ids for comparison operators
"""
width = kw.get('w') or 35
if len(args) == 2:
(dsc, tfx) = args
tfx = tfx.strip()
if tfx == "T":
fmt = "{:>{width}s} |{:<3s}"
elif tfx == "F":
fmt = "{:>{width... |
def p_string(val, use_asterisks=False):
""" Return a string with properly formatted p-value.
:param val: float p-value
:param use_asterisks: True to report just asterisks rather than quantitative value
:returns: formatted string for reporting
"""
if val < 0.00001:
if use_asterisks:
... |
def pack_int(value, length):
""" Unpack an int for serialisation """
return value.to_bytes(length, 'little', signed=False) |
def generate_imm5(value):
"""Returns the 5-bit two's complement representation of the number."""
if value < 0:
# the sign bit needs to be bit number 5.
return 0x1 << 4 | (0b1111 & value)
else:
return value |
def isop(char):
"""Simple function to determine whether a character is a c
operator character (not including semi-colon)."""
if ((char == '-') or (char == '+') or (char == ',') or (char == '=')
or (char == '(') or (char == ')') or (char == '?') or (char == ':')
or (char == '*') or (char ==... |
def list_strip_eos(list_, eos_token):
"""Strips EOS token from a list of lists of tokens.
"""
list_strip = []
for elem in list_:
if eos_token in elem:
elem = elem[:elem.index(eos_token)]
list_strip.append(elem)
return list_strip |
def suites_by_class(tests):
"""Creates a {class --> [suite_instance, ...]} mapping."""
suite_dict = {}
for test in tests:
try:
for suite in test.cfg.suites:
if suite.__class__ not in suite_dict:
suite_dict[suite.__class__] = []
suite_di... |
def remove_html(s):
"""
Removes all HTML tags from a string.
"""
tmp = s
#while (sub := tmp.find('<')) >= 0:
sub = tmp.find('<')
while sub >= 0:
tmp1 = tmp[:sub]
tmp2 = tmp[sub:]
sub = tmp2.find('>')
tmp = tmp1 + tmp2[sub+1:]
sub = tmp.find('<')
... |
def jump(nums):
"""
:type nums: List[int]
:rtype: int
"""
jump = 0
ability = 1 # the ability to jump at current point
reach = 0
# do not care about the last one, we only need to know the second last one's ability is not 0,
# or we have to make one more jump
for i in range(0, len... |
def transform_uppercase(val, mode=None):
"""
Convert to uppercase
<dotted>|uppercase string to uppercase
<dotted>|uppercase:force string to uppercase or raises
"""
try:
return val.upper()
except TypeError:
if mode == 'force':
raise
return v... |
def rcomp(seq):
"""
reverse complement our sequence
:param seq:
:return:
"""
def _complement(rseq):
"""
This is code copied from BioPython. It is here because Python 3.3 does not give the same result as Python 3.4 when
called from the Biopython Seq module.
... |
def clean_atoms(atoms, xo, yo, zo):
"""
Converts the x, y and z cooridnates from strings to floats and corrects for
the origin offset. Furthermore changes two letter atomic symbols from XX to
Xx.
"""
for atom in atoms:
if atom[0].find('___') > 0: #If APPLY symm used in XDFOUR e.g. C(1)_... |
def path_with_sums(root, total):
""" 4.12 Paths with Sum: You are given a binary tree in which each node
contains an integer value (which might be positive or negative).
Design an algorithm to count the number of paths that sum to a given value.
The path does not need to start or end at the root or a le... |
def _parse_vars(variables, vardict):
"""Helper for parsing env, sys variables.
"""
domains = []
for v in variables:
dom = vardict[v]
if dom[0] == "[":
end_ind = dom.find("]")
if end_ind < 0:
raise ValueError((
'invalid domain fo... |
def is_interval_subset(interval1, interval2):
"""Checks whether interval1 is subset of interval2."""
# Check the upper bound.
if (interval1[1] == "inf" and interval2[1] != "inf") or \
(interval1[1] != "inf" and interval2[1] != "inf" and interval1[1] > interval2[1]):
return False
# C... |
def valid_enough_email(address):
"""Sanity check a user supplied email address.
Validation of an email address is very difficult. Make a best effort attempt to
see if it minimally conforms to the following RFCs.
https://tools.ietf.org/html/rfc822
https://tools.ietf.org/html/rfc2822
https://to... |
def nbytes_to_nwords(n, width):
"""how many width-bit words in n bytes?"""
(mask, shift) = ((3, 2), (7, 3))[width == 64]
return ((n + mask) & ~mask) >> shift |
def do_checksum(source_string):
""" Verify the packet integrity """
sum = 0
max_count = (len(source_string)/2)*2
count = 0
while count < max_count:
val = source_string[count + 1]*256 + source_string[count]
sum = sum + val
sum = sum & 0xffffffff
count = count + 2
... |
def gamma_encode(x):
"""Converts RGB data to `viewable values <https://en.wikipedia.org/wiki/Gamma_correction>`_."""
return x**(1/2.2) |
def check_description(sig_info, errors):
"""
Check description
:param sig_info: content of sig-info.yaml
:param errors: errors count
:return: errors
"""
if 'description' not in sig_info.keys():
print('ERROR! description is a required field')
errors += 1
else:
prin... |
def decode_src_string(src_string):
"""Decodes minilogue_og_patch_normalisation tuple src strings.
The tuples take the form (Note here N >= 1)
('dest_name', 'src1_name_XX_x', 'src2_name_XX_x', ..., 'srcN_name_XX_x')
'src1_name_XX_x' contains 'src1_name', the name of a source field, a hex bit mask XX
... |
def vtimesw(v, w):
"""
v * w (element-wise)
"""
return [v[i] * w[i] for i in range(len(v))] |
def common_denominator(number_one, number_two, range_one, range_two):
"""
Recursion solution to this problem even though it is not the best way of doing it.
Base case is when the modulo of both numbers and the second range value is zero,
or if they are the same.
Parameters
----------
numbe... |
def partTypeNum(partType):
""" Mapping between common names and numeric particle types. """
if str(partType).isdigit():
return int(partType)
if str(partType).lower() in ['gas','cells']:
return 0
if str(partType).lower() in ['dm','darkmatter']:
return 1
if str(partType).l... |
def ValidateCoords(coords):
"""
Check that latitude/longitude values defining a bounding box are within acceptable ranges
Parameters
----------
coords : list
List of coordinates to evaluate: minlat, maxlat, minlon, maxlon
Returns
-------
result : boolean
"""
... |
def isprimeF(n: int, b: int) -> bool:
"""True if n is prime or a Fermat pseudoprime to base b."""
return pow(b, n - 1, n) == 1 |
def find_max_weight(regions):
"""Find the maximal weight in the given regions"""
mw = 0
for r in regions:
mw = max(mw, r.profEntry.weight)
return mw |
def dict_to_args(dict):
"""
Convert an dictionary to a args list
:param dict: Dictionary
:return: List
"""
_args = []
for key, val in dict.items():
if isinstance(val, bool):
if val:
_args.append(f'--{key}')
else:
_args.append(f'--{key}'... |
def getDecile(type):
"""
Return a list of decile in either string or numeric form from ``5p`` to ``95p``.
We also include the ``50p`` for convinient.
Parameters
----------
type: str
Type of decile. Currently supported ``'string'`` (e.g. ``'5p'``) or
``... |
def _get_order_and_exponentiation_step(method):
"""Return order and exponentiation step given ``method``.
Given ``method`` we return the initial order of the approximation error of the
sequence under consideration (order) as well as the step size representing the
growth of the exponent in the series ex... |
def fan(raw_table, base_index):
""" Convert for fan speed """
val = raw_table[base_index]
return val & 0x007F |
def macros_as_tuples(macros):
"""Return all macros as tuples. Required by distutils.ccompiler."""
ret_macros = list()
for macro in macros:
if isinstance(macro, str):
ret_macros.append((macro, ""))
else:
assert isinstance(macro, tuple)
ret_macros.append(mac... |
def _bbox_around_polycoords(coords):
"""
bounding box
"""
x_all = []
y_all = []
for first in coords[0]:
x_all.append(first[1])
y_all.append(first[0])
return [min(x_all), min(y_all), max(x_all), max(y_all)] |
def get_back_calls(edges, layers):
"""Detect back calls"""
b_calls = []
for u, v in edges:
if layers[u] < layers[v]:
b_calls.append((u, v))
return b_calls |
def x(k):
"""Numerically investigate the continued fraction x =
1 + 1
________________
1 + 1
__________
1 + 1
_____
...
We won't be able to go out to infinity, so we'll use a counter to take only
a... |
def del_none(dictionary):
"""
Recursively delete from the dictionary all entries which values are None.
This function changes the input parameter in place.
:param dictionary: input dictionary
:type dictionary: dict
:return: output dictionary
:rtype: dict
"""
for key, value in list(... |
def p(pwp):
"""Calculates XP cost for the prior work penalty (pwp)"""
#https://minecraft.gamepedia.com/Anvil/Mechanics#Prior_work_penalty
return pow(2, pwp)-1 |
def cc(g):
"""
>>> graph = [[1, 4], [0], [3, 6, 7], [2, 7], [0, 8, 9], [], [2, 10], \
[2, 3, 10, 11], [4, 9], [4, 8], [6, 7, 11], [10, 7]]
>>> cc(graph)
3
"""
def dfs(g, t, seen):
for v in g[t]:
if v not in seen:
seen.add(v)
df... |
def _filename_dataset(dataset, market=None, variant=None, extension=None):
"""
Compose the filename for a dataset given its name, variant, market,
and filename extension.
:param dataset: String with dataset name e.g. 'income'.
:param market: Optional string with dataset market e.g. 'usa'.
:para... |
def unpack_string(byte_stream):
"""Return decoded ASCII string from bytestring.
Decode a bytes object via UTF-8 into a string
Args:
byte_stream (bytes): arbitrary length
Returns:
string: UTF-8 decoded string
"""
out_string = byte_stream.decode("utf-8", "replace")
return ou... |
def getIterable(dict_or_list):
"""
Returns an iterable given a dictionary of a list.
"""
if isinstance(dict_or_list, dict):
iterable = list(dict_or_list.values())
elif isinstance(dict_or_list, list):
iterable = dict_or_list
else:
raise Exception("Unknown type '" + str(typ... |
def speciesAlive(populations, threshold=0.01):
""" Returns the number of elements in array 'populations' that are larger
than 'threshold'.
Keyword arguments:
populations -- an array of species populations
threshold -- the size a population must be to be considered extant... |
def delete_keys(data):
"""
set data values to None
:param data:
:return:
"""
return {key: None for key in data} |
def check_whether_complete(blocknumbers):
"""
do we have consecutive blocks, none missing?
"""
start = min(blocknumbers)[0]
last = max(blocknumbers)[0]
old = start-1
total=0
for bn in blocknumbers:
bn = bn[0]
missing=bn-old-1
if missing>0:
print ("from... |
def bin_data(signal_list, bins, labels = [], group_sizes = []):
"""
"""
assert all([type(item) == float or type(item) == int for item in signal_list]), "Signal should be provided as a float."
assert type(bins) == int, "The number of groups (bins) should be an integer."
assert type(labels) in [list, ... |
def convert_range_to_list(node_range):
"""
Convert a number range to a list.
Example input: Input can be like one of the format: "1-3", "1-2,6", "2, 8"
Example output: [1, 2, 3]
"""
return sum(
(
(list(range(*[int(j) + k for k, j in enumerate(i.split("-"))])) if "-" in i els... |
def single_value_from_permutable_keys(source_dict, permutable_keys,
default_value=''):
"""Single value from permutable keys."""
example_condition = True
err_msg = 'Multiple permutable keys were found. Please use one.\n\n' \
'Source dictionary: {}\n' \
... |
def dos_list_request_to_indexd(dos_list):
"""
Takes a DOS ListDataObjects request and converts it into a request against
indexd index.
:param gdc:
:return:
"""
mreq = {}
mreq['limit'] = dos_list.get('page_size', None)
mreq['start'] = dos_list.get('page_token', None)
return mreq |
def get_linear_intersection(m1,c1,m2,c2):
"""gets the intersection of 2 straight lines described by y=mx+c"""
x_intersect = (c1-c2)/(m2-m1)
y_intersect = x_intersect*m1+c1
return x_intersect, y_intersect |
def select(value, key):
"""
Select a key from a dictionary.
If ``value`` is not a dictionary or ``key`` does not exist in it,
the ``value`` is returned as is.
"""
return value.get(key, value) if isinstance(value, dict) else value |
def vector_multiply(vector, value):
"""
Args:
vector (list): 3 value list
value (float): value to multiply the vector by
Return:
list: 3 value list
"""
result = [vector[0] * value, vector[1] * value, vector[2] * value]
return result |
def get_tr1(name):
"""
When using libstd++, there is a tr1 namespace.
Note that tr1 was also replaced by std in declarations.py,
for the parent attribute.
Return either an empty string or tr1::, useful for
appending to search patterns.
"""
tr1 = ""
if "tr1" in name:
tr1 =... |
def get_entities(interactions, req_entities):
"""
This method looks for entities in the different interactions.
Args:
:param interactions: A list of all of users last thread
:param req_entities: A list of required entities
"""
entities = []
missing_entities = len(req_e... |
def find_area_perim(array):
"""
Scalar!
"""
a = 0
p = 0
ox, oy = array[0]
for x, y in array[1:]:
a += (x * oy - y * ox)
p += abs((x - ox) + (y - oy) * 1j)
ox, oy = x, y
return a / 2, p |
def skip(*args) -> bool:
"""Things that should be skipped by the autodoc generation."""
name = args[2]
would_skip = args[4]
if name in (
"__weakref__",
):
return True
return would_skip |
def apply_transform(base, transform, num_pos):
"""
:param base: 1-D array to be transformed
:param transform: 1-D transform to apply
"""
return [base[transform[i]] for i in range(num_pos)] |
def exclude(m, keys):
"""
Exclude from the map any items
matching the supplied `keys`
"""
return {k: v for k, v in m.items() if k not in keys} |
def _hasattr(obj, attr):
"""
Looks for attribute in inheritance hierarchy, but excludes metaclass methods
from consideration. Necessary to prevent recursion inside metaclass methods.
"""
try:
return any(attr in ancestor.__dict__ for ancestor in obj.__mro__)
except AttributeError:
... |
def is_same_class(obj, a_class):
""" type(obj) == a_class (True) """
return type(obj) is a_class |
def check_brackets(pathway, levels_brackets):
"""
Function checks is this expression in brackets. Returns without if true
Example: input (A B C)
return: A B C
:param pathway: input string expression
:return: output string expression
"""
L = len(pathway)
if pathway[0] == '(' a... |
def wrap(text, open_tag, close_tag):
"""Wrap the text in tags... or anything really."""
return ''.join((open_tag, text, close_tag, )) |
def tts_ip_address(ip_address):
"""Convert an IP address to something the TTS will pronounce correctly.
Args:
ip_address (str): The IP address, e.g. '102.168.0.102'
Returns:
str: A pronounceable IP address, e.g. '192 dot 168 dot 0 dot 102'
"""
return ip_address.replace('.', ' point... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.