content
stringlengths 42
6.51k
|
---|
def format_duration(duration: float):
"""Formats the duration (milliseconds) to a human readable way.
:param duration: Duration in milliseconds
:return: Duration in HOURS:MINUTES:SECONDS format. Example: 01:05:10
"""
m, s = divmod(duration / 1000, 60)
h, m = divmod(m, 60)
if h:
return "{0}:{1:0>2}:{2:0>2}".format(str(int(h)).zfill(2),
str(int(m)).zfill(2), str(int(s)).zfill(2))
else:
return "{0}:{1:0>2}".format(str(int(m)).zfill(2), str(int(s)).zfill(2))
|
def create_average_data(json_data):
"""
Args:
json_data -- School data in tree structure.
Returns:
dict -- Average of financial data across schools that provided data.
"""
avg = {}
counts = {}
for school in json_data:
for year in json_data[school]:
if year < 2005:
continue
if year not in avg:
avg[year] = json_data[school][year]
counts[year] = {}
for elem in json_data[school][year]:
counts[year][elem] = 1
else:
for elem in json_data[school][year]:
if elem not in avg[year]:
avg[year][elem] = json_data[school][year][elem]
counts[year][elem] = 1
else:
avg[year][elem] += json_data[school][year][elem]
counts[year][elem] += 1
for year in avg:
for elem in avg[year]:
avg[year][elem] = avg[year][elem] / counts[year][elem]
return avg
|
def build_header(src, episode_url):
"""
Build header.
"""
return {'Referer': episode_url}
|
def string_ijk1_for_cell_ijk1(cell_ijk1):
"""Returns a string showing indices for a cell in simulator protocol, from data in simulator protocol."""
return '[{:}, {:}, {:}]'.format(cell_ijk1[0], cell_ijk1[1], cell_ijk1[2])
|
def joint_number(text_list):
"""joint fraction number
Args:
text_list (list): text list.
Returns:
(list): processed text list.
"""
new_list = []
i = 0
while i < len(text_list):
if text_list[i] == '(' and i + 4 < len(text_list) and text_list[i + 4] == ')':
sub = ''.join(text_list[i:i + 5])
new_list.append(sub)
i = i + 5
else:
new_list.append(text_list[i])
i += 1
return new_list
|
def get_barycenter(vector):
"""
this function calculates a barycenter from an array with connections.
:param list vector: vector of connections from an interconnectivity matrix
1 = connection, 0 = no connection.
:return float: barycenter from the connection vector.
"""
weighted_sum, sum = 0, 0
for x in range(len(vector)):
if vector[x]:
weighted_sum += x + 1
sum += 1
if sum == 0:
return -1
else:
return weighted_sum / sum
|
def _cmp(kd1, kd2):
"""
Compare 2 keys
:param kd1: First key
:param kd2: Second key
:return: -1,0,1 depending on whether kd1 is le,eq or gt then kd2
"""
if kd1 == kd2:
return 0
if kd1 < kd2:
return -1
return 1
|
def verify(str1: str, str2: str):
"""
Verify two numeric (0s and 1s) representations of images.
"""
if len(str1) == len(str2):
matches = 0
misses = 0
for char in enumerate(str1):
if str1[char[0]] == str2[char[0]]:
matches += 1
else:
misses += 1
return (matches * 100) / len(str1)
print('Lists with different sizes. Aborting...')
return -1
|
def display(head):
"""."""
res = []
if not head:
return res
curr = head
while curr:
res.append(curr.data)
curr = curr.next
return res
|
def get_file_name_from_url(url: str) -> str:
"""Returns the filename from a given url.
"""
return url.rsplit('/', 1)[1]
|
def _clean_name(net, name):
""" Clear prefix and some suffixes for name """
# prefix = net._prefix
# name = name.replace(prefix, "")
if name.endswith("_fwd_output"):
name = name[:-len("_fwd_output")]
elif name.endswith("_fwd"):
name = name[:-len("_fwd")]
elif name.endswith("_output"):
name = name[:-len("_output")]
return name
|
def bsearch_ins_pos(arr, t, left):
""" Index where we should insert t in sorted arr. If t exists, then
we can return the left (left=True) or right (left=False) side of
the dups range. """
low = 0
high = len(arr) # note search goes 1 higher b/c you might need to insert afterwards
while low < high:
mid = low + (high - low) // 2
if arr[mid] < t:
low = mid + 1
elif arr[mid] > t:
high = mid
else:
if left:
high = mid
else:
low = mid + 1
return low
|
def inherits_from(obj, a_class):
""" Return True if the object is an instance that
inherited from the specified """
return isinstance(obj, a_class) and type(obj) != a_class
|
def MILLISECOND(expression):
"""
Returns the millisecond portion of a date as an integer between 0 and 999.
See https://docs.mongodb.com/manual/reference/operator/aggregation/millisecond/
for more details
:param expression: expression or variable of a Date, a Timestamp, or an ObjectID
:return: Aggregation operator
"""
return {'$millisecond': expression}
|
def boltHeadFinder(head):
"""
"""
_head = str(head).lower()
_head = _head.replace('bolt','')
_head = _head.replace('screw','')
_head = _head.replace('head','')
_head = _head.replace(' ','')
_head = _head.replace('_','')
_head = _head.replace('-','')
_head = _head.strip()
#
_hexagonon = ['hexagonon', 'hex']
_slotted = ['slotted','slottedhex', 'slottedhexagonon','hexslotted', 'hexagononslotted']
_socket = ['socket', 'hexagonsocketcountersunk', 'hexagononsocket', 'hexsocket']
_cheese = ['cheese', 'slottedcheese']
_flat = ['flat']
_pan = ['pan']
_filser = ['filser']
_oval = ['oval']
_special = ['special']
#
if _head in _socket: _type = 'socket'
else: _type = _head
#
return _type
#
|
def _ord(i):
"""Converts a 1-char byte string to int.
This function is used for python2 and python3 compatibility
that can also handle an integer input.
Args:
i: The 1-char byte string to convert to an int.
Returns:
The byte string value as int or i if the input was already an
integer.
"""
if isinstance(i, int):
return i
else:
return ord(i)
|
def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
this function is copied from distutils.util to avoid deprecation waring https://www.python.org/dev/peps/pep-0632/
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
|
def get_next_race_info(next_race_time_events: list, race_id: str) -> list:
"""Enrich start list with next race info."""
startlist = []
# get videre til information - loop and simulate result for pos 1 to 8
for x in range(1, 9):
for template in next_race_time_events:
start_entry = {}
_rank = template["rank"]
if template["timing_point"] == "Template" and _rank.isnumeric():
if int(_rank) == x:
start_entry["race_id"] = race_id
start_entry["starting_position"] = x # type: ignore
if template["next_race"].startswith("Ute"):
start_entry["next_race"] = "Ute"
else:
start_entry[
"next_race"
] = f"{template['next_race']}-{template['next_race_position']}"
startlist.append(start_entry)
return startlist
|
def deep_merge(dict1: dict, dict2: dict) -> dict:
"""Deeply merge dictionary2 and dictionary1 then return a new dictionary
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:
dict1_copy = dict1.copy()
for key in dict2.keys():
if key in dict1.keys() and type(dict1[key]) is dict and type(dict2[key]) is dict:
dict1_copy[key] = deep_merge(dict1[key], dict2[key])
else:
dict1_copy[key] = dict2[key]
return dict1_copy
return dict1
|
def remove(geo, idxs=()):
""" Remove idxs from a geometry
"""
new_geo = tuple(row for i, row in enumerate(geo) if i not in idxs)
return new_geo
|
def listbox_width(items, max_width=30):
"""Calculate the width for a listbox, based on a list of strings and a
maximum width.
listbox_width(["foo", "bar", "asdf"], 10) #=> 4 ("asdf")
listbox_width(["foo", "asdf", "beep boop"], 5) #=> 5 (max_width)
"""
max_item_width = max(map(len, items))
return min(max_width, max_item_width)
|
def is_power_of_2(n: int) -> bool:
"""For a positive integer `n`, returns `True` is `n` is a perfect power of 2, `False` otherwise."""
assert n >= 1
return n & (n - 1) == 0
|
def split_and_number(strips, missing_indices):
"""
Number contiguous elements in an array with the information of the missing
indices.
"""
remapped_strips = []
j = 0
missing_indices.sort()
for i in range(len(strips)):
if j in missing_indices:
while j in missing_indices:
j += 1
remapped_strips.append((j, strips[i]))
j += 1
return remapped_strips
|
def get_color_from_cmap(val, val_min, val_max, cmap):
"""Return color.
Args:
val (float): value to get color for from colormap (mV)
val_min (int): minimum value of voltage for colormap (mV)
val_max (int): minimum value of voltage for colormap (mV)
cmap (matplotlib.colors.Colormap): colormap
Returns:
tuple: tuple of RGBA values indicating a color
"""
if val_min >= val_max:
return "black"
val_range = val_max - val_min
return cmap((min(max(val, val_min), val_max) - val_min) / (val_range))
|
def get_links(page_text):
"""
:param page_text: Page text
:return:
The list of external link of the page
"""
import re
ragex = re.compile(r'\[\[.*?\]\]')
l = ragex.findall(page_text)
return [s[2:-2].split("|")[0] for s in l]
|
def buildParams(jobParams, args):
"""Build the list of parameters that are passed through to the command"""
paramString = ""
if (jobParams is not None):
for param in jobParams:
dash_prefix = '--' if len(param.name) > 1 else '-'
value = args.get(param.name.replace("-", "_"), param.default)
if (param.accepts == "boolean"):
if (value):
paramString += " {dash_prefix}{name}".format(dash_prefix = dash_prefix, name=param.name)
elif (value is not None):
if (param.accepts == "list"):
value = " ".join(map(str, value))
paramString += " {dash_prefix}{name} {value}".format(dash_prefix = dash_prefix, name=param.name, value=value)
return paramString
|
def get_transitions(sequence):
"""
Extracts a list of transitions from a sequence, returning a list of lists containing each transition.
Example
--------
>>> sequence = [1,2,2,1,2,3,2,3,1]
>>> ps.get_transitions(sequence)
[[1, 2], [2, 1], [1, 2], [2, 3], [3, 2], [2, 3], [3, 1]]
"""
transitions = []
for position in range(len(sequence) - 1):
if sequence[position] != sequence[position + 1]:
transitions.append([sequence[position], sequence[position + 1]])
return transitions
|
def insert_row(order:int) -> str:
"""
insert polynomial root data into an SQL database
"""
params = ', '.join(["root{}, iroot{}".format(root, root) for root in range(order)])
inserts = ', '.join(["?, ?" for root in range(order)])
query = "INSERT OR REPLACE INTO polynomials (id, {}) VALUES (?, {})".format(params, inserts)
return query
|
def _get_with_item_indices(exs):
"""Returns a list of indices in case of re-running with-items.
:param exs: List of executions.
:return: a list of numbers.
"""
return sorted(set([ex.runtime_context['with_items_index'] for ex in exs]))
|
def timeout_soft_cmd(cmd, timeout):
"""Same as timeout_cmd buf using SIGTERM on timeout."""
return 'timeout %us stdbuf -o0 -e0 %s' % (timeout, cmd)
|
def find_best_match(path, prefixes):
"""Find the Ingredient that shares the longest prefix with path."""
path_parts = path.split('.')
for p in prefixes:
if len(p) <= len(path_parts) and p == path_parts[:len(p)]:
return '.'.join(p), '.'.join(path_parts[len(p):])
return '', path
|
def get_big_mat_nrows(nrows: int):
"""
Parameters
----------
nrows : int
the number of rows in the matrix
Returns
-------
nrows : int
the number of rows in the matrix
BIGMAT : Input-logical-default=FALSE. BIGMAT is applicable only
when IUNIT < 0. BIGMAT=FALSE selects the format that uses a
string header as described under Remark 1. But, if the
matrix has more than 65535 rows, then BIGMAT will
automatically be set to TRUE regardless of the value
specified.
"""
if nrows < 0: # if less than 0, big
is_big_mat = True
nrows = abs(nrows)
elif nrows > 0:
is_big_mat = False
if nrows > 65535:
is_big_mat = True
nrows = abs(nrows)
else:
raise RuntimeError('unknown BIGMAT. nrows=%s' % nrows)
return is_big_mat, nrows
|
def flatten(l):
"""Flattens a list of lists to the first level.
Given a list containing a mix of scalars and lists,
flattens down to a list of the scalars within the original
list.
Examples
--------
>>> print(flatten([[[0], 1], 2]))
[0, 1, 2]
"""
if not isinstance(l, list):
return [l]
else:
return sum(map(flatten, l), [])
|
def dev_turn_left(dev0):
"""
m07.turn left.....
return none........
"""
try:
dev0.swipe(150, 1000, 850, 1000)
# (150, 1000) -> (850, 1000)
except Exception as e:
print("error at dev_turn_left.")
pass
else:
pass
finally:
return None
|
def encode(request):
"""Encode request (command, *args) to redis bulk bytes.
Note that command is a string defined by redis.
All elements in args should be a string.
"""
assert isinstance(request, tuple)
data = '*%d\r\n' % len(request) + ''.join(['$%d\r\n%s\r\n' % (len(str(x)), x) for x in request])
return data
|
def main(textlines, messagefunc, config):
"""
KlipChop func to to convert text into unique lines
"""
result = list()
count = 0
for line in textlines():
if line not in result:
result.append(line)
count += 1
if config['sort']:
result = sorted(result)
result = '\n'.join(result)
messagefunc(f'{count} unique lines')
return result
|
def formatFreq(value, pos):
""" Format function for Matplotlib formatter. """
inv = 999.
if value:
inv = 1 / value
return "1/%0.2f" % inv
|
def count_list_nodes(taxonomy):
"""
Count list nodes and return sum.
:param taxonomy: taxonomy
:return: int
"""
count = 0
keys = [x for x in list(taxonomy.keys()) if x != "data"]
for i in keys:
if set(taxonomy[i]) == set(list({"data"})):
if i == keys[-1]:
count += 1
return count
else:
count += 1
else:
count += count_list_nodes(taxonomy[i])
return count
|
def find_replace_line_endings(fp_readlines):
"""
special find and replace function
to clean up line endings in the file
from end or starttag characters
"""
clean = []
for line in fp_readlines:
if line.endswith("=<\n"):
line = line.replace("<\n", "lt\n")
clean.append(line)
return "".join(clean)
|
def fatorial(num, show =False):
"""
program com um funcao fatorial, que recebe um numero como parametro e retorna o fatorial
Com um parametro opcional se ele receber True mostra a operacao
"""
print('-=' * 30)
fat = 1
for c in range(num, 0, -1):
if show:
print(c, end='')
if c > 1:
print (f' x ', end='')
else:
print(' = ', end='')
fat *= c
return fat
|
def has_unique_chars(string):
"""
Implement an algorithm to determine if a string has all unique characters.
:param string: string
:return: True/False
"""
if string is None:
return False
if not isinstance(string, str):
return False
return len(set(string)) == len(string)
|
def _add_read_queue_size(input_cmd, queue_size=50000):
"""
only add when mapall option is used and
"-q" and "--reads-queue-size" is not already used.
there is no other long command starting with q either.
:param input_cmd:
:param queue_size:
:return:
"""
if "mapall" not in input_cmd:
return input_cmd
if ("-q" in input_cmd) or ("--reads-queue-size" in input_cmd):
return input_cmd
return input_cmd + "-q %d" % queue_size
|
def getFeatureGeometry(feature):
"""
Return the geometry of a feature
params:
feature -> a feature
"""
return feature["geometry"]
|
def clean_check(name_list, link_list):
"""
This goes and checks that there are not any offsets. Both the name list and the link lists should be the same length
:param name_list:
:param link_list:
:return:
"""
# making sure there are not offsets, if so stop the run
try:
if len(name_list) != len(link_list):
raise ValueError('Length of data retrieved is offset')
except (ValueError):
exit('Length of data retrived is offset')
return name_list, link_list
|
def _prod(iterable):
"""
Product of a list of numbers.
Faster than np.prod for short lists like array shapes.
"""
product = 1
for x in iterable:
product *= x
return product
|
def pad_number(number, padding=3):
"""Add zero padding to number"""
number_string = str(number)
padded_number = number_string.zfill(padding)
return padded_number
|
def _parse_query(query):
"""extract key-value pairs from a url query string
for example
"collection=23&someoption&format=json"
-> {"collection": "23", "someoption": None, "format": "json"}
"""
parts = [p.split("=") for p in query.split("&")]
result = {}
for p in parts:
if len(p) == 2:
result[p[0]] = p[1]
if len(p) == 1:
result[p[0]] = None
return result
|
def find_missing(integers_list, start=None, limit=None):
""" Given a list of integers and optionally a start and an end
finds all integers from start to end that are not in the list
"""
start = start if start is not None else integers_list[0]
limit = limit if limit is not None else integers_list[-1]
return [i for i in range(start, limit + 1) if i not in integers_list]
|
def _format_pos_to_db(pos: list) -> str:
"""
Returns a database-ready string that contains the position in the form x/y
"""
return "{}/{}".format(pos[0], pos[1])
|
def rgb_to_hex(rgb):
"""RGB to HEX conversion"""
return '#%02x%02x%02x' % (rgb[0], rgb[1], rgb[2])
|
def insert_string(original, insertion, index):
"""
Insert a string at the given index of the provided string
:param original: string to be inserted into
:param insertion: string to insert
:param index: index of insertion
:return: initial string with completed insertion
"""
return original[:index+1] + insertion + original[index+1:]
|
def indent(string: str, n=4) -> str:
"""Indent a multi-line string by given number of spaces."""
return "\n".join(" " * n + x for x in str(string).split("\n"))
|
def make_subj(common_name, encrypted=False):
"""
Make a subject string
:param common_name: Common name used in certificate
:param encrypted: Add the encrypted flag to the organisation
:return: A subject string
"""
return "/C=FR/ST=Auvergne-Rhone-Alpes/L=Grenoble/O=iPOPO Tests ({0})" \
"/CN={1}".format("encrypted" if encrypted else "plain", common_name)
|
def pixel_distance(p1, p2):
"""straight 3-d euclidean distance (assume RGB)"""
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 + (p1[2] - p2[2])**2)**0.5
|
def isPointValid(point, validPoints, clearance):
"""
Definition
---
Method to check if point is valid and clear of obstacles
Parameters
---
point : node of intrest
validPoints : list of all valid points
clearance : minimum distance required from obstacles
Returns
---
bool : True if point is valid, False othervise
"""
for i in range(-clearance, clearance):
for j in range(-clearance, clearance):
if not (point[0] + i, point[1] + j) in validPoints:
return False
return True
|
def is_public_method(class_to_check, name):
"""Determine if the specified name is a public method on a class"""
if hasattr(class_to_check, name) and name[0] != '_':
if callable(getattr(class_to_check, name)):
return True
return False
|
def get_number_nation(number) -> str:
"""
Gets the nation of a number.
:param number: The number to get the nation from.
:return: The number's nation.
"""
return "000s" if len(str(number)) <= 2 else f"{str(number)[-3]}00s"
|
def custom_rounder(input_number, p):
"""
Return round of the input number respected to the digit.
:param input_number: number that should be round
:type input_number: float
:param p: 10 powered by number of digits that wanted to be rounded to
:type p: int
:return: rounded number in float
"""
return int(input_number * p + 0.5) / p
|
def julian_century(jd_local):
"""Returns the Julian Century with Julian Day, julian_local."""
days_century = 2451545 # this is Saturday, AD 2000 Jan 1 in the Julian Calendar
day_per_century = 36525
for i in range(2451545, 0, -36525):
if jd_local < i:
days_century = i - day_per_century
else:
break
julian_cent = (jd_local - days_century) / day_per_century
return julian_cent
|
def score(letter):
"""
Returns index of letter in alphabet e.g. A -> 1, B -> 2, ...
"""
string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
return(string.index(letter) + 1)
|
def reverse_dict(original):
"""
Returns a dictionary based on an original dictionary
where previous keys are values and previous values pass
to be the keys
"""
final = {}
for k, value in original.items():
if type(value) == list:
for v in value:
final.setdefault(v, []).append(k)
else:
final.setdefault(value, []).append(k)
return final
|
def _id_remapper(orig, new):
"""Provide a dictionary remapping original read indexes to new indexes.
When re-ordering the header, the individual read identifiers need to be
updated as well.
"""
new_chrom_to_index = {}
for i_n, (chr_n, _) in enumerate(new):
new_chrom_to_index[chr_n] = i_n
remap_indexes = {}
for i_o, (chr_o, _) in enumerate(orig):
if chr_o in new_chrom_to_index.keys():
remap_indexes[i_o] = new_chrom_to_index[chr_o]
remap_indexes[None] = None
return remap_indexes
|
def find_predecessor_row_from_batch(parsed_rows, batch_row_id, predecessor_name):
"""
finds a relevant predecessor row in a batch
"""
batch_rows = filter(
lambda x: x['parent_id'] == batch_row_id,
parsed_rows
)
for row in batch_rows:
if row['name'] == predecessor_name:
return row
return None
|
def _round_pow_2(value):
"""Round value to next power of 2 value - max 16"""
if value > 8:
return 16
elif value > 4:
return 8
elif value > 2:
return 4
return value
|
def get_data_element(item='case'):
"""Method to get data elements other than categories and inteventions."""
results = {}
try:
case, params = {}, {}
case[1] = 'Total Children'
case[2] = 'Total Cases'
case[3] = 'Total Interventions'
case[4] = 'Percentage Interventions'
# dropped out - (90+ days no intervention)
case[5] = 'Dropped Out'
case[6] = 'Pending'
results['case'] = case
if item in results:
params = results[item]
except Exception:
pass
else:
return params
|
def fib(n):
""" Calculates the n-th Fabonacci number iteratively
>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
"""
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
|
def _LookupTargets(names, mapping):
"""Returns a list of the mapping[name] for each value in |names| that is in
|mapping|."""
return [mapping[name] for name in names if name in mapping]
|
def distance(a, b):
"""Returns the case-insensitive Levenshtein edit distance between |a| and |b|.
The Levenshtein distance is a metric for measuring the difference between
two strings. If |a| == |b|, the distance is 0. It is roughly the number
of insertions, deletions, and substitutions needed to convert |a| -> |b|.
This distance is at most the length of the longer string.
This distance is 0 iff the strings are equal.
Examples:
levenshtein_distance("cow", "bow") == 1
levenshtein_distance("cow", "bowl") == 2
levenshtein_distance("cow", "blrp") == 4
See https://en.wikipedia.org/wiki/Levenshtein_distance for more background.
Args:
a: A string
b: A string
Returns:
The Levenshtein distance between the inputs.
"""
a = a.lower()
b = b.lower()
if len(a) == 0:
return len(b)
if len(b) == 0:
return len(a)
# Create 2D array[len(a)+1][len(b)+1]
# | 0 b1 b2 b3 .. bN
# ---+-------------------
# 0 | 0 1 2 3 .. N
# a1 | 1 0 0 0 .. 0
# a2 | 2 0 0 0 .. 0
# a3 | 3 0 0 0 .. 0
# .. | . . . . .. .
# aM | M 0 0 0 .. 0
dist = [[0 for _ in range(len(b)+1)] for _ in range(len(a)+1)]
for i in range(len(a)+1):
dist[i][0] = i
for j in range(len(b)+1):
dist[0][j] = j
# Build up the dist[][] table dynamically. At the end, the Levenshtein
# distance between |a| and |b| will be in the bottom right cell.
for i in range(1, len(a)+1):
for j in range(1, len(b)+1):
cost = 0 if a[i-1] == b[j-1] else 1
dist[i][j] = min(dist[i-1][j] + 1,
dist[i][j-1] + 1,
dist[i-1][j-1] + cost)
return dist[-1][-1]
|
def to_namespace(node, namespace):
"""Return node name as if it's inside the namespace.
Args:
node (str): Node name
namespace (str): Namespace
Returns:
str: The node in the namespace.
"""
namespace_prefix = "|{}:".format(namespace)
node = namespace_prefix.join(node.split("|"))
return node
|
def empty_if_none(_string, _source=None):
"""If _source if None, return an empty string, otherwise return string.
This is useful when you build strings and want it to be empty if you don't have any data.
For example when building a comma-separated string with a dynamic number of parameters:
.. code-block:: python
command = (_id +";" + + empty_if_none(";"+str(_comment), _comment))
"""
if _source is None:
return ""
else:
return str(_string)
|
def model_trapezoidal_pulses(pileup_time, energy1, energy2, cfg):
"""
Models the pileup energy based on a trapezoidal filter. We have 4 scenarios for the pileup.
The final energy depends on when the pileup signal peaks:
1. fully inside the gap of the first signal,
2. between the gap and the rise time of the first signal,
3. fully inside the first signal's peak,
4. or at the end of the first signal's peak.
Depends on the following parameters:
* Filter gap or flat top in seconds
* Filter length or rise time in seconds
* Signal rise time in seconds
:param pileup_time: The time that the pile-up occurred in seconds
:param energy1: The energy of the first signal we had.
:param energy2: The energy of the piled-up signal
:param cfg: The configuration containing all necessary parameters.
:return: The piled up energy
"""
if pileup_time <= cfg['filter']['gap'] - cfg['signal']['rise_time']:
# Second pulse rises fully inside gap
return energy1 + energy2
if cfg['filter']['gap'] - cfg['signal']['rise_time'] < pileup_time <= cfg['filter']['gap']:
# Second pulse rises between gap and filter risetime
x = pileup_time + cfg['signal']['rise_time'] - cfg['filter']['gap']
y = x * energy2 / cfg['signal']['rise_time']
a = x * y / 2
return energy1 + (energy2 * cfg['filter']['length'] - a) / cfg['filter']['length']
if cfg['filter']['gap'] < pileup_time <= cfg['filter']['gap'] + cfg['filter'][
'length'] - cfg['signal']['rise_time']:
# Second pulse rises fully inside the peak
return energy1 + (
cfg['filter']['length'] + cfg['filter']['gap'] - pileup_time - 0.5
* cfg['signal']['rise_time']) * energy2 / cfg['filter']['length']
if cfg['filter']['gap'] + cfg['filter']['length'] - cfg['signal']['rise_time'] < pileup_time <= \
cfg['filter']['gap'] + cfg['filter']['length']:
# Second pulse rises at the end of the peak
x = cfg['filter']['length'] + cfg['filter']['gap'] - pileup_time
y = x * energy2 / cfg['signal']['rise_time']
return energy1 + x * y * 0.5 / cfg['filter']['length']
|
def _board_to_string(board):
"""Returns a string representation of the board."""
return "\n".join("".join(row) for row in board)
|
def find_close_elements(a, b, precision = 0.01):
"""Finds close elements in two arrays with diffrent sizes.
Parameters
----------
a : array of floats with dimention of N
Description of parameter `a`.
b : array of floats with dimention of M
Description of parameter `b`.
precision : threshold withing which two elements are considered the same.
Description of parameter `precision`.
Returns
-------
[array, array]
returns two arrays with the elements that mathched withing the
precision.
"""
return [[x for x in a for i in b if abs(x - i) < precision], [x for x in b for i in a if abs(x - i) < precision]]
|
def common_filters(limit=None, sort_key=None, sort_dir=None, marker=None):
"""Generate common filters for any list request.
:param limit: maximum number of entities to return.
:param sort_key: field to use for sorting.
:param sort_dir: direction of sorting: 'asc' or 'desc'.
:param marker: The last actionplan UUID of the previous page.
:returns: list of string filters.
"""
filters = []
if isinstance(limit, int) and limit > 0:
filters.append('limit=%s' % limit)
if sort_key is not None:
filters.append('sort_key=%s' % sort_key)
if sort_dir is not None:
filters.append('sort_dir=%s' % sort_dir)
if marker is not None:
filters.append('marker=%s' % marker)
return filters
|
def sol_rad_island(et_rad):
"""
Estimate incoming solar (or shortwave) radiation, *Rs* (radiation hitting
a horizontal plane after scattering by the atmosphere) for an island
location.
An island is defined as a land mass with width perpendicular to the
coastline <= 20 km. Use this method only if radiation data from
elsewhere on the island is not available.
**NOTE**: This method is only applicable for low altitudes (0-100 m)
and monthly calculations.
Based on FAO equation 51 in Allen et al (1998).
:param et_rad: Extraterrestrial radiation [MJ m-2 day-1]. Can be
estimated using ``et_rad()``.
:return: Incoming solar (or shortwave) radiation [MJ m-2 day-1].
:rtype: float
"""
return (0.7 * et_rad) - 4.0
|
def strip_code_prompts(rst_string):
"""Removes >>> and ... prompts from code blocks in examples."""
return rst_string.replace('>>> ', '').replace('>>>\n', '\n').replace('\n...', '\n')
|
def colored(str, color="red"):
"""
Color a string for terminal output
@params
str - Required : the string to color
color - Optional : the color to use. Default value: red. Available options: red, yellow, blue
"""
colors = {
"red": "\033[91m",
"yellow": "\33[33m",
"blue": "\33[34m",
"green": "\33[32m"
}
end = "\033[0m"
return f"{colors[color]}{str}{end}"
|
def is_hla(chrom):
"""
check if a chromosome is an HLA
"""
return chrom.startswith("HLA")
|
def clean_dict(dictionary: dict) -> dict:
"""Recursively removes `None` values from `dictionary`
Args:
dictionary (dict): subject dictionary
Returns:
dict: dictionary without None values
"""
for key, value in list(dictionary.items()):
if isinstance(value, dict):
clean_dict(value)
elif value is None:
dictionary.pop(key)
return dictionary
|
def correct_name(name):
"""
Ensures that the name of object used to create paths in file system do not
contain characters that would be handled erroneously (e.g. \ or / that
normally separate file directories).
Parameters
----------
name : str
Name of object (course, file, folder, etc.) to correct
Returns
-------
corrected_name
Corrected name
"""
corrected_name = name.replace(" ", "_")
corrected_name = corrected_name.replace("\\", "_")
corrected_name = corrected_name.replace("/", "_")
corrected_name = corrected_name.replace(":", "_")
return corrected_name
|
def flavor_id(request):
"""Flavor id of the flavor to test."""
return request.param if hasattr(request, 'param') else None
|
def _string_contains(arg, substr):
"""
Determine if indicated string is exactly contained in the calling string.
Parameters
----------
substr : str or ibis.expr.types.StringValue
Returns
-------
contains : ibis.expr.types.BooleanValue
"""
return arg.find(substr) >= 0
|
def is_model(obj):
"""
Returns True if the obj is a Django model
"""
if not hasattr(obj, '_meta'):
return False
if not hasattr(obj._meta, 'db_table'):
return False
return True
|
def flatten_seq(seq):
"""convert a sequence of embedded sequences into a plain list"""
result = []
vals = seq.values() if type(seq) == dict else seq
for i in vals:
if type(i) in (dict, list):
result.extend(flatten_seq(i))
else:
result.append(i)
return result
|
def product(iterable, init=None):
"""
product(iterable) is a product of all elements in iterable. If
init is given, the multiplication starts with init instead of the
first element in iterable. If the iterable is empty, then init or
1 will be returned.
If iterable is an iterator, it will be exhausted.
"""
iterator = iter(iterable)
if init is None:
try:
result = next(iterator)
except StopIteration:
return 1 # empty product
else:
result = init
for item in iterator:
result *= item
return result
|
def no_replace(f):
"""
Method decorator to indicate that a method definition shall
silently be ignored if it already exists in the target class.
"""
f.__no_replace = True
return f
|
def has_prefix(sub_s, current_dict):
"""
:param sub_s: string, part of the input word
:param current_dict: list, save words in the dictionary beginning with the entered letters
:return: boolean
"""
cnt = 0
for w in current_dict:
if w.startswith(sub_s):
cnt += 1
# cnt > 0 means sub_s is a prefix of some words in the dictionary
return cnt > 0
|
def is_account_in_invalid_state(ou_id, config):
"""
Check if Account is sitting in the root
of the Organization or in Protected OU
"""
if ou_id.startswith('r-'):
return "Is in the Root of the Organization, it will be skipped."
protected = config.get('protected', [])
if ou_id in protected:
return "Is in a protected Organizational Unit {0}, it will be skipped.".format(
ou_id)
return False
|
def _link2dict(l):
"""
Converts the GitHub Link header to a dict:
Example::
>>> link2dict('<https://api.github.com/repos/sympy/sympy/pulls?page=2&state=closed>; rel="next", <https://api.github.com/repos/sympy/sympy/pulls?page=21&state=closed>; rel="last"')
{'last': 'https://api.github.com/repos/sympy/sympy/pulls?page=21&state=closed', 'next': 'https://api.github.com/repos/sympy/sympy/pulls?page=2&state=closed'}
"""
d = {}
while True:
i = l.find(";")
assert i != -1
assert l[0] == "<"
url = l[1:i - 1]
assert l[i - 1] == ">"
assert l[i + 1:i + 7] == ' rel="'
j = l.find('"', i + 7)
assert j != -1
param = l[i + 7:j]
d[param] = url
if len(l) == j + 1:
break
assert l[j + 1] == ","
j += 2
l = l[j + 1:]
return d
|
def lr_mark(line, lmark, rmark):
""" read a string segment from line, which is enclosed between l&rmark
e.g. extract the contents in parenteses
Args:
line (str): text line
lmark (str): left marker, e.g. '('
rmark (str): right marker, e.g. ')'
Return:
str: text in between left and right markers
"""
lidx = line.find(lmark)
assert lidx != -1
ridx = line.find(rmark)
assert ridx != -1
return line[lidx+1:ridx]
|
def _round_channels(channels, multiplier=1.0, divisor=8, channel_min=None):
"""Round number of filters based on depth multiplier."""
if not multiplier:
return channels
channels *= multiplier
channel_min = channel_min or divisor
new_channels = max(
int(channels + divisor / 2) // divisor * divisor,
channel_min)
if new_channels < 0.9 * channels:
new_channels += divisor
return new_channels
|
def get_current_stream_name(logger, zulip_stream_names, stream_id):
"""
Check all Zulip streams and get a name for the current stream.
Raise ValueError if it is impossible to narrow down stream names.
:param logger: Logger object
:param zulip_stream_names: List of Zulip stream names
:param stream_id: ID of the stream (default name)
:return: Name of the current stream
"""
name = stream_id
if stream_id not in zulip_stream_names:
names_with_id = [x for x in zulip_stream_names if x.startswith(stream_id)]
logger.debug('Stream names with id: %s', names_with_id)
if not names_with_id:
pass
elif len(names_with_id) == 1:
name = names_with_id[0]
elif len(names_with_id) > 1:
names_with_id_and_space = [x for x in names_with_id if x.startswith(stream_id + ' ')]
logger.debug('names_with_id_and_space: %s', names_with_id_and_space)
if len(names_with_id_and_space) == 1:
name = names_with_id_and_space[0]
else:
logger.error('Several streams starting with: %s', stream_id)
logger.error('Without space: %s', names_with_id)
logger.error('With space: %s', names_with_id_and_space)
raise ValueError
return name
|
def _sign(num):
"""Defines the sign for the multiplication"""
if not num:
return 0
return 1 if num > 0 else -1
|
def validate_limit_amount(amount):
"""Validate limit amount value."""
errors = []
if not isinstance(amount, float) and not isinstance(amount, int):
errors.append("Amount must be float or integer type.")
return errors
if amount <= 0:
errors.append("Amount must be positive value.")
return errors
|
def determine_issue_category(issue_type, issue_types):
"""Determine the category of an issue."""
category = None
for issue in issue_types:
issue_id = issue["@Id"]
if issue_id == issue_type:
category = issue["@Category"]
break
return category
|
def attsiz(att: str) -> int:
"""
Helper function to return attribute size in bytes.
:param str: attribute type e.g. 'U002'
:return: size of attribute in bytes
:rtype: int
"""
return int(att[1:4])
|
def get_test_values(alignments):
"""
@type alignments: C{dict}
@param alignments:
@return:
@rtype: C{list}
"""
test_values = []
for hard_regions_index in alignments.keys():
soft_regions_list = []
for soft_regions_index in alignments[hard_regions_index].keys():
soft_regions_list.extend(alignments[hard_regions_index][soft_regions_index].alignment_mappings)
soft_regions_list.reverse()
test_values.extend(soft_regions_list)
return test_values
|
def github_disable_dismiss_stale_pull_request_approvals(rec):
"""
author: @mimeframe
description: Setting 'Dismiss stale pull request approvals when new commits are pushed'
was disabled. As a result, commits occurring after approval will not
require approval.
repro_steps: (a) Visit /<org>/<repo>/settings/branches/<branch>
(b) Uncheck 'Dismiss stale pull request approvals when new commits are pushed'
(c) Click 'Save Changes'
reference: https://help.github.com/articles/configuring-protected-branches/
"""
return rec['action'] == 'protected_branch.dismiss_stale_reviews'
|
def _sanatize_user_answer(answer):
""" replace chars that shouldn't be in the answer """
#The user may have forgotten to enter a 0
if answer[0] == ".":
answer = "0" + answer
#values such as / , and - will not work so replace them
try:
return answer.replace("/",".").replace(",",".").replace("-","")
except Exception:
#then we have no idea what the user intended to write down
return -2
|
def _convert_from_bcd(bcd):
""" Converts a bcd value to a decimal value
:param value: The value to unpack from bcd
:returns: The number in decimal form
"""
place, decimal = 1, 0
while bcd > 0:
nibble = bcd & 0xf
decimal += nibble * place
bcd >>= 4
place *= 10
return decimal
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.