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).
... |
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 ... |
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 ... |
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... |
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... |
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 ... |
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_d... |
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
"""
... |
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":... |
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
T... |
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``
... |
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
... |
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 fundin... |
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 Stat... |
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... |
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:
- `st... |
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:
... |
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:
... |
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.
... |
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... |
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 r... |
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]
... |
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 ... |
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
... |
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:... |
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... |
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:
... |
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.
... |
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 a... |
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. ... |
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
seco... |
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:
r... |
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... |
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) ... |
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... |
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]
... |
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 correspo... |
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(elaps... |
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 lin... |
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 ke... |
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 Casat... |
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... |
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 Nu... |
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['... |
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, c... |
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 con... |
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:
... |
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:
... |
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... |
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' % (k... |
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
... |
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 ... |
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... |
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... |
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.