content stringlengths 42 6.51k |
|---|
def unauth_or_invalid_jwt_handler(reason):
"""
Custom generic handler for when the given JWT is invalid.
"""
return {'status': 'error', 'reason': reason}, 401 |
def format_integer(num: int, force_sign: bool = False) -> str:
"""Formats a integer with commas."""
prefix = '+' if force_sign and num > 0 else ''
return '{}{:,}'.format(prefix, num) |
def label_expression_to_str(label):
"""Return symbol of expression"""
if label == "plus":
return '+'
elif label == "minus":
return '-'
elif label == "div":
return '/'
elif label == "decimal" or label == "times":
return 'x' |
def _p(pp, name):
"""
Make prefix-appended name
"""
return '%s_%s'%(pp, name) |
def get_filetext(fname, lineno):
"""try to extract line from source text file"""
out = '<could not find text>'
try:
ftmp = open(fname, 'r')
lines = ftmp.readlines()
ftmp.close()
lineno = min(lineno, len(lines)) - 1
out = lines[lineno][:-1]
except:
pass
... |
def get_inrange(get, default, highest):
""" Checks if an int is in a range """
if get and get.isdigit() and int(get) in range(highest):
return int(get)
return default |
def sentiment(rating, source):
"""Return sentiment for a given rating"""
if source == "ReclameAqui":
rating /= 2
if rating < 3:
return "negative"
elif rating >= 3:
return "positive" |
def reverse_order_str(order_str):
"""Given some ordering, possibly already negative, reverse it."""
# Historical note on why we abstract orderings as strings:
# NDB makes it really hard to reverse an arbitrary ordering.
# Specifically, Property.__neg__() returns a PropertyOrder, not
# a Property, s... |
def get_project_choices(env):
"""Concatentate the names of values in a structure."""
results = ""
first_choice = True
for i, v in enumerate(env['projects']):
if first_choice:
results = "%s (%s)" % (v['name'], v['key'])
first_choice = False
else:
result... |
def useless_detect(entity):
"""
detect useless entity
"""
fh = "~!@#$%^&*()_+-*/<>,.[]\/ "
sz = "0123456789"
flag = 0
for e in entity:
if e in fh or e in sz:
flag += 1
if flag == len(entity):
return True
else:
return False |
def underscore_unescape(text):
"""
This function mimics the behaviour of underscore js unescape function
The html unescape by jinja is not compatible for underscore escape
function
:param text: input html text
:return: unescaped text
"""
html_map = {
"&": '&',
"<":... |
def support_interval(thing):
"""Lower and upper bounds on this value, if known."""
if hasattr(thing, "support_interval"):
return thing.support_interval()
if isinstance(thing, (int, float)):
return thing, thing
return None, None |
def get_best_indexes(logits, n_best_size):
"""Gets the indices of the n-best logits from a list."""
indices = sorted(range(len(logits)), key=logits.__getitem__, reverse=True)
return indices[:n_best_size] |
def argument_parser(input_args):
"""
Returns a list of tokens for a given argument
:param input_args: input string
:return: argument list
"""
arguments = input_args.split(' ')
if len(arguments) > 1:
return arguments[1:]
else:
return arguments |
def fib(n):
"""Calculate the n-th fibonacci number."""
def acc_fib(n, n_m2=0, n_m1=1):
for i in range(n):
n_m2, n_m1 = n_m1, n_m1+n_m2
return n_m2
return acc_fib(n) |
def remove_from_dict(obj, keys=list(), keep_keys=True):
""" Prune a class or dictionary of all but keys (keep_keys=True).
Prune a class or dictionary of specified keys.(keep_keys=False).
"""
if type(obj) == dict:
items = list(obj.items())
elif isinstance(obj, dict):
items = list(... |
def clean(string):
"""Return a *clean* string
Removes whitespace and hyphen
"""
return string.replace(" ", "").replace("-", "") |
def str2int(video_path):
"""
argparse returns and string althout webcam uses int (0, 1 ...)
Cast to int if needed
"""
try:
return int(video_path)
except ValueError:
return video_path |
def even_numbers_list(n):
""" Returns the list of n first even numbers"""
return [2 * k for k in range(0, n)] |
def fatal_request_error(err=None):
"""Give up retrying if the error code is in fatal range.
Returns:
bool: True if to giveup on backing off, False it to continue.
"""
if not err or not err.response:
return False
if err.response.status_code == 403:
# download url needs to be ... |
def dict_replace(subject_dict, string):
"""
Replace a dict map, key to its value in the stirng
:param subject_dict: dict
:param string: string
:return: string
"""
for i, j in subject_dict.items():
string = string.replace(i, j)
return string |
def to_bool(value):
"""Try to convert the string to a boolean"""
return (
value.lower()[0] in ["y", "t", "1"] if isinstance(value, str) else bool(value)
) |
def _get_name(type_, value):
"""Return the name for the given value of the given type_.
The value `None` returns empty string.
"""
return type_._VALUES_TO_NAMES[value] if value is not None else "None" |
def get_source_url(j):
"""
return URL for source file for the latest version
return "" in errors
"""
v = j["info"]["version"]
rs = j["releases"][v]
for r in rs:
if r["packagetype"] == "sdist":
return r["url"]
return "" |
def RS_indices(name):
"""Extract raster-scan indices (row,column) from name; returns (r,c)."""
indices = name.split("/")[-1].split("_")[0].split(",")
R = int(indices[0])
C = int(indices[1])
return R,C |
def _obfuscate(string):
"""
Given a string, return that string obfuscated for display on a web page.
"""
return ''.join(['&#%s;' % ord(char) for char in string]) |
def regulatory_elements(gene_descriptors):
"""Provide possible regulatory_element input data."""
return [
{
"type": "promoter",
"gene_descriptor": gene_descriptors[0]
}
] |
def get_fuel_cost_part2(x1, x2):
"""Get the fuel that would cost move from x1 to x2, when:
Moving from each change of 1 step in horizontal position costs 1 more unit of fuel than the last. This can be easily
computed as a triangular number/binomial coefficient.
"""
steps = abs(x1-x2)
return ste... |
def _lower(text):
"""Convert the supplied text to lowercase"""
return text.lower() |
def __py_variable(statements,lineno):
"""returns a valid python assignment statement"""
return statements[:statements.find('var')]+statements.replace('var','').strip()+'\n' |
def format_odometer(raw: list) -> dict:
"""Formats odometer information from a list to a dict."""
instruments: dict = {}
for instrument in raw:
instruments[instrument["type"]] = instrument["value"]
if "unit" in instrument:
instruments[instrument["type"] + "_unit"] = instrument["u... |
def evalMultiRefToken(mref, ixname, val):
"""Helper function for evaluating multi-reference tokens for
given index values."""
return eval(mref.replace(ixname,str(val)), {}, {}) |
def my_function(x):
"""This is docstring"""
print(x)
return x |
def parse_image_layers(data, width, height):
"""
>>> parse_image_layers("123456789012", 3, 2)
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [0, 1, 2]]]
"""
num_layers = len(data) // (width*height)
image = [[] for _ in range(num_layers)]
counter = 0
for layer in range(num_layers):
for y in... |
def geojson_features_to_collection(geojson_features):
"""
Adds the feature collection wrapper for geojson
"""
return {
'type': 'FeatureCollection',
'crs': {
'type': 'name',
'properties': {
'name': 'EPSG:4326'
}
},
'featu... |
def _is_number(s):
"""
Check whether string can be converted to float
"""
try:
float(s)
return True
except TypeError: # for example if 'None' is sent
return False
except ValueError: # for example if a 'string' is sent
return False |
def palindromic_permutation(string):
"""
Question 13.2: Test whether the letters
forming a string to form a palindrome
"""
seen = set()
for char in string:
if char in seen:
seen.remove(char)
else:
seen.add(char)
return len(seen) <= 1 |
def extract_bmi_percentile(s):
"""
Extract a bmi percentile from a string.
Precondition: string must be in format 'number%' (ex: '20%')
"""
return int(s[:-1]) |
def unique(x):
"""Return a list of unique elements of *x*"""
return list(set(x)) |
def process_other_transcript(contents):
"""
process all other transcript output
"""
checked = contents.count('<strong>') > 0
context = {'text': contents, 'checked': checked }
return context |
def premises_to_syllogism(premises):
"""
>>> premises_to_syllogism(["Aab", "Ebc"])
'AE1'
"""
figure = {"abbc": "1", "bacb": "2", "abcb": "3", "babc": "4"}[premises[0][1:] + premises[1][1:]]
return premises[0][0] + premises[1][0] + figure |
def clean_IPv6(host_address):
"""Clean IPv6 host address
"""
if host_address:
host_address = host_address.replace("[", "")
host_address = host_address.replace("]", "")
return host_address |
def team_role_from_base_role(base_role, default=None):
"""
Converts a ``user.role`` value to equivalent team role value
:param base_role: The role value that would typically be user's base role
:param default: The default value if no equivalent is found.
"""
team_role = default
if base_role... |
def _login_url(subdomain):
"""
Returns the URL for the login page for the given subdomain.
"""
return 'https://{subdomain}.slack.com/'.format(subdomain=subdomain) |
def pad_b64(b64s):
"""Pad Base64 encoded string so that its length is a multiple of 4 bytes"""
pad = len(b64s) % 4
if pad != 0:
return b64s + '=' * pad
return b64s |
def dot2D(v1,v2):
"""calculates the scalar dot product of two 2D vectors, v1 and v2"""
return v1[0]*v2[0] + v1[1]*v2[1] |
def push_backslash(stuff):
""" push a backslash before a word, dumbest function ever"""
stuff_url = ""
if stuff is None:
stuff = ""
else:
stuff_url = "/" + stuff
return stuff, stuff_url |
def _splits_label_and_features(example, label_tensors):
"""
Split the features and labels in a tfrecord example or sequence example.
:param example: tfrecord example or sequence of example
:param label_tensors: metadata of label tensors
:return: feature partition and label partition of the example /... |
def generate_dir_prefix(max_weight_kld: float = 1.0, warmup_bool: bool = True):
"""Return the prefix for the directory name of the training run"""
return f'weightedVAE_{max_weight_kld}_warmup_{warmup_bool}_' |
def int2bin(n, count=24):
"""
trans a number to binary string
:param n: number
:type n: int
:param count: total length
:type count: int
:rtype: binary string
"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) |
def sign(number):
"""Return the sign of a number."""
return 1 if number >= 0 else -1 |
def reverse_words(sentence):
"""
Question 7.6: Reverse space-separated words in string
"""
split_sentence = sentence.split()
return ' '.join(reversed(split_sentence)) |
def should_go_right(event: dict):
"""Returns true if the current text event implies a "right" button press to proceed."""
if event["text"].startswith("Review"):
return True
elif event["text"].startswith("Amount"):
return True
elif event["text"].startswith("Address"):
return True... |
def encode_html_for_file(html):
"""Hack in a meta tag at the top of an HTML snippet to make the resulting
file display correctly in a web browser."""
return ('<meta charset="utf-8">\n' + html).encode('utf-8') |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
Dictionary. Structured data with the following schema:
{
"variables": [
"name": string,
... |
def default_viewname_order(tx_rx_tuple):
"""
The views are sorted in ascending order with the following criteria (in this order):
1) the total number of legs,
2) the maximum number of legs for transmit and receive paths,
3) the number of legs for receive path,
4) the number of legs for transmit... |
def gen_State(drone_id, battery, direction, position, sensor_status, speed):
"""Generate a State objects."""
state = {
"@type": "State",
"DroneID": drone_id,
"Battery": battery,
"Direction": direction,
"Position": position,
"Status": sensor_status,
... |
def scan_row(row):
"""get the first and last shaded columns in a row"""
start = 0
end = 0
for c, value in enumerate(row):
if value:
if start == 0:
start = c
end = c
return (start, end) |
def negate(obj):
"""
Toggle boolean value or reverse the sign of an integer.
:param obj:
:return:
"""
try:
if isinstance(obj, bool):
return not obj
return -1 * int(obj)
except:
return obj |
def array_pyxll_function_3(x):
"""returns the types of the elements as strings"""
# x may not be an array
if not isinstance(x, list):
return [[type(x)]]
# x is a 2d array - list of lists.
return [[type(e) for e in row] for row in x] |
def LegalCharacter(character) -> bool:
"""
description: check if character is legal
param {*} character
return {*} bool value
"""
if character.isalnum() or character == "_":
return True
else:
return False |
def get_measures(station_data):
"""Force measure key to always be a list."""
if "measures" not in station_data:
return []
if isinstance(station_data["measures"], dict):
return [station_data["measures"]]
return station_data["measures"] |
def findRandomLabel(labels, name):
"""
Because some people are too clever by half, ensure that group labels are unique...
"""
if name not in labels:
return name
# This is what the heatmapper.py did to ensure unique names
i = 0
while True:
i += 1
nameTry = name + "_r"... |
def getSectionByName(sections, name, key="name", default=None):
"""identify the first section with matching key among 'sections'"""
for s in sections:
if name == s.get(key):
return s
return default |
def Offset_op(input_length, output_length, stride):
"""
Takes input(height, width), output(height, width) and strides
:param input_length:
:param output_length:
:param stride:
:return: offset, i.e. left out portion after applying strides
"""
offset = (input_length) - (stride * ... |
def saves_to_partial_epochs(epochs, saves):
"""epochs is a list of epochs, and saves[k] is a list of all the saves for epoch k. This utility converts these two
lists into a single list that shows all of the (fractional) epochs at which saves occur. For instance,
epochs = [0,1,2,3] and saves=[[0,1],[0,1],[0,... |
def mean(numbers):
"""Return the arithmetic mean of a list of numbers"""
return float(sum(numbers)) / float(len(numbers)) |
def next_biggest(target, in_list):
"""
Returns the next highest number in the in_list.
If target is greater the the last number in in_list, will return the last
item in the list.
"""
next_highest = None
for item in in_list:
if item > target:
next_highest = item
... |
def color(palos):
"""
Regresa 1 si encuentra un color,
de lo contrario regresa 0
palos es un arreglo con todos los
palos de la mano
"""
palo_carta_1 = palos[0] # Primer palo
for palo in palos:
if palo_carta_1 != palo:
return 0
return 1 |
def proper_fractions_totient(num):
"""Calculate using the Euler totient function."""
# Totient function description:
# https://en.wikipedia.org/wiki/Euler%27s_totient_function
# Method proof:
# Totient function is defined as follows:
# phi(n) = n * Pi(1 - 1/p) for prime numbers where p | n
#... |
def calc_score(score):
"""
Convert threatgrid score to dbot score
"""
if not score:
return 0
dbot_score = 1
if score >= 95:
dbot_score = 3
elif score >= 75:
dbot_score = 2
return dbot_score |
def table( data ):
"""
create a markdown table
"""
seps = " | ".join( [ "---" for x in data[0] ] )
data[0] = " | ".join( [ str(x) for x in data[0] ] )
data[1:] = [ " | ".join( [ str(x) for x in y ] ) for y in data[1:] ]
result = "\n\n"
result += data[0]
result += "\n"
result += seps
result += "\n... |
def group_signature_features(signature_features):
"""Further prepare signature feature dict for visualization"""
grouped_features = {}
for feature in signature_features:
if feature["gn"] not in grouped_features:
grouped_features[feature["gn"]] = []
grouped_features[feature["gn"]]... |
def apply_func_to_ast_helper(ast, func, acc):
"""Recursive helper function for "apply_func_to_ast".
Args:
ast: The AST instance.
func: The function applied to the AST elements.
acc: A list of values accumulated during application.
Returns:
The adapted AST.
"""
if is... |
def is_integer(s):
""" Simply check whether or not a given input is a string or an integer
Args:
s (str): A string.
Returns:
(bool): True if the string can be cast as an int. False if the string
can not be cast as an int (it is actually not an int).
"""
try:
int... |
def increment_idx(poolidx, maxidx):
"""
Increments the pool indexes.
"""
try:
poolidx[0] += 1
if poolidx[0] <= maxidx:
return poolidx
except: # index out of range, list empty
return []
update = False
for i in range(1, len(poolidx)):
if po... |
def conv_tup_to_str(tupl):
"""
Join all the string entries inside a tuple
@param {tuple} tupl Tuple of strings
@return {tuple} Tuple of one concatenated string
"""
return tuple(map("".join, tupl)) |
def create_selector_query(selectors_list):
"""
Get a list of selectors and append them to a whole one liner that will get
the element by combining the querySelector function with the provided
selectors
If the value `shadowRoot` is given, then the shadow-root element will be
used in the query
... |
def compare_overlaps(context, synsets_signatures,
nbest=False, keepscore=False, normalizescore=False):
"""
Calculates overlaps between the context sentence and the synset_signture
and returns a ranked list of synsets from highest overlap to lowest.
"""
overlaplen_synsets = [] # ... |
def _get_sensor_name(sensor, entry_data):
"""Generate a name based on the kube and flx config, and the data type and sub type."""
name = "unknown"
if "class" in sensor and sensor["class"] == "kube":
if (
"kube" in entry_data
and "name" in entry_data["kube"][str(sensor["kid"])... |
def build_xaxis(num, radius_increment=0.05):
"""Calculate the radius/diameter for the x-axis in plots."""
x_axis = {
'radius': [],
'diameter': []
}
radius = 0
for _ in range(num):
radius = round(radius, 2)
diameter = round(radius * 2, 1)
x_axis['radius'].append(radius)
x_axis['dia... |
def get_bounds_from_centre_and_diameter(centre, diameter):
"""Convert centre and field size into collimation edge positions."""
lower = centre - diameter / 2
upper = centre + diameter / 2
return lower, upper |
def get_current_in_all(l_to_add, l_old, pattern_dict):
"""
Get those labels that were already there and known
:param l_to_add: new labels
:param l_old: old labels
:type l_to_add: list
:type l_old: list
:param pattern_dict: directory of patterns that are used to match the ... |
def OnlyTests(path, dent, is_dir):
"""Filter function that can be passed to FindCFiles in order to remove
non-test sources."""
if is_dir:
return dent != 'test'
return '_test.' in dent |
def is_bip66(sig):
"""Checks hex DER sig for BIP66 compliance"""
#https://raw.githubusercontent.com/bitcoin/bips/master/bip-0066.mediawiki
#0x30 [total-len] 0x02 [R-len] [R] 0x02 [S-len] [S] [sighash]
# sig = bytearray.fromhex(sig) if (isinstance(sig, string_types) and
# ... |
def get_module_name(path, package_name):
"""Determines the correct python module name for the given os path, relative to a particular package"""
package_index = path.rfind(package_name)
if package_index >= 0:
path = path[package_index:]
else:
raise ValueError("package_name %s not found i... |
def make_blocks(listlike, blocksize):
"""Make blocks out of a listlike object.
Parameters
----------
listlike : Iterable
must be an iterable that supports slicing
blocksize : int
number of objects per block
Returns
-------
List[List[Any]] :
the input iterable c... |
def process_utterance(utterance):
"""Lowercase and remove punctuation."""
return utterance.lower().rstrip("?").rstrip(".").rstrip().replace(" '", "") |
def fill_gap_to_prevent(board, ai_mark, player_mark):
"""Put a mark ('ai_mark) in the gap on the line to prevent player (human) win
if doing so returns True, otherwise False."""
# copy of board
board_copy = board.copy()
# Changing 'board' lines from vertical to horizontal and put in 'tmp_list',
... |
def get_key_value(obj, key):
"""Get value for a nested key using period separated accessor
:param dict obj: Dict or json-like object
:param str key: Key, can be in the form of 'key.nestedkey'
"""
keys = key.split('.')
if len(keys) == 1:
return obj.get(keys[0])
else:
return ... |
def align_decision_ref(id_human, title):
""" In German, decisions are either referred to as 'Beschluss' or
'Entscheidung'. This function shall align the term used in the
title with the term used in id_human.
"""
if 'Beschluss' in title:
return id_human
return id_human.replace('Be... |
def get(path, context):
"""Resolve a value given a path and a deeply-nested object
Arguments:
path: a dot-separated string
context: any object, list, dictionary,
or single-argument callable
Returns:
value at the end of the path, or None
"""
parts = path.split(".... |
def _cast_query(query, col):
"""
ALlow different query types (e.g. numerical, list, str)
"""
query = query.strip()
if col in {"t", "d"}:
return query
if query.startswith("[") and query.endswith("]"):
if "," in query:
query = ",".split(query[1:-1])
return [... |
def even_or_odd (num):
"""
Is the given number even?
:return: True or False
"""
if num % 2 == 0:
return True
else:
return False |
def _simple_init(parent, num):
"""Creates a list parent copies"""
return [parent.copy() for i in range(num)] |
def collatz(n, verbose=False):
"""Return 1 if n is not a counterexample to the Collatz / Ulam / Kakutani /
Thwaites / blah / etc conjecture. Otherwise return some other number, or
never return.
Oh, and also return the number of steps taken to reduce the input.
"""
if verbose:
vprint = ... |
def _closest_partial_swap(a, b, c) -> float:
"""A good approximation to the best value x to get the minimum
trace distance for Ud(x, x, x) from Ud(a, b, c)
"""
m = (a + b + c) / 3
am, bm, cm = a - m, b - m, c - m
ab, bc, ca = a - b, b - c, c - a
return m + am * bm * cm * (6 + ab * ab + bc *... |
def space_filler(num_spaces):
"""Returns a string with the specified number of spaces.
@param num_spaces: The number of spaces
@type num_spaces: int
@return: The string
@rtype: str
"""
return " " * num_spaces |
def flatten(list_of_lists):
"""
- list_of_lists: (list (list *)), a list of lists
RETURN: (List *), the list flattened
"""
return [
item
for sublist in list_of_lists
for item in sublist] |
def check_type(x: str, inp_type: type) -> bool:
"""Function for checking if a string can be converted to a certain type.
Args:
x (str): String to convert.\n
inp_type (type) : Type.
Returns:
bool: If x can be converted or not.
"""
try:
inp_type(x)
return True... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.