content stringlengths 42 6.51k |
|---|
def digits_to_skip(distinct_letter_pairs: int) -> int:
"""The number of letters which can be skipped (i.e. not being incremented
one by one) depending on the number of distinct letter pairs present."""
if distinct_letter_pairs == 0:
# If no letter pair exists already, we know at least one must be
... |
def get_port_str(port: str) -> str:
"""Get str representing port for using in human_readable strings.
Args:
port (str): Port name
Returns:
str: if port is 'top' return '(port top)' if port is None return ''
"""
if port:
return '(port {0})'.format(port)
return '' |
def score_distance(x):
"""Function used to compute the distance score (x should be between 0 and 1 but can be a bit greter than 1)"""
a = 10
b = 0.5
s = 0.2
g = 0.18*x + s
f = (1/(b*g)**2 - a/(b*g)) * 0.1 *(1-x) / a
return min(1, - 4.82*f) |
def rescale_score_by_abs (score, max_score, min_score):
"""
rescale positive score to the range [0.5, 1.0], negative score to the range [0.0, 0.5],
using the extremal scores max_score and min_score for normalization
"""
# CASE 1: positive AND negative scores occur --------------------
if ma... |
def listify(value, return_empty_list_if_none=True, convert_tuple_to_list=True) -> list:
"""Ensures that the value is a list.
If it is not a list, it creates a new list with `value` as an item.
Args:
value (object): A list or something else.
return_empty_list_if_none (bool, optional): Wh... |
def remove_base64(examples):
"""Remove base64-encoded string if "path" is preserved in example."""
for eg in examples:
if "audio" in eg and eg["audio"].startswith("data:") and "path" in eg:
eg["audio"] = eg["path"]
if "video" in eg and eg["video"].startswith("data:") and "path" in eg... |
def format_bytes(size):
"""
Format a number of bytes as a string.
"""
names = ("B", "KB", "MB", "GB", "TB")
mag = 0
while size > 1024:
mag += 1
size = size / 1024.0
return "{} {}".format(round(size, 2), names[mag]) |
def _errmsg(argname, ltd, errmsgExtra=''):
"""Construct an error message.
argname, string, the argument name.
ltd, string, description of the legal types.
errmsgExtra, string, text to append to error mssage.
Returns: string, the error message.
"""
if errmsgExtra:
errmsgExtra = '\n' ... |
def truncate(s, maxlen=128, suffix='...'):
# type: (str, int, str) -> str
"""Truncate text to a maximum number of characters."""
if maxlen and len(s) >= maxlen:
return s[:maxlen].rsplit(' ', 1)[0] + suffix
return s |
def event():
"""Event fixture."""
return {
"path": "/",
"httpMethod": "GET",
"headers": {"Host": "test.apigw.com"},
"queryStringParameters": {},
} |
def _traverse_pagination(response, endpoint, querystring, no_data):
"""Traverse a paginated API response.
Extracts and concatenates "results" (list of dict) returned by DRF-powered APIs.
"""
results = response.get('results', no_data)
page = 1
next_page = response.get('next')
while next_pag... |
def replace(s, old, new, maxsplit=0):
"""replace (str, old, new[, maxsplit]) -> string
Return a copy of string str with all occurrences of substring
old replaced by new. If the optional argument maxsplit is
given, only the first maxsplit occurrences are replaced.
"""
return s.replace(o... |
def func_x_a(x, a=2):
"""func.
Parameters
----------
x: float
a: int, optional
Returns
-------
x: float
a: int
"""
return x, None, a, None, None, None, None, None |
def format_cmd(cmd):
"""If some command arguments have spaces, quote them. Then concatenate the results."""
ans = ""
for val in cmd:
if " " in val or "\t" in cmd:
val = '"' + val + '"'
ans += val + " "
return ans |
def xor(b1, b2):
"""Expects two bytes objects of equal length, returns their XOR"""
assert len(b1) == len(b2)
return bytes([x ^ y for x, y in zip(b1, b2)]) |
def bytes_to_int(byte_string) -> int:
"""
:param byte_string: a string formatted like b'\xd4\x053K\xd8\xea'
:return: integer value of the byte stream
"""
return int.from_bytes(byte_string, "big") |
def cross(*args):
""" compute cross-product of args """
ans = []
for arg in args[0]:
for arg2 in args[1]:
ans.append(arg+arg2)
return ans
#alternatively:
#ans = [[]]
#for arg in args:
#ans = [x+y for x in ans for y in arg]
#return ans |
def _isSBMLModel(obj):
"""
Tests if object is a libsbml model
"""
cls_stg = str(type(obj))
if ('Model' in cls_stg) and ('lib' in cls_stg):
return True
else:
return False |
def unique3(s, start, stop):
"""Return True if there are no duplicates elements in slice s[start:stop]."""
if stop - start <= 0: # at most one item
return True
elif not unique3(s, start, stop - 1): # first part has duplicate
return False
elif not unique3(s, start + 1, stop): # second... |
def list_math_addition(a, b):
"""!
@brief Addition of two lists.
@details Each element from list 'a' is added to element from list 'b' accordingly.
@param[in] a (list): List of elements that supports mathematic addition..
@param[in] b (list): List of elements that supports mathematic addi... |
def process_description(description: str):
"""
Function to cut the passed in string before \n\n if any
Parameters
----------
description: str
the passed in string for process
Returns
-------
str
processed string
"""
if not description:
return "No Info Pr... |
def non_negative(number: int) -> int:
"""
:return: Number, or 0 if number is negative
"""
return max(0, number) |
def is_windows_path(path):
"""Checks if the path argument is a Windows platform path."""
return '\\' in path or ':' in path or '|' in path |
def split_section(url):
"""
Splits into (head, tail), where head contains no '#' and is max length.
"""
if '#' in url:
i = url.index('#')
return (url[:i], url[i:])
else:
return (url, '') |
def home():
"""All available api routes."""
return (
f"Available Hawaii Weather Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"api/v1.0/<start><br/>"
f"api/v1.0/<start>/<end>"
) |
def relMatches(rel_attr, target_rel):
"""Does this target_rel appear in the rel_str?"""
# XXX: TESTME
rels = rel_attr.strip().split()
for rel in rels:
rel = rel.lower()
if rel == target_rel:
return 1
return 0 |
def pad(message_len, group_len, fillvalue):
"""Return the padding needed to extend a message to a multiple of group_len
in length.
fillvalue can be a function or a literal value. If a function, it is called
once for each padded character. Use this with fillvalue=random_english_letter
to pad a messa... |
def _load_file(file):
"""Load the log file and creates it if it doesn't exist.
Parameters
----------
file : str
The file to write down
Returns
-------
list
A list of strings.
"""
try:
with open(file, 'r', encoding='utf-8') as temp_file:
return te... |
def listify(item):
"""
listify a query result consisting of user types
returns nested arrays representing user type ordering
"""
if isinstance(item, (tuple, list)):
return [listify(i) for i in item]
else:
return item |
def get_version(v):
"""
Generate a PEP386 compliant version
Stolen from django.utils.version.get_version
:param v tuple: A five part tuple indicating the version
:returns str: Compliant version
"""
assert isinstance(v, tuple)
assert len(v) == 5
assert v[3] in ('alpha', 'beta', 'rc... |
def min_(xs):
"""Returns min element (or None if there are no elements)"""
if len(xs) == 0:
return None
else:
return min(xs) |
def and_sum (phrase):
"""Returns TRUE iff every element in <phrase> is TRUE"""
for x in phrase:
if not x:
return False
return True |
def binary_does_not_exist(response):
"""
Used to figure if the npm, pip, gem binary exists in the container image
"""
if 'executable file not found in' in response or 'not found' in response \
or 'no such file or directory' in response:
return True
return False |
def dead_zone(controller_input, dead_zone):
"""Old-style dead zone scaling, required for similar drive behaviour."""
if controller_input <= dead_zone and controller_input >= -dead_zone:
return 0
elif controller_input > 0:
return ((controller_input-dead_zone)/(1-dead_zone))
else:
... |
def ImportCinema(filename, view=None):
"""::deprecated:: 5.9
Cinema import capabilities are no longer supported in this version.
"""
import warnings
warnings.warn("'ImportCinema' is no longer supported", DeprecationWarning)
return False |
def grid_walk(directions, part_two=False):
"""Return Manhattan distance of destination or first revisited place."""
x = 0
y = 0
orientation = 0
visited = [[0, 0],]
for direction in directions:
turn = direction[0]
steps = int(direction[1:])
if turn == 'R':
ori... |
def get_kwcolors(labels, colors):
"""Generate a dictinary of {label: color} using unique labels and a list of availabel colors
"""
nc = len(colors)
nl = len(labels)
n_repeats = int((nl + nc - 1)/nc)
colors = list(colors)*n_repeats
kw_colors = {l:c for (l,c) in zip(labels, colors)}
r... |
def replace_dict_value(d, bad_val, good_val):
"""
Replaces Dictionary Values whenver bad_val is encountered with good_val
"""
for k,v in d.items():
if v == bad_val:
d[k] = good_val
return d |
def remove_prefix(string: str, prefix: str) -> str:
"""
Removes a prefix substring from a given string
Params:
- `string` - The string to remove the prefix from
- `prefix` - The substring to remove from the start of `string`
Returns:
A copy of `string` without the given `prefix`
"""
... |
def time_string(time_seconds):
"""
Creates a formatted string to express a length of time. Given a value in seconds, the value will
be split into hours, minutes, and seconds based on how long that time period is.
:param time_seconds: A value of time in seconds.
:return: A formatted string expressing... |
def strfind(name: str, ch: str) -> list:
"""Simple function to replicate MATLAB's strfind function"""
inds = []
for i in range(len(name)):
if name.find(ch, i) == i:
inds.append(i)
return inds |
def clean_thing_description(thing_description: dict) -> dict:
"""Change the property name "@type" to "thing_type" and "id" to "thing_id" in the thing_description
Args:
thing_description (dict): dict representing a thing description
Returns:
dict: the same dict with "@type" and "id" keys ar... |
def validate(config):
"""
Validate the beacon configuration
"""
_config = {}
list(map(_config.update, config))
# Configuration for log beacon should be a list of dicts
if not isinstance(config, list):
return False, ("Configuration for log beacon must be a list.")
if "file" not ... |
def getShortestPath(source, target, prev, dist):
"""
Rebuild the shortest path from source to target as a list and its cost
Parameters:
source (int): the vertex choose as source
target (int): the vertex choose as target
prev (dict): a ... |
def dsub_to_api(job):
"""Extracts labels from a job, if present.
Args:
job: A dict with dsub job metadata
Returns:
dict: Labels key value pairs with dsub-specific information
"""
labels = job['labels'].copy() if job['labels'] else {}
if 'job-id' in job:
... |
def nested_combine(*dicts: dict) -> dict:
"""Combine an iterable of dictionaries.
Each dictionary is combined into a result dictionary. For
each key in the first dictionary, it will be overwritten
by any same-named key in any later dictionaries in the
iterable. If the element at that key is a dicti... |
def flatten_list(list_of_lists):
"""Will recursively flatten a nested list"""
if len(list_of_lists) == 0:
return list_of_lists
if isinstance(list_of_lists[0], list):
return flatten_list(list_of_lists[0]) + flatten_list(list_of_lists[1:])
return list_of_lists[:1] + flatten_list(list_of_li... |
def check_game_status(board):
"""Return game status by current board status.
Args:
board (list): Current board state
Returns:
int:
-1: game in progress
0: draw game,
1 or 2 for finished game (winner mark code).
"""
for t in [1, 2]:
for j in... |
def get_image_type(fileName):
"""
Get image type.
:param fileName:
:return:
"""
if fileName.endswith(".jpg"):
return "image/jpeg"
elif fileName.endswith(".png"):
return "image/png" |
def label_index2node(label_index, labels):
"""
returns the high or medium degree node with a given label index
labels contains the output of the label function:
the sorted list of high degree nodes with their labels, and
the sorted list of medium degree nodes with their labels
note that label in... |
def parse_line(line):
"""
line is in the format distance,zipcode,city,state,gender,race,income,price
"""
line = line.strip().split(",")[1:]
# zipcode = str(line[0])
# city = str(line[1])
state = str(line[2])
gender = str(line[3])
race = str(line[4])
income = str(line[5])
pric... |
def get_box_coordinates(box,img_shape):
"""#convert model coordinates format to (xmin,ymin,width,height)
Args:
box ((xmin,xmax,ymin,ymax)): the coordinates are relative [0,1]
img_shape ((height,width,channels)): the frame size
Returns:
(xmin,ymin,width,height): (xmin,ymin,width,hei... |
def pad_base64_str(str):
"""
Pads the base64 string.
"""
missing_padding = len(str) % 4
if missing_padding != 0:
str += '=' * (4 - missing_padding)
return str |
def is_valid_byr(birthyear):
"""Checks for valid Birth Year."""
if birthyear.isdigit() and (1920 <= int(birthyear) <= 2002):
return True
else:
return False |
def guess_DMstep(dt, BW, fctr):
"""Choose a reasonable DMstep by setting the maximum smearing across the
'BW' to equal the sampling time 'dt'.
Inputs:
dt: sampling time (in seconds)
BW: bandwidth (in MHz)
fctr: centre frequency (in MHz)
"""
return... |
def item_default(list_values, arg):
"""
Loops over a list and replaces any values that are None, False or blank
with arg.
"""
if list_values:
return [item for item in list_values if item ]
else:
return [] |
def human_size(bytes):
"""Return number of bytes as string with most appropriate unit."""
if bytes == 0:
return '0 B'
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'YB']
bytes = float(bytes)
i = 0
while bytes >= 1024 and i < (len(suffixes) - 1):
bytes /= 1024.0
i += 1
... |
def get_top_keywords(keywords_dict, top_n):
"""
Used to get the top results to display for keyword filtering
Given a dictionary of keywords as keys and the number of times that keyword is linked to a statement in the search results: {Iraq : 300}
Returns the top n results as as list of pairs, ordered by... |
def split_name(name):
"""
Split a long form name like "Derrick J Schommer" into "Derrick" and "J Schommer".
The Shopify system uses one long name field, where WooCommerce uses 2 fields for
first and last name (and we'll just stuff all the extra letters into the second field
if they have middle init... |
def camelize(name):
"""Turns snake_case name into SnakeCase."""
return ''.join([bit.capitalize() for bit in name.split('_')]) |
def test_none(*args):
"""Returns true if any of the arguments are None."""
for x in args:
if x is None:
return True
return False |
def get_list_elem(obj, idx, dft):
"""
Returns element at index or default
:param obj: list
:param idx: index
:param dft: default value
:return: element
"""
if len(obj) - 1 < idx:
return dft
return obj[idx] |
def to_int(raw_value, default=0):
"""
Safely parse a raw value and convert to an integer.
If that fails return the default value.
:param raw_value: the raw value
:param default: the fallback value if conversion fails
:return: the value as int or None
"""
try:
return int(float(ra... |
def _is_ref(schema):
"""
Given a JSON Schema compatible dict, returns True when the schema implements `$ref`
NOTE: `$ref` OVERRIDES all other keys present in a schema
:param schema:
:return: Boolean
"""
return '$ref' in schema |
def long_tail_reversal(close, open, high, low, trend='up', daily_movement_minimum=0.01):
"""
try to detect if a chandle stick fall in the pattern of a doji, long-shadow and hammer
:daily_movement_minimum: default to 0.01 (1%)
"""
detected = False
mid_point_magnatude_scaling = 0.8
# the move... |
def remap_unbound(input_val, in_from, in_to, out_from, out_to):
"""
Remaps input_val from source domain to target domain.
No clamping is performed, the result can be outside of the target domain
if the input is outside of the source domain.
"""
out_range = out_to - out_from
in_range = in_to ... |
def _TopImprovements(recent_anomalies, num_to_show):
"""Fills in the given template dictionary with top improvements.
Args:
recent_anomalies: A list of Anomaly entities sorted from large to small.
num_to_show: The number of improvements to return.
Returns:
A list of top improvement Anomaly entities,... |
def get_attrname(name):
"""Return the mangled name of the attribute's underlying storage."""
return '_obj_' + name |
def get_phone_number(phone_number):
"""
Following suggested RFC 3966 protocol by open id
expect: +111-1111-111111 format
"""
if '-' in phone_number:
phone_split = phone_number.split('-')
if len(phone_split) > 2:
#if had country code
return phone_split[2]
... |
def is_same_tree(p, q):
"""
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Args:
p: TreeNode
q: TreeNode
Returns:
bool
"""
... |
def degToDMS(g):
"""
Convert degrees into arc units (degrees, (arc)minutes, (arc)seconds)
Parameters
----------
g : float
Value in degrees.
Returns
-------
d, m, s, sign : float, int
Degrees, (arc)minutes, and (arc)seconds. Note that only the
degree numb... |
def list_to_string(l: list, s: str = "\n") -> str:
"""Transforms a list into a string.
The entries of the list are seperated by a seperator.
Args:
l (list): the list
s (str, optional): the seperator. Defaults to "\\n".
Returns:
str: the list representation with seperator
"""
r = ""
f... |
def is_int(data):
"""Checks if data is an integer."""
return isinstance(data, int) |
def find_key(wkt, k):
"""
Find a key in the wkt, return it's name and items.
.. versionadded:: 9.2
"""
for w in wkt:
if type(w) is dict:
if w['key'] == k:
return w['name'], w.get('items', [])
# try the kids
name, items = find_key(w.g... |
def chao1_var_no_doubletons(singles, chao1):
"""Calculates chao1 variance in absence of doubletons.
From EstimateS manual, equation 7.
chao1 is the estimate of the mean of Chao1 from the same dataset.
"""
s = float(singles)
return s*(s-1)/2 + s*(2*s-1)**2/4 - s**4/(4*chao1) |
def drop_nulls_in_dict(d): # d: dict
"""Drops the dict key if the value is None
ES mapping does not allow None values and drops the document completely.
"""
return {k: v for k, v in d.items() if v is not None} |
def get_table_tree(form):
"""return a list consisting of multiple lists"""
table=[]
if len(form) :
while form[0] :
table.append( get_table_tree( form[1:] ) )
form[0]-=1
return table
else :
return [] |
def get_spaceweather_imagefile(if_path, if_date, if_filename, if_extension, \
verbose):
"""Returns a complete image filename string tailored to the spaceweather
site string by concatenating the input image filename (if) strings that
define the path, date, filename root, and the filename extension
... |
def port_status_change(port, original):
"""
Checks whether a port update is being called for a port status change
event.
Port activation events are triggered by our own action: if the only change
in the port dictionary is activation state, we don't want to do any
processing.
"""
# Be de... |
def check_cake_order_sequence(take_out, dine_in, served_orders):
"""Checks that the sequence of served_order is first-come, first-served"""
take_out_index = 0
dine_in_index = 0
for i in range(0, len(served_orders)):
if take_out[take_out_index] == served_orders[i]:
take_out_index +=... |
def subreddit_search_key(sr):
"""Search key for subreddit."""
return sr['name']
# return '{} {}'.format(sr['name'], sr['title']) |
def extract_options(name):
"""
Extracts comparison option from filename.
As example, ``Binarizer-SkipDim1`` means
options *SkipDim1* is enabled.
``(1, 2)`` and ``(2,)`` are considered equal.
Available options: see :func:`dump_data_and_model`.
"""
opts = name.replace("\\", "/").split("/")... |
def is_deriv_in(coll: list):
"""Check to see if there are any derivatives acting on fields in `coll`."""
for f in coll:
if str(f)[0] == "D":
return True
return False |
def formatPages(pages):
"""One or more page numbers or range of numbers, such as 42-111 or 7,41,73-97
or 43+ (the `+' in this last example indicates pages following that don't
form a simple range). To make it easier to maintain Scribe-compatible
databases, the standard styles convert a sing... |
def round_to_odd(x):
"""
:param x: some number (float or int)
:return: nearst odd integer
"""
return int(round((x - 1) / 2) * 2 + 1) |
def convert_symbol(text, l1, l2, quote='"'):
"""convert symbol l1 to l2 if inside quote"""
text2 = ''
inside = False
for c in text:
if c == quote:
inside = not inside
elif c == l1:
if inside:
text2 += l2
else:
text2 += l1
else:
text2 += c
return text2 |
def is_dask_collection(x):
"""Returns ``True`` if ``x`` is a dask collection"""
try:
return x.__dask_graph__() is not None
except (AttributeError, TypeError):
return False |
def to_pairs(object):
"""Converts an object into an array of key, value arrays. Only the object's
own properties are used.
Note that the order of the output array is not guaranteed to be consistent
across different JS platforms"""
return [list(x) for x in object.items()] |
def reverse_iter(lst):
"""Returns the reverse of the given list.
>>> reverse_iter([1, 2, 3, 4])
[4, 3, 2, 1]
>>> import inspect, re
>>> cleaned = re.sub(r"#.*\\n", '', re.sub(r'"{3}[\s\S]*?"{3}', '', inspect.getsource(reverse_iter)))
>>> print("Do not use lst[::-1], lst.reverse(), or reversed(l... |
def calc_timeleft(bytesleft, bps):
""" Calculate the time left in the format HH:MM:SS """
try:
if bytesleft <= 0:
return '0:00:00'
totalseconds = int(bytesleft / bps)
minutes, seconds = divmod(totalseconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours ... |
def get_collection_and_suffix(collection_name):
"""
Lookup collection and suffix based on the name of the collection as used by GEE
Parameters
==========
collection_name: str, GEE name of the collection, eg. 'COPERNICUS/S2'
Returns
=======
collection: str, user-friendly name of the col... |
def to_ymd(s):
"""take a string of the form "YYYY-MM-DD" (or "YYYY"), terurn a tuple (year, month, date) of three integers"""
if not s:
return
s = s + '--'
y = s.split('-')[0]
m = s.split('-')[1]
d = s.split('-')[2]
if y:
y = int(y)
else:
y = None
if m:
... |
def tupleinsert(tpl, val, idx):
""" Return a tuple with *val* inserted into position *idx* """
lst = list(tpl[:idx]) + [val] + list(tpl[idx:])
return tuple(lst) |
def reg2bin(rbeg, rend):
"""Finds the largest superset bin of region. Numeric values taken from hts-specs
Args:
rbeg (int): inclusive beginning position of region
rend (int): exclusive end position of region
Returns:
(int): distinct bin ID for largest superset bin of region
"""... |
def rewrite_attribute_name(name, default_namespace='html'):
"""
Takes an attribute name and tries to make it HTML correct.
This function takes an attribute name as a string, as it may be
passed in to a formatting method using a keyword-argument syntax,
and tries to convert it into a real attribute ... |
def set_digital_out(id, signal):
"""
Function that returns UR script for setting digital out
Args:
id: int. Input id number
signal: boolean. signal level - on or off
Returns:
script: UR script
"""
# Format UR script
return "set_digital_out({:d}, {})\n".format(id, s... |
def _knapsack(weights, capacity):
"""
Binary knapsack solver with identical profits of weight 1.
Args:
weights (list) : list of integers
capacity (int) : maximum capacity
Returns:
(int) : maximum number of objects
"""
n = len(weights)
# sol... |
def _cc(recipient):
"""
Returns a query item matching messages that have certain recipients in
the cc field.
Args:
recipient (str): The recipient in the cc field to match.
Returns:
The query string.
"""
return f"cc:{recipient}" |
def pt_time_estimation(position_0, position_1,
pan_speed=22.5, tilt_speed=6.5, unit=1e-2):
"""
Estimation of time to go from position_0 to position_1
FIXME : Does not take into account forbidden angle, and
rotation direction neither (shortest path is chosen)
wo... |
def normalizeHomogenious(points):
""" Normalize a collection of points in
homogeneous coordinates so that last row = 1. """
for row in points:
row /= points[-1]
return points |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.