content stringlengths 42 6.51k |
|---|
def gcd_fast(a: int, b: int) -> tuple:
"""
GCD using Euler's Extended Algorithm generalized for all integers of the
set Z. Including negative values.
:param a: The first number.
:param b: The second number.
:return: gcd,x,y. Where x and y are bezout's coeffecients.
"""
gcd=0
x=0
y=0
x=0
"""
if a < 0:
sign_x=-1
else:
sign_x=1
if b < 0:
sign_y=-1
else:
sign_y=1
"""
#if a or b is zero return the other value and the coeffecient's accordingly.
if a==0:
return b, 0, 1
elif b==0:
return a, 0, 1
#otherwise actually perform the calculation.
else:
#set the gcd x and y according to the outputs of the function.
# a is b (mod) a. b is just a.
gcd, x, y = gcd_fast(b % a, a)
#we're returning the gcd, x equals y - floor(b/a) * x
# y is thus x.
return gcd, y - (b // a) * x, x |
def first_half(dayinput):
"""
first half solver:
"""
lines = dayinput.split('\n')
registers = {}
max_max = 0
for line in lines:
register = line.split(' ')[0]
amount = int(line.split(' ')[2])
if register not in registers:
registers[register] = 0
equation = line.split(' if ')
left, cond, right = equation[1].split(' ')
if left not in registers:
registers[left] = 0
left, right = registers[left], int(right)
execute = {
'==': left == right,
'!=': left != right,
'>': left > right,
'<': left < right,
'>=': left >= right,
'<=': left <= right
}
if execute[cond]:
if 'inc' in line:
registers[register] += amount
elif 'dec' in line:
registers[register] -= amount
if registers[register] > max_max:
max_max = registers[register]
return [max([x for x in registers.values()]), max_max] |
def config_tag(iteration=1):
# type: (int) -> str
"""Marks this field as a value that should be saved and loaded at config
Args:
iteration: All iterations are sorted in increasing order and done in
batches of the same iteration number
"""
tag = "config:%d" % iteration
return tag |
def unix_epoch(epoch):
"""Converts embedded epoch since 2000-01-01 00:00:00
to unix epoch since 1970-01-01 00:00:00
"""
return str(946684800 + epoch) |
def endSwap(b):
""" change endianess of bytes """
if type(b) is bytes:
return bytes(reversed(b))
elif type(b) is bytearray:
return bytearray(reversed(b))
else:
assert False,"Type must be byte or bytearray!" |
def get_ship_name(internal_name):
"""
Get the display name of a ship from its internal API name
:param internal_name: the internal name of the ship
:return: the display name of the ship, or None if not found
"""
internal_names = {
"adder": "Adder",
"alliance-challenger": "Alliance Challenger",
"alliance-chieftain": "Alliance Chieftain",
"alliance-crusader": "Alliance Crusader",
"anaconda": "Anaconda",
"asp-explorer": "Asp Explorer",
"asp-scout": "Asp Scout",
"beluga-liner": "Beluga Liner",
"cobra-mk-iii": "Cobra MkIII",
"cobra-mk-iv": "Cobra MkIV",
"diamondback-explorer": "Diamondback Explorer",
"diamondback-scout": "Diamondback Scout",
"dolphin": "Dolphin",
"eagle": "Eagle",
"federal-assault-ship": "Federal Assault Ship",
"federal-corvette": "Federal Corvette",
"federal-dropship": "Federal Dropship",
"federal-gunship": "Federal Gunship",
"fer-de-lance": "Fer-de-Lance",
"hauler": "Hauler",
"imperial-clipper": "Imperial Clipper",
"imperial-courier": "Imperial Courier",
"imperial-cutter": "Imperial Cutter",
"imperial-eagle": "Imperial Eagle",
"keelback": "Keelback",
"krait-mk-ii": "Krait MkII",
"krait-phantom": "Krait Phantom",
"mamba": "Mamba",
"orca": "Orca",
"python": "Python",
"sidewinder": "Sidewinder",
"type-6": "Type-6 Transporter",
"type-7": "Type-7 Transporter",
"type-9": "Type-9 Heavy",
"type-10": "Type-10 Defender",
"viper-mk-iii": "Viper MkIII",
"viper-mk-iv": "Viper MkIV",
"vulture": "Vulture",
}
if internal_name in internal_names:
return internal_names[internal_name]
return None |
def cdb_hash(buf):
"""CDB hash function"""
h = 5381 # cdb hash start
for c in buf:
h = (h + (h << 5)) & 0xFFFFFFFF
h ^= c
return h |
def _filter_size_out(n_prev, filter_size, stride, padding):
"""Calculates the output size for a filter."""
return ((n_prev + 2 * padding - filter_size) // stride) + 1 |
def make_sql_jinja2_filename(file_name: str) -> str:
""" Add .sql.jinja2 to a filename.
:param file_name: the filename without an extension.
:return: the filename.
"""
return f'{file_name}.sql.jinja2' |
def createPacketReport(packet_list):
"""
Takes as input a packet a list.
Returns a dict containing a dict with the packet
summary and the raw packet.
"""
report = []
for packet in packet_list:
report.append({'raw_packet': str(packet),
'summary': str(packet.summary())})
return report |
def to_str(obj):
"""
Turn the given object into a string.
If the obj is None the result will be an empty string.
@return a string representation of obj. If obj is None the string is empty.
"""
if obj is None:
return ""
return str(obj) |
def format_keys(d, format_string):
"""
Creates a new dict with all keys from an original dict reformatted/mapped.
:param d: a dict.
:param format_string: a normal python format string (i.e. str().format() style).
:return: a new dict (of the same type as the original) containing the original dict's values,
but with each key reformatted (as a string).
>>> format_keys({'a': 1, 'b': 2}, '#{}:')
{'#b:': 2, '#a:': 1}
>>> format_keys(OrderedDict([('a', 1), ('z', 26)]), 'K={}.')
OrderedDict([('K=a.', 1), ('K=z.', 26)])
"""
dict_type = type(d)
d = dict_type([(format_string.format(k), v) for k, v in d.items()])
return d |
def ngrams(w_input, n):
"""
Generate a set of n-grams for more complex features
"""
output = []
for i in range(len(w_input) - n + 1):
output.append(w_input[i: i + n])
return [''.join(x) for x in output] |
def fix_ext_py(filename):
"""Given a .pyc filename converts it to the appropriate .py"""
if filename.endswith('.pyc'):
filename = filename[:-1]
return filename |
def manage_data_button(mission_id, testcase_id, number_of_attachments, as_button=False):
""" Returns the text that should be displayed regarding attachments to a test case. """
return {
'mission_id': mission_id,
'test_detail_id': testcase_id,
'supporting_data_count': number_of_attachments,
'as_button': as_button
} |
def get_label(char):
"""Change character to a number between 0 and 25.
A = 0
B = 1
...
Y = 24
Z = 25"""
value = ord(char) - 65
return value |
def formulas_to_string(formulas):
"""Convert formulas to string.
Takes an iterable of compiler sentence objects and returns a
string representing that iterable, which the compiler will parse
into the original iterable.
"""
if formulas is None:
return "None"
return " ".join([str(formula) for formula in formulas]) |
def isNull(s):
""" Checks to see if this is a JSON null object """
if s == 'null':
return True
else:
return False |
def is_variant(call):
"""Check if a variant position qualifies as a variant
0,1,2,3==HOM_REF, HET, UNKNOWN, HOM_ALT"""
if call == 1 or call == 3:
return True
else:
return False |
def get_or_default(arr, index, default_value=None):
"""
Get value at index from list. Return default value if index out of bound
:type arr: list
:param arr: List to get value from
:type index: int
:param index: Index to get value for
:type default_value: Any
:param default_value: Default value
:rtype: Any
:return: Value to get
"""
return arr[index] if len(arr) > index else default_value |
def constr_container_process_head(xml_str, container, operation):
"""construct the container update string process """
xml_str += "<" + container + "s>\r\n"
xml_str += "<" + container + " xc:operation=\"" + operation + "\">\r\n"
return xml_str |
def arrangements(n, max_jump=3):
""" Calculate the number of permutations of N
contiguous numbers, where the max jump is the maximum
difference for a valid permutation.
"""
current = [0]
perms = 0
end = n-1
while len(current) != 0:
new = []
for c in current:
if c == end:
perms += 1
continue
for i in range(1,max_jump+1):
if c + i > n:
break
new.append(c + i)
current = new
return perms |
def get_cluster_sizes(clusters):
"""
Calculates all the sizes of a clusters list and returns it in a tuple in which
the first element is the total number of elements, and the second a list containing
the size of each cluster (maintaining the ordering).
"""
total_elements = 0
cluster_sizes = []
for c in clusters:
size = c.get_size()
total_elements = total_elements + size
cluster_sizes.append(size)
return total_elements,cluster_sizes |
def session(context_name="session", request=None, **kwargs):
"""Returns the session associated with the current request"""
return request and request.context.get(context_name, None) |
def get_toc_parameter_dict(definitions):
""" Process the uframe toc['parameter_definitions'] list into a list of dict keyed by pdId. Return dict and pdids.
"""
result = {}
pdids = []
if not definitions:
return {}
for definition in definitions:
pdid = definition['pdId']
if pdid:
if pdid not in pdids:
definition['particleKey'] = definition['particle_key']
del definition['particle_key']
pdids.append(pdid)
result[pdid] = definition
return result, pdids |
def time_float_to_text(time_float):
"""Convert tramscript time from float to text format."""
hours = int(time_float/3600)
time_float %= 3600
minutes = int(time_float/60)
seconds = time_float % 60
return f'{hours}:{minutes:02d}:{seconds:05.2f}' |
def change_ext(file, ext) :
"""
altera a extensao do arquivo file para ext
"""
return file[0:len(file)-4] + '.' + ext |
def indg(x):
"""Return numbers with digit grouping as per Indian system."""
x = str(int(x))
result = x[-3:]
i = len(x) - 3
while i > 0:
i -= 2
j = i + 2
if i < 0: i = 0
result = x[i:j] + ',' + result
return result |
def parse_date(git_line: str) -> str:
"""
Return the author/committer date from git show output
>>> parse_date('AuthorDate: Thu Jun 6 14:31:55 2019 +0300')
'Thu Jun 6 14:31:55 2019 +0300'
"""
date = git_line.split(":", 1)[1].strip()
return date |
def generate_hash(tmpstr):
"""Generate hash."""
hash_val = 1
if tmpstr:
hash_val = 0
# pylint: disable=W0141
for ordinal in map(ord, tmpstr[::-1]):
hash_val = (
(hash_val << 6) & 0xfffffff) + ordinal + (ordinal << 14)
left_most_7 = hash_val & 0xfe00000
if left_most_7 != 0:
hash_val ^= left_most_7 >> 21
return hash_val |
def count_combination(visit_to_fid_to_sequence_type_to_filename, nb_augmented_images):
"""
Description: Counts the number of combinations for the T2, DWI and ADC images of a specific patient.
Params:
- visit_to_fid_to_sequence_type_to_filename: dictionary {'visit': {'fid': {'t2': [filenames], 'dwi': [filenames], 'adc': [filenames]}}}
- nb_augmented_images: number of augmented images
Returns:
- number of combinations for a specific patient (int)
"""
# Count the number of saved images
nb_saved = 0
for visit, fid_to_sequence_type_to_filename in visit_to_fid_to_sequence_type_to_filename.items():
for fid, sequences_to_filenames in fid_to_sequence_type_to_filename.items():
for t2_file_name in sequences_to_filenames['t2']:
for dwi_file_name in sequences_to_filenames['dwi']:
for adc_file_name in sequences_to_filenames['adc']:
for augmented_index in range(nb_augmented_images):
nb_saved += 1
print(nb_saved)
return nb_saved |
def _prepare_shape_for_expand_dims(shape, axes):
"""
Creates the expanded new shape based on the shape and given axes
Args:
shape (tuple): the shape of the tensor
axes Union(int, tuple(int), list(int)): the axes with dimensions expanded.
Returns:
new_shape(tuple): the shape with dimensions expanded.
"""
new_shape = []
shape_idx = 0
new_shape_length = len(shape)
# Convert to set
if isinstance(axes, int):
new_shape_length += 1
if axes >= new_shape_length or axes < -new_shape_length:
raise ValueError(f"axis {axes} is out of bounds for tensor of dimension {new_shape_length}")
axes = {axes}
elif isinstance(axes, (list, tuple)):
new_shape_length += len(axes)
for axis in axes:
if axis >= new_shape_length or axis < -new_shape_length:
raise ValueError(f"axis {axis} is out of bounds for tensor of dimension {new_shape_length}")
axes = set(axes)
else:
raise TypeError(f"only int, tuple and list are allowed for axes, but got {type(axes)}")
for new_shape_idx in range(new_shape_length):
if new_shape_idx in axes or new_shape_idx - new_shape_length in axes:
new_shape.append(1)
else:
new_shape.append(shape[shape_idx])
shape_idx += 1
return tuple(new_shape) |
def alexnet_params(model_name):
""" Map AlexNet model name to parameter coefficients. """
params_dict = {
# Coefficients: dropout, res
"alexnet": (0.2, 224),
}
return params_dict[model_name] |
def add(x, y, **kwargs):
"""add"""
print(kwargs)
return x + y |
def naivemult(x, y, base=10):
""" Function to multiply 2 numbers using the grade school algorithm."""
if len(str(x)) == 1 or len(str(y)) == 1:
return x*y
else:
n = max(len(str(x)),len(str(y)))
# that's suboptimal, and ugly, but it's quick to write
nby2 = n // 2
# split x in b + 10^{n/2} a, with a and b of sizes at most n/2
a = x // base**(nby2)
b = x % base**(nby2)
# split y in d + 10^{n/2} a, with c and d of sizes at most n/2
c = y // base**(nby2)
d = y % base**(nby2)
# we make 3 calls to entries which are 2 times smaller
ac = naivemult(a, c)
ad = naivemult(a, d)
bd = naivemult(b, d)
bc = naivemult(b, c)
# x y = (b + 10^{n/2} a) (d + 10^{n/2} c)
# ==> x y = bd + 10^{n/2} (b c + a d) + 10^{n} (a c)
# this little trick, writing n as 2*nby2 takes care of both even and odd n
prod = ac * base**(2*nby2) + ((ad + bc) * base**nby2) + bd
return prod |
def class_import_string(o):
"""Returns a fully qualified import path of an object class."""
return f'{o.__class__.__module__}.{o.__class__.__qualname__}' |
def make_list(obj):
"""
:param it:
:return: empty list if obj is None, a singleton list of obj is not a list, else obj
"""
if obj is None:
return []
return obj if isinstance(obj, list) else [obj] |
def capitalize_by_mapping(string: str) -> str:
"""
Capitalizes a string by mapping between a set of lowercase
characters and a set of uppercase characters.
:param string: an input string
:return: the capitalized string
"""
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
character = string[0]
i = lowercase.find(character)
return string if i == -1 else uppercase[i] + string[1:] |
def _longest_line_length(text):
"""Return the longest line in the given text."""
max_line_length = 0
for line in text.splitlines():
if len(line) > max_line_length:
max_line_length = len(line)
return max_line_length |
def _get_entities(run, **kwargs):
""" Get BIDS-entities from run object """
valid = ['number', 'session', 'subject', 'acquisition', 'task_name']
entities = {
r: v
for r, v in run.items()
if r in valid and v is not None
}
if 'number' in entities:
entities['run'] = entities.pop('number')
if 'task_name' in entities:
entities['task'] = entities.pop('task_name')
entities = {**entities, **kwargs}
return entities |
def side_of_line(l, p):
"""Returns on which side of line `l` point `p` lies.
Line `l` must be a tuple of two tuples, which are the start and end
point of the line. Point `p` is a single tuple.
Returned value is negative, 0, or positive when the point is right,
collinear, or left from the line, respectively. If the line is horizontal,
then the returned value is positive.
Source: http://stackoverflow.com/a/3461533/466781
"""
a,b = l
return ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])) |
def format_duration_ms(ms):
"""Format milliseconds (int) to a human-readable string."""
def _format(d):
d = str(d)
if len(d) == 1:
d = '0' + d
return d
s = int(ms / 1000)
if s < 60:
return '00:{}'.format(_format(s))
m, s = divmod(s, 60)
return '{}:{}'.format(_format(m), _format(s)) |
def items_string(items_list):
"""Convert a list of Id, number pairs into a string representation.
items_string(list((str, int))) -> str
"""
result = []
for itemid, num in items_list:
result.append("{0}:{1}".format(itemid, num))
return ','.join(result) |
def parse_extension(extension):
"""Parse a single extension in to an extension token and a dict
of options.
"""
# Naive http header parser, works for current extensions
tokens = [token.strip() for token in extension.split(';')]
extension_token = tokens[0]
options = {}
for token in tokens[1:]:
key, sep, value = token.partition('=')
value = value.strip().strip('"')
options[key.strip()] = value
return extension_token, options |
def bresenham_line(x, y, x2, y2):
"""Brensenham line algorithm"""
steep = 0
coords = []
dx = abs(x2 - x)
if (x2 - x) > 0: sx = 1
else: sx = -1
dy = abs(y2 - y)
if (y2 - y) > 0: sy = 1
else: sy = -1
if dy > dx:
steep = 1
x,y = y,x
dx,dy = dy,dx
sx,sy = sy,sx
d = (2 * dy) - dx
for i in range(0,dx):
if steep: coords.append((y,x))
else: coords.append((x,y))
while d >= 0:
y = y + sy
d = d - (2 * dx)
x = x + sx
d = d + (2 * dy)
coords.append((x2,y2))
return coords |
def duplicar(valores):
"""duplica os valores em uma lista
>>> duplicar([1, 2, 3, 4])
[2, 4, 6, 8]
>>> duplicar([])
[]
>>> duplicar('a', 'b', 'c')
['aa', 'bb', 'cc']
>>> duplicar([True, None])
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
"""
return [2 * elemento for elemento in valores] |
def _match_authorizables(base_authorizables, authorizables):
"""
Method to check if authorizables (entity in CDAP) is contained (the children) of base_authorizables
If so, base_authorizables should be exactly the same as the leading part of authorizables
:return: bool: True if match else False
"""
return authorizables[:len(base_authorizables)] == base_authorizables |
def add_search_filters(search, filters):
"""This helper method iterates through the filters and adds them
to the search query"""
result_search = search
for filter_name in filters:
if filter_name != 'page' and filter_name != 'sort':
# .keyword is necessary for elastic search filtering
field_name = filter_name + '.keyword'
result_search = result_search\
.filter('terms', **{field_name: filters[filter_name]})
return result_search |
def deep_merge_in(dict1: dict, dict2: dict) -> dict:
"""Deeply merge dictionary2 into dictionary1
Arguments:
dict1 {dict} -- Dictionary female
dict2 {dict} -- Dictionary mail to be added to dict1
Returns:
dict -- Merged dictionary
"""
if type(dict1) is dict and type(dict2) is dict:
for key in dict2.keys():
if key in dict1.keys() and type(dict1[key]) is dict and type(dict2[key]) is dict:
deep_merge_in(dict1[key], dict2[key])
else:
dict1[key] = dict2[key]
return dict1 |
def get_tags_gff(tagline):
"""Extract tags from given tagline in GFF format"""
tags = dict()
for t in tagline.split(';'):
tt = t.split('=')
tags[tt[0]] = tt[1]
return tags |
def is_triangle(sides):
"""
Check to see if this is a triangle
:param sides: list[*int] - the length of the three sides of a triangle?
:return bool - whether it is a triangle or not
>>> is_triangle([1, 2, 3])
True
>>> is_triangle([0, 0, 0])
False
All sides have to be of length > 0
The sum of the lengths of any two sides must be greater
than or equal to the length of the third side.
See https://en.wikipedia.org/wiki/Triangle_inequality
"""
for length in sides:
if length <= 0:
return False
if sides[0] + sides[1] < sides[2]:
return False
if sides[1] + sides[2] < sides[0]:
return False
if sides[0] + sides[2] < sides[1]:
return False
return True |
def validate_params(params):
"""assert that json contains all required params"""
keys = params.keys()
result = True
if not "artist" in keys:
print('An artist must be provided in jobs_jukebox job params')
result = False
if not "genre" in keys:
print('A genre must be provided in jobs_jukebox job params')
result = False
if not "lyrics" in keys:
print('Lyrics must be provided in jobs_jukebox job params')
result = False
if not 'model' in keys:
print('A trained model name must be provided in jobs_jukebox job params')
result = False
if not 'name' in keys:
print('An experiment name must be provided in jobs_jukebox job params')
result = False
if not 'length': # sample length in seconds
print('A sample length in seconds must be provided in jobs_jukebox job params')
result = False
return result |
def _has_relation_and_head(row):
"""Does this token participate in a relation?"""
return row[-1] != "0" and row[-2] != "0" |
def replace_newline(text):
"""Just used for debugging, make sure to not use this elsewhere because it
is dangerous since it turns unicode into non-unicode."""
return str(text).replace("\n", '\\n') |
def add_rowcount_limit(sql, limit=300, delimeter=';'):
""" Sets the rowcount limit.
Can be used in lieue of adding a `TOP` clause for databases
that support it.
Args:
sql (str): The sql statement.
limit (int): The row number limit.
delimiter (str): The sql statement delimeter.
"""
return 'set rowcount {}{} {}'.format(limit, delimeter, sql) |
def get_mismatch_type(a_base, b_base):
"""
For two given nucleotide values (A, T, C, G, and -) representing a mismatch
or indel, return the type of mismatch. For substitutions, return transition
or transversion. Otherwise, return insertion or deletion.
"""
type_string = "".join(sorted((a_base, b_base)))
if type_string in ("AG", "CT"):
return "transition"
elif type_string in ("AC", "AT", "CG", "GT"):
return "transversion"
elif a_base == "-":
return "insertion"
elif b_base == "-":
return "deletion"
else:
raise Exception("Unrecognized mismatch type: %s" % type_string) |
def looks_like_a_license(text):
"""
Check if TEXT is likely to be a license header.
Note that TEXT does not contain initial /final horizontal rules,
but does contain comment markers in each non-empty line.
"""
return 'Copyright' in text |
def ris_defaultValue_get(fieldsTuple):
"""
params: fieldsTuple, ()
return: fieldVaule_dict, {}
"""
#
ris_element = fieldsTuple[0]
if len(fieldsTuple[1]) != 0:
default_value = fieldsTuple[1][0]
else:
default_value = []
fieldValue_dict = {}
fieldValue_dict[ris_element] = default_value
#
return fieldValue_dict |
def importModule(name):
"""
Just a copy/paste of the example my_import function from here:
http://docs.python.org/lib/built-in-funcs.html
"""
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod |
def expand_var(v, env):
""" If v is a variable reference (for example: '$myvar'), replace it using the supplied
env dictionary.
Args:
v: the variable to replace if needed.
env: user supplied dictionary.
Raises:
Exception if v is a variable reference but it is not found in env.
"""
if len(v) == 0:
return v
# Using len() and v[0] instead of startswith makes this Unicode-safe.
if v[0] == '$':
v = v[1:]
if len(v) and v[0] != '$':
if v in env:
v = env[v]
else:
raise Exception('Cannot expand variable $%s' % v)
return v |
def is_tool(name):
"""Check whether `name` is on PATH and marked as executable."""
# from whichcraft import which
from shutil import which
return which(name) is not None |
def get_item(obj, key):
"""
Obtain an item in a dictionary style object.
:param obj: The object to look up the key on.
:param key: The key to lookup.
:return: The contents of the the dictionary lookup.
"""
try:
return obj[key]
except KeyError:
return None |
def moments_get_skew(m):
"""Returns the skew from moments."""
return m['mu11']/m['mu02'] |
def list_public_methods(obj):
"""Returns a list of attribute strings, found in the specified
object, which represent callable attributes"""
return [ member for member in dir(obj) if not member.startswith('_') and hasattr(getattr(obj, member), '__call__')
] |
def revalueOutlier(x,mean,stddev,alpha=0.95):
"""
replace null and outlier with mean
"""
if abs(float(x)-mean)<=1.96*stddev:
return float(x)
else:
return float(mean) |
def get_function_name(f):
"""
Get name for either a function or a functools.partial.
"""
try:
return f.__name__
except AttributeError:
pass
# this works for functools.partial objects
try:
return f.func.__name__
except AttributeError:
pass
return type(f).__name__ |
def make_label(expr, node_type):
"""
Make a graph label to replace named variable values and variable functions.
If it is a variable function (node_type = 'internal'), the label is '<var_func>'.
If it is a variable value (node_type = 'leaf'), the label is:
<var_ev> if the variable name starts with 'e' (event).
<var_en> otherwise (entity).
"""
label = '<var_en>'
if node_type == 'internal':
label = '<var_func>'
else:
if expr.startswith('e'):
label = '<var_ev>'
if expr[0].isupper():
label = '<var_func>'
return label |
def decode_encap_ethernet(value):
"""Decodes encap ethernet value"""
return "ethernet", int(value, 0) |
def qname_to_extended(qname, namespaces):
"""
Maps a QName in prefixed format or a local name to the extended QName format.
Local names are mapped if *namespaces* has a not empty default namespace.
:param qname: a QName in prefixed format or a local name.
:param namespaces: a map from prefixes to namespace URIs.
:return: a QName in extended format or a local name.
"""
try:
if qname[0] == '{' or not namespaces:
return qname
except IndexError:
return qname
try:
prefix, name = qname.split(':', 1)
except ValueError:
if not namespaces.get(''):
return qname
else:
return '{%s}%s' % (namespaces[''], qname)
else:
try:
uri = namespaces[prefix]
except KeyError:
return qname
else:
return u'{%s}%s' % (uri, name) if uri else name |
def filter_point(x, y, xlower, xupper, ylower, yupper):
"""
Used in case we want to filter out contours that aren't in some area.
Returns True if we _should_ ignore the point.
"""
ignore = False
if (x < xlower or x > xupper or y < ylower or y > yupper):
ignore = True
return ignore |
def remove_first_word(text):
"""Given a string, remove what is found before the first space"""
l = text.split(" ", 1)
return l[1] if len(l) > 1 else "" |
def _clean_table_name(table_name):
"""Cleans the table name
"""
return table_name.replace("'","''") |
def progress_bar(progress, size = 20):
"""
Returns an ASCII progress bar.
:param progress: A floating point number between 0 and 1 representing the
progress that has been completed already.
:param size: The width of the bar.
.. code-block:: python
>>> ui.progress_bar(0.5, 10)
'[#### ]'
"""
size -= 2
if size <= 0:
raise ValueError("size not big enough.")
if progress < 0:
return "[" + "?" * size + "]"
else:
progress = min(progress, 1)
done = int(round(size * progress))
return "[" + "#" * done + " " * (size - done) + "]" |
def get_config_option(option_name, options, optional=False):
"""Given option_name, checks if it is in app.config. Raises ValueError if a mandatory option is missing"""
option = options.get(option_name)
if option is None and optional is False:
err = "'{0}' is mandatory and is not set in ~/.resilient/app.config file. You must set this value to run this function".format(option_name)
raise ValueError(err)
else:
return option |
def calculateBBCenter(bb):
"""
**SUMMARY**
Calculates the center of the given bounding box
**PARAMETERS**
bb - Bounding Box represented through 2 points (x1,y1,x2,y2)
**RETURNS**
center - A tuple of two floating points
"""
center = (0.5*(bb[0] + bb[2]),0.5*(bb[1]+bb[3]))
return center |
def _bool(raw_bool):
""" Parse WPS boolean string."""
return raw_bool == "true" |
def is_self(user, other):
"""
Check whether `user` is performing an action on themselves
:param user User: The user to check
:param other User: The other user to check
"""
if other is None:
return True
return user == other |
def string_to_array(str_val, separator):
"""
Args
str_val : string value
separator : string separator
Return
List as splitted string by separator after stripping whitespaces from each element
"""
if not str_val:
return []
res = str_val.split(separator)
return res |
def namify_config(obj, **cfg):
"""
Prepend everything in cfg's keys with obj.name_, and remove entries where
the value is None.
"""
return {obj.name + "_" + k: v for k, v in cfg.items() if v is not None} |
def parse_node_coverage(line):
# S s34 CGTGACT LN:i:7 SN:Z:1 SO:i:122101 SR:i:0 dc:f:0
# "nodeid","nodelen","chromo","pos","rrank",assemb
"""
Parse the gaf alignment
Input: line from gaf alignment
Output: tuple of nodeid, nodelen, start_chromo, start_pos, coverage
"""
line_comp = line.strip().split()
nodeid = line_comp[1]
nodelen = len(line_comp[2])
start_chromo = line_comp[4].split(":")[2]
start_pos = line_comp[5].split(":")[2]
rrank = line_comp[-2].split(":")[2]
coverage = line_comp[-1].split(":")[2]
return nodeid, nodelen, start_chromo, start_pos, rrank, coverage |
def _is_primary(s):
"""Indicates whether a sequence is a part of the primary assembly.
Args:
s (dict): A dictionary of sequence data, e.g. those in assembly['sequences'].
Returns:
bool: True if the sequence is part of the primary assembly, False otherwise.
Examples:
>>> _is_primary({'assembly_unit': 'Primary Assembly'})
True
>>> _is_primary({'assembly_unit': 'Something else entirely'})
False
"""
return s['assembly_unit'] == 'Primary Assembly' |
def get_scenario_number_for_tag(tag):
"""
only for logging in tensorboard - gets scenario name and retrieves the number of the scenario
Arguments:
tag String - string with the scenario name
Return:
int - number of the scenario
"""
scenario_dict = {
"sc1_coop": 1,
"SC02": 2,
"sc4_coop": 4,
"sc7_coop": 7,
"sc8_coop": 8,
"SC10": 10,
}
if tag in scenario_dict:
return True, scenario_dict[tag]
else:
return False, 0 |
def matrix_sum(mat_a: list, mat_b: list):
"""
Compute the sum of two compatible matrices.
"""
n: int = len(mat_a)
if n != len(mat_b):
print("ERROR: cannot add incompatible matrices. Stop.")
return None
results = []
for col in range(n):
column = []
for row in range(n):
column.append(mat_a[col][row] + mat_b[col][row])
results.append(column)
return results |
def wrapper(field, wrap_txt):
"""
Wrap a field in html.
"""
answer = "<%s>" % wrap_txt
answer += field
answer += "</%s>" % wrap_txt
return answer |
def lerp(a: float, b: float, t: float) -> float:
"""
Linearly interpolates (unclamped) between a and b with factor t.
Acts such that `lerp(a, b, 0.0)` returns `a`, and `lerp(a, b, 1.0)` returns `b`.
"""
return (1 - t) * a + t * b |
def _get_ngrams(n, text):
"""Calcualtes n-grams.
Args:
n: which n-grams to calculate
text: An array of tokens
Returns:
A set of n-grams
"""
ngram_set = set()
text_length = len(text)
max_index_ngram_start = text_length - n
for i in range(max_index_ngram_start + 1):
ngram_set.add(tuple(text[i:i + n]))
return ngram_set |
def parse_json_body(data, basekey=None):
"""
Takes nested json object and returns all key names associated with them.
Parameters:
data(json): JSON object that may or may not have nested data structures in it.
Returns:
list: List of dictionaries that are key:value pairs.
"""
results = []
if type(data) == dict:
for key, val in data.items():
if type(val) == int or type(val) == str:
results.append({key:val})
else: # Must be a list or dict
results += parse_json_body(val, basekey=key)
elif type(data) == list:
for item in data:
if type(item) == int or type(item) == str:
results.append({basekey:item})
else:
results += parse_json_body(item, basekey=basekey)
else:
if not basekey:
raise Exception("No base key defined for data {}".format(data))
results.append({basekey:data})
return results |
def convert_bounding_box_to_xyxy(box: dict) -> list:
"""
Converts dictionary representing a bounding box into a list of xy coordinates
Parameters
----------
box: dict
Bounding box in the format {x: x1, y: y1, h: height, w: width}
Returns
-------
bounding_box: dict
List of arrays of coordinates in the format [x1, y1, x2, y2]
"""
x2 = box["x"] + box["width"]
y2 = box["y"] + box["height"]
return [box["x"], box["y"], x2, y2] |
def get_investigation_data(investigation_response):
"""Get investigation raw response and returns the investigation info for context and human readable.
Args:
investigation_response: The investigation raw response
Returns:
dict. Investigation's info
"""
investigation_data = {
"ID": investigation_response.get('id'),
"StartTime": investigation_response.get('startTime'),
"EndTime": investigation_response.get('endTime'),
"InvestigationState": investigation_response.get('state'),
"CancelledBy": investigation_response.get('cancelledBy'),
"StatusDetails": investigation_response.get('statusDetails'),
"MachineID": investigation_response.get('machineId'),
"ComputerDNSName": investigation_response.get('computerDnsName'),
"TriggeringAlertID": investigation_response.get('triggeringAlertId')
}
return investigation_data |
def get_pos_constants(tag: str):
"""
Static function for tag conversion
:param tag: The given pos tag
:return: The corresponding letter
"""
if tag.startswith("J"):
return "a"
elif tag.startswith("V"):
return "v"
elif tag.startswith("N"):
return "n"
elif tag.startswith("R"):
return "r"
else:
return "n" |
def create2D(rowCount, colCount, value=None):
"""
Create and return a 2D array having rowCount rows and colCount
columns, with each element initialized to value.
"""
a = [None] * rowCount
for row in range(rowCount):
a[row] = [value] * colCount
return a |
def format_lines(text):
"""Returns list of list of ints"""
return [[int(i) for i in str.split(line, 'x')] for line in str.split(text)] |
def _BuildForceFieldTrialsSwitchValue(trials):
"""Generates --force-fieldtrials switch value string.
This is the opposite of _ParseForceFieldTrials().
Args:
trials: A list of _Trial objects from which the switch value string
is generated.
"""
return ''.join('%s%s/%s/' % (
'*' if trial.star else '',
trial.trial_name,
trial.group_name
) for trial in trials) |
def to_base36(obj):
"""
Converts an integer to base 36 (a useful scheme for human-sayable IDs).
:param obj: int
:return: str
"""
if obj < 0:
raise ValueError('must supply a positive integer')
alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'
converted = []
while obj != 0:
obj, r = divmod(obj, 36)
converted.insert(0, alphabet[r])
return ''.join(converted) or '0' |
def pre_text(string, lang=None):
"""
Encapsulate a string inside a Markdown <pre> container
"""
s = "```{}```"
if lang is not None:
s = s.format(lang+"\n{}")
return s.format(string.rstrip().strip("\n").replace("\t", "")) |
def py2_replace_version(argv):
"""
Workaround for Python 2.7 argparse, which does not accept empty COMMAND
If `-V` or `--version` present and every argument before it begins with `-`,
then convert it to `version.
"""
try:
ind = argv.index('--version')
except ValueError:
try:
ind = argv.index('-V')
except ValueError:
ind = None
if ind is not None:
for k in range(ind):
if argv[k][0] != '-':
ind = None
break
if ind is not None:
argv[ind] = 'version'
return argv |
def touch(name):
"""Create a file and return its name."""
with open(name, 'w') as f:
return f.name |
def add_prefix(key, prefix):
"""Add prefix to key."""
if prefix:
key = "{}_{}".format(prefix, key)
return key |
def uniq(ls):
"""
uniqify a list
"""
return list(set(ls)) |
def cup_vs_cups(left, right):
""" Simple type error. """
return "Cup can only witness adjunctions between simple types. "\
"Use Diagram.cups({}, {}) instead.".format(left, right) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.