content stringlengths 42 6.51k |
|---|
def getAuthHeaders(token):
"""
Receives a token and returns a header dict
"""
header = {
'authorization': 'Bearer ' + token
}
return header |
def containsAll(s, pat) -> bool:
"""Check whether string `s` contains ALL of the items in `pat`."""
return all(c in s for c in pat) |
def __adjust_rad_for_skip(diam, skip):
"""
If necessary, increase the crop circle diameter (radius) for the chosen
skip value. This is required because the diameter must be divisible by
skip without rest.
Parameters
----------
diam: int
Initial diameter of crop circle (in pixels).
skip: int
The numbers of pixels to skip when evaluating film thickness
information.
Returns
-------
diam: int
Diameter of circle that is divisible by skip without rest.
"""
while diam % skip != 0:
diam += 1
return diam |
def indices(alist,value):
"""
Returns the indices for a given value in a list
"""
ind = [item for item in range(len(alist)) if alist[item] == value]
return ind |
def textonly(tovalidate):
"""Returns T or F depending on whether the input is a single character in A-Z or a-z or an empty string"""
return tovalidate.isalpha() | (tovalidate == '') | (tovalidate == ' ') |
def wordsByLevel(word, charLevels, dictionary):
"""This method takes a word, charLevels and dictionary, and determinate a level that is suitable for the word
based on characters which is word made of, add that word to the dictionary and return the dictionary.
Args:
word (string): Word which length will be measured and will be added into dictionary.
charLevels (list): List of lists, sublists contain characters from specified alphabet.
dictionary (Dictionary): Keys are levels and values are list of words suitable for such level.
Returns:
Dictionary: Returns dictionary where keys are levels and values are list of words suitable for such level.
"""
currentIndex = 1 # cannot be 0 because of slicing below
while currentIndex <= len(charLevels):
subset = [j for i in charLevels[:currentIndex] for j in i]
if all(letter in subset for letter in word):
if dictionary.has_key(currentIndex):
dictionary[currentIndex].append(word)
else:
dictionary[currentIndex] = [word]
break
else:
currentIndex += 1
return dictionary |
def showd(d):
"""Catch key values to string, sorted on keys.
Ignore hard to read items (marked with '_')."""
d = d if isinstance(d,dict) else d.__dict__
return '{'+ ' '.join([':%s %s' % (k,v)
for k,v in
sorted(d.items())
if not "_" in k]) + '}' |
def prepend_domain(link):
"""
Urls are directly combined as given in *args
"""
top_level_domain ='https://www.proff.no'
return top_level_domain + link |
def chunk_document_collection(seq, num):
"""
Helper function to break a collection of N = len(seq) documents
to num batches.
Input:
- seq: list,
a list of documents
- num: int,
number of batches to be broken into. This will usually be
equal to the number of cores available
Output:
- out: list,
a list of lists. Each sublist contains the batch-collection
of documents to be used.
"""
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return out |
def is_close(val, target, delta=1):
"""Return whether the value is near the target value(s).
Parameters
----------
val : number
The value being compared against.
target : number, iterable
If a number, the values are simply evaluated.
If a sequence, each target is compared to ``val``.
If any values of ``target`` are close, the comparison is considered True.
Returns
-------
bool
"""
try:
targets = (value for value in target)
except (AttributeError, TypeError):
targets = [target] # type: ignore
for target in targets:
if target - delta < val < target + delta:
return True
return False |
def or_options(values, initial_value=0):
"""
Combine all given values using binary OR.
"""
options = initial_value
for value in values:
options |= value
return options |
def int2phoneme(int_to_phoneme, int_list):
"""
Converts a list of integers into a list of phonemes according to the given
int-to-phoneme dictionary. If int_to_phoneme is None, then return int_list
as is.
:param int_to_phoneme: a dictionary mapping integers to phonemes
:param int_list: a list of integers to map
:return: a list of phonemes
"""
if int_to_phoneme is None:
return int_list
return [int_to_phoneme.get(i, "KEY_ERROR:" + str(i)) for i in int_list] |
def unite_dicts(*args):
"""Unites the given dicts into a single dict mapping each key to the
latest value it was mapped to in the order the dicts were given.
Parameters
---------
*args : positional arguments, each of type dict
The dicts to unite.
Returns
-------
dict
A dict where each key is mapped to the latest value it was mapped to
in the order the dicts were given
Example:
--------
>>> dict_obj = {'a':2, 'b':1}
>>> dict_obj2 = {'a':8, 'c':5}
>>> united = unite_dicts(dict_obj, dict_obj2)
>>> print(sorted(united.items()))
[('a', 8), ('b', 1), ('c', 5)]
"""
return dict(i for dct in args for i in dct.items()) |
def image_search_args_to_queryset_args(searchDict, source):
"""
Take the image search arguments directly from the visualization search form's
form.cleaned_data, and return the search arguments in a format that can go into
Image.objects.filter().
Only the value1, ... valuen and the year in cleaned_data are processed. label and
page, if present, are ignored and not included in the returned dict.
"""
searchArgs = dict([(k, searchDict[k]) for k in searchDict if searchDict[k] != ''])
querysetArgs = dict()
for k in searchArgs:
if k.startswith('value'):
querysetArgs['metadata__'+k+'__id'] = searchArgs[k]
elif k == 'year':
querysetArgs['metadata__photo_date__'+k] = int(searchArgs[k])
return querysetArgs |
def same_list(l1, l2):
"""
Checks if a list is the same as the other. Order matters.
:param l1: list 1
:param l2: list 2
:return: bool True if the lists are the same, false otherwise.
"""
if l1 == l2:
return True
else:
return False |
def format_email_subject(quote):
"""
This functions formats the subject field of the email to be send to the user as configured in bitstampconfig.py
:param quote: The current quote values to be inserted on the subject of the email
:return: the email subject to be sent with the current quote
"""
return 'Bitstamp Last Quote: {0} USD'.format(quote['last']) |
def collatz_test(n):
"""
If n is even, return (n/2), else return (3n+1).
"""
return((n/2) if n%2==0 else (3*n+1)) |
def update_analyze_button(disabled):
"""
Updates the color of the analyze button depending on
its disabled status
:param disabled: if the button is disabled
"""
if not disabled:
style = {"width": "100%", "text-transform": "uppercase",
"font-weight": "700", "background": "green", "outline": "green"}
else:
style = {"width": "100%", "text-transform": "uppercase",
"font-weight": "700"}
return style |
def invert_dict(d):
"""Returns a new dict with keys as values and values as keys.
Parameters
----------
d : dict
Input dictionary. If one value of the dictionary is a list or a tuple,
each element of the sequence will be considered separately.
Returns
-------
dict
The new dictionary with d keys as values and d values as keys.
In the case of duplicated d values, the value of the resulting key
of the new dictionary will be a list with all the corresponding d keys.
Examples
--------
>>> from secml.utils.dict_utils import invert_dict
>>> a = {'k1': 2, 'k2': 2, 'k3': 1}
>>> print(invert_dict(a))
{1: 'k3', 2: ['k1', 'k2']}
>>> a = {'k1': 2, 'k2': [2,3,1], 'k3': 1}
>>> print(invert_dict(a))
{1: ['k2', 'k3'], 2: ['k1', 'k2'], 3: 'k2'}
"""
def tolist(x): return [x] if not isinstance(x, (list, tuple)) else list(x)
new_d = {}
for k in d.items():
for v in tolist(k[1]):
i = k[0]
if v in new_d:
# If the key has already been set create a list for the values
i = tolist(i)
i = tolist(new_d[v]) + i
new_d[v] = i
return new_d |
def gen_urdf_collision(geom, material, origin):
"""
Generates (as a string) the complete urdf element sequence for a `collision` child
of a `link` element. This is essentially a string concatenation operation.
:param geom: urdf element sequence for the geometry child of a collision element, ``str``
:param material: urdf element sequence for the material child of a collision element, ``str``
:param origin: urdf element sequence for the origin child of a collision element, ``str``
:returns: urdf element sequence for the `collision` child of a `link` element, ``str``
"""
return '<collision>{0}{1}{2}</collision>'.format(geom, material, origin) |
def _infection(state_old, state_new):
"""
Parameters
----------
state_old : dict or pd.Series
Dictionary or pd.Series with the keys "s", "i", and "r".
state_new : dict or pd.Series
Same type requirements as for the `state_old` argument in this function
apply.
Returns
-------
infected : bool
True if the event that occurred between `state_old` and `state_new` was
an infection. False otherwise.
"""
return state_new["s"] == state_old["s"] - 1 and \
state_new["i"] == state_old["i"] + 1 and \
state_new["r"] == state_old["r"] |
def rewrite_elife_funding_awards(json_content, doi):
""" rewrite elife funding awards """
# remove a funding award
if doi == "10.7554/eLife.00801":
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-2":
del json_content[i]
# add funding award recipient
if doi == "10.7554/eLife.04250":
recipients_for_04250 = [
{
"type": "person",
"name": {"preferred": "Eric Jonas", "index": "Jonas, Eric"},
}
]
for i, award in enumerate(json_content):
if "id" in award and award["id"] in ["par-2", "par-3", "par-4"]:
if "recipients" not in award:
json_content[i]["recipients"] = recipients_for_04250
# add funding award recipient
if doi == "10.7554/eLife.06412":
recipients_for_06412 = [
{
"type": "person",
"name": {"preferred": "Adam J Granger", "index": "Granger, Adam J"},
}
]
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-1":
if "recipients" not in award:
json_content[i]["recipients"] = recipients_for_06412
return json_content |
def _is_cell_blank(cell):
"""Is this cell blank i.e. contains nothing or only whitespace"""
return cell is None or (isinstance(cell, str) and not cell.strip()) |
def get_host_finding_status_hr(status):
"""
Prepare human readable json for "risksense-get-host-finding-detail" command.
Including status details.
:param status: status details from response.
:return: list of dict
"""
return [{
'State': status.get('state', ''),
'Current State': status.get('stateName', ''),
'Description': status.get('stateDescription', ''),
'Duration': str(status.get('durationInDays', 0)) + ' day(s)',
'Due Date': status.get('dueDate', ''),
'Resolved On': status.get('expirationDate', '')
}, {}] |
def sol(arr, n, p):
"""
If we have more chocolates than cost we just pay from the balance
otherwise we use all the balance and add the remaining to the total
cost also making bal 0
"""
bal = 0
res = 0
for i in range(n):
d = arr[i-1]-arr[i] if i > 0 else 0-arr[i]
# Careful about comparing with arr[-1] when i=0 !!!
if d > 0:
bal+=d
else:
d = abs(d)
if bal >= d:
bal -= d
else:
res += d-bal
bal = 0
return res*p |
def calulate_loss_of_life(List_V, t):
""" For list of V values, calculate loss of life in hours
t = Time Interval (min)
"""
L = 0
for V in List_V:
L += (V * t) # Sum loss of life in minutes for each interval
LoL = L / 60 # Calculate loss of life in hours
return LoL |
def find_duplicate_auto_mappings(manual_to_auto_map):
"""Finds each auto FOV with more than one manual FOV mapping to it
Args:
manual_to_auto_map (dict):
defines the mapping of manual to auto FOV names
Returns:
list:
contains tuples with elements:
- `str`: the name of the auto FOV
- `tuple`: the set of manual FOVs that map to the auto FOV
only for auto FOVs with more than one manual FOV mapping to it
"""
# "reverse" manual_to_auto_map: for each auto FOV find the list of manual FOVs that map to it
auto_fov_mappings = {}
# good ol' incremental dict building!
for mf in manual_to_auto_map:
closest_auto_fov = manual_to_auto_map[mf]
if closest_auto_fov not in auto_fov_mappings:
auto_fov_mappings[closest_auto_fov] = []
auto_fov_mappings[closest_auto_fov].append(mf)
# only keep the auto FOVs with more than one manual FOV mapping to it
duplicate_auto_fovs = [
(af, tuple(mf_list)) for (af, mf_list) in auto_fov_mappings.items() if len(mf_list) > 1
]
# sort auto FOVs alphabetically
duplicate_auto_fovs = sorted(duplicate_auto_fovs, key=lambda val: val[0])
return duplicate_auto_fovs |
def Dutch_Flag(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
Adapted from https://en.wikipedia.org/wiki/Dutch_national_flag_problem
"""
#Null input
if input_list == None:
return None
#Empty List input
if input_list == []:
return []
i = 0
j = 0
mid = 1
n = len(input_list) - 1
while j <= n:
if input_list[j] < mid:
#swap
temp = input_list[i]
input_list[i] = input_list[j]
input_list[j] = temp
i = i + 1
j = j + 1
elif input_list[j] > mid:
#swap
temp = input_list[j]
input_list[j] = input_list[n]
input_list[n] = temp
n = n - 1
else:
j = j + 1
return input_list |
def line_search_return(line):
"""
get the source/facet in the return statement
"""
l = line.split()
n = l.count("return")
if n == 1:
i = l.index("return")
if len(l) > i + 1: # cause index is zero based
return_obj = l[i + 1]
if "[" in return_obj:
return return_obj.split('[')[0]
else:
return return_obj
else: # if multiple return values, fail
return None |
def get_wrapped(func):
"""Find the wrapped function in a chain of decorators.
This looks for a _wraps attribute on the function, and returns the first
one in the chain that doesn't have that attribute. Note that this requires
decorators to set a _wraps attribute on the wrapper functions they return.
See :func:`~with_wraps` for an easy to to augment existing decorators with
this functionality.
:param callable func: A function, probably created by a decorator.
:returns: callable
"""
while hasattr(func, '_wraps'):
func = func._wraps
return func |
def stripquotes(s):
""" Enforce to be a string and strip matching quotes """
return str(s).lstrip('"').rstrip('"') |
def version_compare(version1, version2):
"""Compare two version iterables consisting of arbitrary number of numeric elements."""
len_version1 = len(version1)
len_version2 = len(version2)
if len_version1 == len_version2:
# Both version objects have the same number of components, compare them left to right
for i in range(len_version1):
if version1[i] > version2[i]: return 1
elif version1[i] < version2[i]: return -1
# version objects compare equal
return 0
elif len_version1 > len_version2:
version2_tmp = list(version2)
while len(version2_tmp) < len_version1: version2_tmp.append(0)
return version_compare(version1, version2_tmp)
else:
version1_tmp = list(version1)
while len(version1_tmp) < len_version2: version1_tmp.append(0)
return version_compare(version1_tmp, version2) |
def x_update(crd, v, a, dt):
"""Currently we only support velocity verlet"""
crd += v*dt + 0.5*a*dt*dt
return crd |
def pointer_length(p):
"""The lowest nybble of the pointer is its length, minus 3."""
return (p & 0xF) + 3 |
def getOutputs(outputs, indexes):
"""
Get n samples of outputs by given indexes
"""
Y = list()
for index in indexes:
Y.append(outputs[index])
return Y |
def ensemble_to_block_rates(model, ensemble_rates):
"""Associates target ensemble firing rates with the correct blocks.
Parameters
----------
model : Model
The model containing the blocks to match.
ensemble_rates : dict
Mapping from a `nengo.Ensemble` to its neurons' target firing rates.
"""
block_rates = {}
for ens, rates in ensemble_rates.items():
if ens not in model.objs:
if ens in model.host_pre.sig or ens in model.host.sig:
continue # this ensemble is not on chip, so skip it
raise ValueError(f"Ensemble {ens} does not appear in the model")
assert len(rates) == ens.n_neurons
blocks = model.objs[ens]["out"]
blocks = blocks if isinstance(blocks, (list, tuple)) else [blocks]
for block in blocks:
comp_idxs = model.block_comp_map.get(block, None)
if comp_idxs is None:
assert len(blocks) == 1
assert block.compartment.n_compartments == ens.n_neurons
block_rates[block] = rates
else:
block_rates[block] = rates[comp_idxs]
return block_rates |
def output_list(str_num):
"""
Outputs a list from a string of numbers that is meant to represent a sudoku game
board. For example, the following...
530070000600195000098000060800060003400803001700020006060000280000419005000080079
will turn into...
[[5 3 0 0 7 0 0 0 0]
[6 0 0 1 9 5 0 0 0]
[0 9 8 0 0 0 0 6 0]
[8 0 0 0 6 0 0 0 3]
[4 0 0 8 0 3 0 0 1]
[7 0 0 0 2 0 0 0 6]
[0 6 0 0 0 0 2 8 0]
[0 0 0 4 1 9 0 0 5]
[0 0 0 0 8 0 0 7 9]]
"""
i = 0
sudoku_list = [[], [], [], [], [], [], [], [], []]
for list in sudoku_list:
for num in str_num[i:i+9]:
if len(list) < 10:
list.append(int(num))
i += 9
return sudoku_list |
def find_idx(list_K_kappa_idx, list_scalar):
"""
Link scalar products with indexes for K and kappa values.
Parameters:
list_K_kappa_idx -- list of lists
list_scalar -- list of integer
Return:
list_scalar -- list of lists
"""
list_idx = [sublist_K_kappa for sublist_K in list_K_kappa_idx for sublist_K_kappa in sublist_K for sublist_sc in list_scalar if (sublist_K_kappa[2] == sublist_sc[0] and (sublist_K_kappa[3] == sublist_sc[1]))]
return list_idx |
def af_to_maf(af):
""" Converts an allele frequency to a minor allele frequency
Args:
af (float or str)
Returns:
float
"""
# Sometimes AF == ".", in these cases, set to 0
try:
af = float(af)
except ValueError:
af = 0.0
if af <= 0.5:
return af
else:
return 1 - af |
def to_ms(microseconds):
"""
Convertes microseconds to milliseconds.
"""
return microseconds / float(1000) |
def is_c_source(s):
"""
Return True if s looks like a C source path.
Example: this.c
FIXME: should get actual algo from contenttype.
"""
return s.endswith(('.c', '.cpp', '.hpp', '.h')) |
def get_direction(source, destination):
"""Find the direction drone needs to move to get from src to dest."""
lat_diff = abs(source[0] - destination[0])
long_diff = abs(source[1] - destination[1])
if lat_diff > long_diff:
if source[0] > destination[0]:
return "S"
else:
return "N"
else:
if source[1] > destination[1]:
return "W"
else:
return "E" |
def lrfact(n):
"""Recursive with lambda functions"""
# In fact, I have no ideas how to count the number of calls of those
# lambda functions.
return (lambda fn: lambda args: fn(fn, args)) \
(lambda f, x: f(f, x - 1) * x if x > 1 else 1) \
(n) |
def func_gravityDistanceCost(x: float, y: float, x_opt: float, y_opt: float, wi: float) -> float:
"""
return cost values with squared euclidean distances
Args:
x (float): X coordinate.
y (float): Y coordinate.
x_opt (float): X coordinate of the optimal location.
y_opt (float): Y coordinate of the optimal location.
wi (float): weight (e.g. flow).
Returns:
float: Cost value.
"""
return ((x - x_opt) ** 2 + (y - y_opt) ** 2) * wi |
def scale_feature(arr):
"""
Rescales all values within array to be in range [0..1]
When all values are identical: assign each new feature to 0.5 (halfway between 0.0 and 1.0)
"""
xmin = min(arr)
xmax = max(arr)
res = []
if xmin == xmax:
res = [.5 for _ in arr]
else:
res = [float((x - xmin)) / (xmax - xmin) for x in arr]
return res |
def read_fasta_file(lines):
"""Read a reference FASTA file. This function is built for many entries in
the FASTA file but we should be loading in one reference at a time for
simplicity's sake. If we need to extract from multiple references then we
should just run the program multiple times instead.
Parameters
----------
lines: list of str
- Output from file.readlines()
Returns
-------
entries: dict
key: Name of the FASTA entry
value: DNA sequence of the FASTA entry
"""
entries = dict()
# Read sequences
cur_entry = ""
cur_seq = ""
for i, line in enumerate(lines):
# Strip whitespace
line = line.strip()
# If not the name of an entry, add this line to the current sequence
# (some FASTA files will have multiple lines per sequence)
if ">" not in line:
# Skip if empty
if not line:
pass
else:
cur_seq = cur_seq + line
# Force to uppercase
_cur_seq = list(cur_seq.upper())
# Throw an error for non canonical bases
# https://www.bioinformatics.org/sms/iupac.html
# for char in _cur_seq:
# if char not in 'ATCGURYSWKMBDHVN':
# error_msg = 'Non canonical base: \"{}\" in sequence {} on line {}.'.format(char, line, i)
# raise Exception(error_msg)
# IUPAC also defines gaps as '-' or '.',
# but the reference shouldn't have gaps.
# Maybe I can add this in later...
# Replace the sequence with the edited one
cur_seq = "".join(_cur_seq)
# Start of another entry = end of the previous entry
if ">" in line or i == (len(lines) - 1):
# Avoid capturing the first one and pushing an empty sequence
if cur_entry:
entries[cur_entry] = cur_seq
# Clear the entry and sequence
cur_entry = line[1:]
# Ignore anything past the first whitespace
if cur_entry:
cur_entry = cur_entry.split()[0]
cur_seq = ""
return entries |
def get_adr_label_vec(adr_id, agent_index_dict, max_n_agents):
"""
:param adr_id: the addressee of the response; int
:param agent_index_dict: {agent id: agent index}
"""
y = []
n_agents_lctx = len(agent_index_dict)
# the case of including addressee in the limited context
if adr_id in agent_index_dict and n_agents_lctx > 1:
# True addressee index
y.append(agent_index_dict[adr_id] - 1)
# False addressee index
for i in range(len(agent_index_dict) - 1):
if i not in y:
y.append(i)
pad = [-1 for i in range(max_n_agents - 1 - len(y))]
y = y + pad
return y |
def format_(__format_string, *args, **kwargs):
""":yaql:format
Returns a string formatted with positional and keyword arguments.
:signature: string.format([args], {kwargs})
:receiverArg string: input string for formatting. Can be passed only as
first positional argument if used as a function. Can contain literal
text or replacement fields marked by braces {}. Every replacement field
should contain either the numeric index of a positional argument or the
name of a keyword argument
:argType string: string
:arg [args]: values for replacements for numeric markers
:argType [args]: chain of strings
:arg {kwargs}: values for keyword replacements
:argType {kwargs}: chain of key-value arguments, where values are strings
:returnValue: string
.. code::
yaql> "abc{0}ab{1}abc".format(" ", ",")
"abc ab,abc"
yaql> "abc{foo}ab{bar}abc".format(foo => " ", bar => ",")
"abc ab,abc"
yaql> format("abc{0}ab{foo}abc", ' ', foo => ",")
"abc ab,abc"
"""
return __format_string.format(*args, **kwargs) |
def transform_time(tim):
"""Transform from hh:mm:ss:fn or pts to hh:mm:ss:ms."""
try:
parts = tim.split(":")
frame_nr = int(parts[-1])
milis = min(int(frame_nr*1000/29.97), 999)
newtime = "%s.%03d" % (":".join(parts[:-1]), milis)
except AttributeError: # pts time
seconds = tim//90000
milis = int((tim % 90000)/90.0)
hours = seconds//3600
minutes = seconds//60
seconds -= hours*3600 + minutes*60
newtime = "%02d:%02d:%02d.%03d" % (hours, minutes, seconds, milis)
return newtime |
def multichoose(n, c):
"""
stars and bars combinatorics problem:
enumerates the different ways to parition c indistinguishable balls into
n distinguishable bins.
returns a list of n-length lists
http://mathoverflow.net/a/9494
"""
if c < 0 or n < 0:
raise
if not c:
return [[0] * n]
if not n:
return []
if n == 1:
return [[c]]
return [[0] + val for val in multichoose(n - 1, c)] + \
[[val[0] + 1] + val[1:] for val in multichoose(n, c - 1)] |
def is_rgb(shape):
"""If last dim is 3 or 4 assume image is rgb.
"""
ndim = len(shape)
last_dim = shape[-1]
if ndim > 2 and last_dim < 5:
return True
else:
return False |
def green(text):
""" Print text in green to the console """
return "\033[32m" + text + "\033[0m" |
def walk_dict_filter(resource, case_handler, **kwargs):
"""
Goes over the fields & values of a dictionary or list and updates it by camel-casing the field name and applying a
transformation over each field value.
"""
if isinstance(resource, dict):
return {
k[0].upper() + k[1:]: walk_dict_filter(case_handler(k, v, **{**kwargs, 'parent': resource}), case_handler,
**kwargs) for k, v in
resource.items() if
('shape_filter' in kwargs and k[0].upper() + k[1:] in kwargs[
'shape_filter']) or 'shape_filter' not in kwargs}
elif isinstance(resource, list):
return [walk_dict_filter(item, case_handler, **{**kwargs, 'parent': item}) for item in resource]
return resource |
def matrix_to_string(matrix):
"""
prints a python list in matrix formatting
"""
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
return '\n'.join(table) + '\n' |
def highlight_str(s, highlight_type=None):
"""
Highlighter for logging using ANSI escape code.
:param s: the element to highlight in the logs
:param highlight_type: types of highlight
:return: an highlighted string
"""
if highlight_type == 'query':
return "\x1b[31;1m %s \x1b[0m" % s
elif highlight_type == 'triple':
return "\x1b[32;1m %s \x1b[0m" % s
else:
return "\x1b[34;1m %s \x1b[0m" % s |
def u8_string(binary: bytes) -> str:
"""
Convert a binary string to a unicode string.
"""
return binary.decode("utf-8") |
def removeSelfLoops(pd):
"""
This function trims pd of all full loops
When trimmed, nodes with only loops do not appear in the path dictionary at all.
"""
pd2 = {}
for s in pd:
for d in pd[s]:
if s != d:
pd2.setdefault(s, dict())[d] = pd[s][d]
return pd2 |
def histogram(samples):
"""
Returns a histogram of samples. The input samples are evaluated in list context
and is typically the output from many of the other functions in this module. Returns
a dictionary where the discovered samples are the keys and the occurence count
is stored in the corresponding dictionary value.
"""
histogram = {}
for s in samples:
if s in histogram:
histogram[s] += 1
else:
histogram[s] = 1
return histogram |
def equals_auto_tol(x: float, y: float, precision: float = 1e-6) -> bool:
""" Returns true if two numbers are equals using a default tolerance of 1e-6 about the smaller one. """
return abs(x - y) < min(x, y) * precision; |
def _to_list(a):
"""convert value `a` to list
Args:
a: value to be convert to `list`
Returns (list):
"""
if isinstance(a, (int, float)):
return [a, ]
else:
# expected to be list or some iterable class
return a |
def maybe_list(l):
"""Return list of one element if ``l`` is a scalar."""
return l if l is None or isinstance(l, list) else [l] |
def transform_list_to_str(list_op):
"""
:param list_op:
:return:
"""
res = ""
for item in list_op:
tmp = "^" + item + "$|"
res += tmp
return res[:-1] |
def get_library_index(library, label):
"""Find index in library of function corresponding to a given label"""
for idx, name in enumerate(library.keys()):
if name == label:
return idx
return -1 |
def find_it(seq):
"""Function to return int that appears in a seq an odd # of times."""
d = {}
for i in seq:
try:
d[i] += 1
except KeyError:
d[i] = 1
for key in d.keys():
if d[key] % 2 == 1:
return(key) |
def process_time(s_time, e_time):
"""
process_time method is written for calculate time
:param s_time: start time
:param e_time: end time
:return:
elapsed_mins: Minutes of process
elapsed_secs: Seconds of process
"""
elapsed_time = e_time - s_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs |
def draw_stairs(n):
"""
Time complexity: O(n^2).
Space complexity: O(n).
"""
stairs = []
for i in range(n):
# Append (i - 1) spaces.
stairs.append(' ' * i)
# Append stair I.
stairs.append('I')
# Append change line if not the last line.
if i != n - 1:
stairs.append('\n')
return ''.join(stairs) |
def normalize_options(options):
"""
Takes some options that have a mixture of - and _ and returns the
equivalent options with only '_'.
"""
normalized_opts = {}
for k, v in options.items():
normalized_key = k.replace('-', '_')
assert normalized_key not in normalized_opts, "The key {0} cannot be normalized".format(k)
normalized_opts[normalized_key] = v
return normalized_opts |
def _make_path_str(path: list) -> str:
"""
Converts a path component list to a dot-separated string
:param path: path components
:returns: dot separated path string
"""
return '.'.join(path) |
def frequency(baskets, item):
"""
Frequency of item in baskets
"""
freq = 0
for basket in baskets:
if item <= basket: freq += 1
return freq |
def _FilterAndFormatImports(import_dict, signature_types):
"""Returns formatted imports required by the passed signature types."""
formatted_imports = [
'import %s;' % import_dict[t] for t in signature_types if t in import_dict
]
return sorted(formatted_imports) |
def binary_mse_init(thr, wavelet="haar"):
"""
Initialize a binary MSE (BMSE) verification object.
Parameters
----------
thr: float
The intensity threshold.
wavelet: str, optional
The name of the wavelet function to use. Defaults to the Haar wavelet,
as described in Casati et al. 2004. See the documentation of PyWavelets
for a list of available options.
Returns
-------
bmse: dict
The initialized BMSE verification object.
"""
bmse = dict(thr=thr, wavelet=wavelet, scales=None, mse=None, eps=0, n=0)
return bmse |
def add_numbers(numbers):
"""Sum a list of numbers server side, ridiculous but well..."""
total = 0
for number in numbers:
try:
total = total + float(number)
except (ValueError, TypeError):
pass
return total |
def kmlcoord(lst):
"""Formats the coordinates according to KML file requirements."""
if len(lst) == 2:
lst += ('0',)
return ','.join(str(i) for i in lst) |
def hexdump(data):
"""Convert byte array to hex string"""
return ' '.join(["{:02X}".format(v) for v in data]) |
def basic_sent_chop(data, raw=True):
"""
Basic method for tokenizing input into sentences
for this tagger:
:param data: list of tokens (words or (word, tag) tuples)
:type data: str or tuple(str, str)
:param raw: boolean flag marking the input data
as a list of words or a list of tagged words
:type raw: bool
:return: list of sentences
sentences are a list of tokens
tokens are the same as the input
Function takes a list of tokens and separates the tokens into lists
where each list represents a sentence fragment
This function can separate both tagged and raw sequences into
basic sentences.
Sentence markers are the set of [,.!?]
This is a simple method which enhances the performance of the TnT
tagger. Better sentence tokenization will further enhance the results.
"""
new_data = []
curr_sent = []
sent_mark = [",", ".", "?", "!"]
if raw:
for word in data:
if word in sent_mark:
curr_sent.append(word)
new_data.append(curr_sent)
curr_sent = []
else:
curr_sent.append(word)
else:
for (word, tag) in data:
if word in sent_mark:
curr_sent.append((word, tag))
new_data.append(curr_sent)
curr_sent = []
else:
curr_sent.append((word, tag))
return new_data |
def fourprod(vec1,vec2):
"""
inner product of two four-vectors
"""
return vec1[0]*vec2[0]-vec1[1]*vec2[1]-vec1[2]*vec2[2]-vec1[3]*vec2[3] |
def gen_color_names(colors):
"""
Convert RGB values into a hexadecimal color string.
"""
color_names = []
for color in colors:
name = "{:02x}{:02x}{:02x}".format(*color)
color_names.append(name)
return color_names |
def coarse_pos_e(tags):
"""
Coarse POS tags of Dadegan corpus:
N: Noun, V: Verb, ADJ: Adjective, ADV: Adverb, PR: Pronoun, PREP: Preposition, POSTP: Postposition, CONJ: Conjunction, PUNC: Punctuation, ADR: Address Term, IDEN: Title, PART: Particle, POSNUM: Post-noun Modifier, PREM: Pre-modifier, PRENUM: Pre-noun Numeral, PSUS: Pseudo-sentence, SUBR: Subordinating Clause
>>> coarse_pos_e(['N', 'IANM'])
'N'
"""
map = {'N': 'N', 'V': 'V', 'ADJ': 'AJ', 'ADV': 'ADV', 'PR': 'PRO', 'PREM': 'DET', 'PREP': 'P', 'POSTP': 'POSTP', 'PRENUM': 'NUM', 'CONJ': 'CONJ', 'PUNC': 'PUNC', 'SUBR': 'CONJ'}
return map.get(tags[0], 'X') + ('e' if 'EZ' in tags else '') |
def sortBoxes(boxes):
"""Calculate coordinates for each box and sort in reading order"""
for ent in boxes:
ent['xmin'] = float(ent['x'])
ent['ymin'] = float(ent['y'])
ent['width'] = float(ent['width'])
ent['height'] = float(ent['height'])
ent['xmax'] = ent['xmin'] + ent['width']
ent['ymax'] = ent['ymin'] + ent['height']
num_boxes = len(boxes)
# sort from top to bottom and left to right
sorted_boxes = sorted(boxes, key=lambda x: (x['ymin'], x['xmin']))
_boxes = list(sorted_boxes)
# for j in range:
# check if the next neighbour box x coordinates is greater then the current box x coordinates if not swap them.
# repeat the swaping process to a threshold iteration and also select the threshold
#MAY NEED TO ADJUST THIS THRESHOLD
threshold_value_y = 25
for i in range(5):
for i in range(num_boxes - 1):
if abs(_boxes[i + 1]['ymin'] - _boxes[i]['ymin']) < threshold_value_y and (_boxes[i + 1]['xmin'] < _boxes[i]['xmin']):
tmp = _boxes[i]
_boxes[i] = _boxes[i + 1]
_boxes[i + 1] = tmp
return _boxes |
def address(obj):
"""Return object address as a string: '<classname @ address>'"""
return "<%s @ %s>" % (obj.__class__.__name__,
hex(id(obj)).upper().replace('X','x')) |
def unpack(value):
"""Return a three tuple of data, code, and headers"""
if not isinstance(value, tuple):
return value, 200, {}
try:
data, code, headers = value
return data, code, headers
except ValueError:
pass
try:
data, code = value
return data, code, {}
except ValueError:
pass
return value, 200, {} |
def _imag_1d_func(x, func):
"""Return imag part of a 1d function."""
return func(x).imag |
def _convert_dtype_value(val):
"""converts a Paddle type id to a string."""
convert_dtype_map = {
21: "int8",
20: "uint8",
6: "float64",
5: "float32",
4: "float16",
3: "int64",
2: "int32",
1: "int16",
0: "bool",
}
if val not in convert_dtype_map:
msg = "Paddle data type value %d is not handled yet." % (val)
raise NotImplementedError(msg)
return convert_dtype_map[val] |
def echo2(msg: str, fail: bool = False) -> str:
"""
returns ``msg`` or raises a RuntimeError if ``fail`` is set
"""
if fail:
raise RuntimeError(msg)
return msg |
def reformat_dict_keys(keymap=None, inputdict=None):
"""Utility function for mapping one dict format to another."""
keymap = keymap or {}
inputdict = inputdict or {}
return dict([(outk, inputdict[ink]) for ink, outk in keymap.items()
if ink in inputdict]) |
def dec2base(num, base, l):
"""
Decimal to any base conversion.
Convert 'num' to a list of 'l' numbers representing 'num'
to base 'base' (most significant symbol first).
"""
s = list(range(l))
n = num
for i in range(l):
s[l-i-1]=n%base
n=int(n / base)
if n!=0:
print('Number ', num, ' requires more than ', l, 'digits.')
return s |
def comb_sort(elements):
"""
Use the simple comb sort algorithm to sort the :param elements.
:param elements: a sequence in which the function __get_item__ and __len__ were implemented
:return: the sorted elements in increasing order
"""
length = len(elements)
if not length or length == 1:
return elements
copy = length - 1
steps = []
while copy > 1:
if copy == 9 or copy == 10:
copy = 11
steps.append(copy)
copy = int(copy / 1.3)
steps.append(1)
if length == 10 or length == 11:
steps = steps[1:]
for step in range(len(steps)):
step = steps[step]
if step > length / 2:
if elements[0] > elements[0 + step]:
elements[0], elements[0 + step] = elements[0 + step], elements[0]
else:
limit = length
while limit > step:
i = 0
while i + step < limit:
if elements[i] > elements[i + step]:
elements[i], elements[i + step] = elements[i + step], elements[i]
i += step
limit -= step
return elements |
def _rhou_f(rho, rhou, p):
"""Computes the flux of the momentum equation."""
return rhou**2 / rho + p |
def find_cntrs(boxes):
"""Get the centers of the list of boxes in the input.
Parameters
----------
boxes : list
The list of the boxes where each box is
[x,y,width,height] where x,y is the coordinates
of the top-left point
Returns
-------
list
Centers of each box where each row is a list of
two float numbers (x,y).
"""
# box is : x,y,w,h
centers = []
for box in boxes:
centers.append([(box[0]+(box[2]/2)),(box[1]+(box[3]/2))])
return centers |
def default_key_func(key, key_prefix, version):
"""
Default function to generate keys.
Constructs the key used by all other methods. By default it prepends
the `key_prefix'. KEY_FUNCTION can be used to specify an alternate
function with custom key making behavior.
"""
return '%s:%s:%s' % (key_prefix, version, key) |
def expsign(sign, exp):
"""
optimization of sign ** exp
"""
if sign == 1:
return 1
assert sign == -1
return -1 if exp % 2 else 1 |
def contains(search_list, predicate):
"""Returns true if and only if the list contains an element x where predicate(x) is True."""
for element in search_list:
if predicate(element):
return True
return False |
def find_index_from_freq(freq, frequency_step):
"""
Gives the index corresponding to a specific frequency (eg to find a frequency
from a fourier transform list). Requires the frequency step of the list
Arguments:
freq - frequency being looked for
frequency_step - the step between consecutive indexes
"""
index = int(round(freq/frequency_step))
return index |
def convert_comment_block(html):
"""
Convert markdown code block to Confluence hidden comment
:param html: string
:return: modified html string
"""
open_tag = '<ac:placeholder>'
close_tag = '</ac:placeholder>'
html = html.replace('<!--', open_tag).replace('-->', close_tag)
return html |
def format_artist_rating(index, data):
"""Returns a formatted line of text describing the artist and its rating."""
return "{}. {artist} - {rating:.1f}\n".format(index, **data) |
def rc4(data, key):
"""RC4 encryption and decryption method."""
S, j, out = list(range(256)), 0, []
for i in range(256):
j = (j + S[i] + key[i % len(key)]) % 256
S[i], S[j] = S[j], S[i]
i = j = 0
for ch in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
out.append(chr(ch ^ S[(S[i] + S[j]) % 256]))
return "".join(out) |
def distance_xyz(p1, p2):
"""Calculates 2D distance between p1 and p2. p1 and p2 are vectors of
length >= 3."""
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2)**0.5 |
def every_item_but_one(l: list, idx: int) -> list:
"""
Returns every item in the list except for the one at index idx.
:param l: a list to process.
:param idx: the index to be excluded from the list.
:return: the list l minus the item at index idx.
"""
return [item for i, item in enumerate(l) if i != idx] |
def subIPSimilar(sub1, sub2):
"""Returns the scaled difference between the CIDR block prefixes"""
diff = abs(sub1-sub2)
return abs((diff/255)-1) |
def newline_to_br(base):
"""Replace newline with `<br />`"""
return base.replace('\n', '<br />') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.