content stringlengths 42 6.51k |
|---|
def fix_epoch(epoch):
"""
Fix value of `epoch` to be epoch, which should be 10 or fewer digits long.
:arg epoch: An epoch timestamp, in epoch + milliseconds, or microsecond, or
even nanoseconds.
:rtype: int
"""
try:
# No decimals allowed
epoch = int(epoch)
except Exc... |
def res_pairs(num_res, nearn):
"""
computes res-res pairs included for which to calculate minimum distance features
state num of residues, and nearest neighbour skip e.g. i+3 is nearn=3
"""
res=[]
for i in range(num_res-nearn):
for j in range(i+nearn,num_res):
res.append([i+1... |
def format_ISO_time(year,doy,timestr):
"""
Format an ISO-like time string: YYYY-DDDTHH:MM
@param year : 4-digit year
@type year : str
@param doy : 3-digit day of year
@type doy : str
@param timestr : HHMM
@type timestr : str
@return: str
"""
return year + '-' + doy + 'T' + timestr[0:2] + ':... |
def to_martial(hora, meridian):
"""
Regresa la hora en formato militar
"""
if meridian == 'PM':
if int(hora) < 12:
return hora + 12
else:
return hora
else:
return hora |
def _log10_lb(c, correction={'1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
'6': 23, '7': 16, '8': 10, '9': 5}):
"""Compute a lower bound for 100*log10(c) for a positive integer c."""
if c <= 0:
raise ValueError('The argument to _log10_lb should be nonnegative.')
str_c = str(c)
return 100 * l... |
def mean(a):
""" Same as np.mean """
return (a[0]+a[1])/2 |
def flatten(l):
"""Flattens a list into 1-dimension"""
return flatten(l[0]) +\
(flatten(l[1:]) if len(l) > 1 else []) if type(l) is list else [l] |
def _strtobool(value: str) -> bool:
"""Return the boolean value encoded in the string"""
value = value.lower()
if value == "true":
return True
if value == "false":
return False
raise ValueError(f"invalid truth value {value!r}") |
def dict2str(dict_):
"""
Create string from Python dictionary.
Parameters
----------
dict_ : dict (str : str)
Returns
-------
str
joined 'key' 'value' pairs separated by space
"""
return " ".join([f'{k} {v}' for k, v in dict_.items()]) |
def seconds_to_str(value):
"""Convert seconds to a simple simple string describing the amount of time."""
mins, secs = divmod(value, 60)
hours, mins = divmod(mins, 60)
if value < 60:
return f"{secs} second{'s' if secs != 1 else ''}"
elif value < 3600:
return f"{mins} minute{'s' if m... |
def parse_uri(uri):
"""Extracts the host, port and db from an uri"""
host, port, db = uri, 6379, 0
if len(host.split('/')) == 2:
host, db = host.split('/')
if len(host.split(':')) == 2:
host, port = host.split(':')
return host, int(port), int(db) |
def get_schema_obj(obj_id, schema):
"""Search the schema graph for an object with the given ID."""
matches = [obj for obj in schema['@graph'] if obj['@id'] == obj_id]
return matches[0] if len(matches) == 1 else None |
def filter_paths(paths):
"""
Removes paths with repetitions, useful for e.g.
handling ascending order conversion.
"""
paths_without_repetitions = []
for path in paths:
if len(set(path)) == len(path):
paths_without_repetitions.append(path)
return paths_without_repetition... |
def _join_shellwords(seq):
"""
Joins a sequence together, parsable https://github.com/mattn/go-shellwords
This exists because buildah config --cmd uses it
"""
# FIXME: Handle ' in items
return " ".join(f"'{s}'" for s in seq) |
def snpReplace(start,alt,seq):
"""
replace reference with snp sites
"""
seq = list(seq)
seq[start] = alt
seq = ''.join(seq)
return seq |
def gcd_modulus(a, b):
"""finds the GCD of a and b
Args:
a, b: non-negative integers
Returns:
int: the GCD of a and b
"""
while b != 0:
a, b = b, a % b
return a |
def build_db_path(package, db):
"""
Build the full device path for a package's database
:param package: The package's name
:param db: The database's name
"""
if db.endswith('.db'):
db = db.rsplit('.', 1)[0]
return '/data/data/{package}/databases/{db}.db'.format(package=package, db=d... |
def connstr_to_dsn(connstring=''):
"""Convert a dict with dsn params to a connstring."""
if not connstring:
return {}
connstring = connstring.strip()
parts = [kv.split('=', 1) for kv in connstring.split(' ')]
return {part[0]: part[1] for part in parts} |
def strtobool(input):
"""
strtobool Convert string to boolean
Parameters
----------
input : str
String to convert into boolean
Returns
-------
bool
Result of the conversion
"""
return input.lower() in ('true', '1', 't') |
def newGame(game):
"""Get a new game from specified attributes"""
game['players'] = {}
game['graveyard'] = []
game['winner'] = 'NONE'
return game |
def extract_jira_project(obj):
"""returns a list containing lists of the form [project key, project name]
"""
arr = []
def extract_jira(obj, arr):
if isinstance(obj, dict):
proj = []
for k, v in obj.items():
if k == 'key' or k == 'name':
... |
def new_path(path, paths):
"""
check if struc is already in the reference solutions
"""
for ref in paths:
if path[:len(ref)] == ref:
return False
return True |
def quote_plus(s):
"""
Convert some URL elements to be HTTP-safe.
Not the same as in urllib, because, for instance, parentheses and commas
are passed through.
Parameters
----------
s: input URL/portion
Returns
-------
corrected URL
"""
s = s.replace('/', '%2F')
s =... |
def _follow_path(json_data, json_path):
"""Get the value in the data pointed to by the path."""
value = json_data
for field in json_path.split("."):
value = value[field]
return value |
def cap(v, l):
"""Shortens string is above certain length."""
s = str(v)
return s if len(s) <= l else s[-l:] |
def conv(ip):
"""
Converts IP integer to human readable IP address
:param ip: integer IP Address in int form
:return: string IP Address
"""
return "%d.%d.%d.%d" % (
(ip >> 24) & 255,
(ip >> 16) & 255,
(ip >> 8) & 255,
ip & 255,
) |
def get_base_file(filepath):
"""
Returns the Base file from a filepath
"""
filepath = filepath.split(".")[0]
flist = filepath.split("/")
if (len(flist) == 2):
return flist[1]
else:
return flist[0] |
def _trim(template: str) -> str:
"""
Cleaning SQL statements
:param template: SQL statement to be cleaned
:return: Cleaning result
"""
template = template.strip()
template = template.replace("\n", " ")
template = template.replace("\t", " ")
template = template.replace("\r", " ")
... |
def default_parameter_f(x, y=3):
""" default_parameter_f """
z = x + y
return z |
def _to_jsonc_name(member_name):
"""Converts a Python style member name to a JSON-C style name.
JSON-C uses camelCaseWithLower while Python tends to use
lower_with_underscores so this method converts as follows:
spam becomes spam
spam_and_eggs becomes spamAndEggs
Args:
member_name: str ... |
def _LJ_ab_to_epsilonsigma(coeffs):
"""
Convert AB representation to epsilon/sigma representation of the LJ
potential
"""
if (coeffs['A'] == 0.0 and coeffs['B'] == 0.0):
return {"sigma": 0.0, "epsilon": 0.0}
try:
sigma = (coeffs['A'] / coeffs['B'])**(1.0 / 6.0)
epsilon =... |
def strip_whitespace(content):
"""Strip whitespace from an input list.
Take a list as input and strip whitespace from each entry.
Args:
content (list): The input list
Returns:
The input list without whitespaces.
Example:
>>> from base64_rot13_decode import strip_whitespac... |
def escape_cdata(data, encoding):
"""Escape character data using the given encoding."""
if "&" in data:
data = data.replace("&", "&")
if "<" in data:
data = data.replace("<", "<")
if ">" in data:
data = data.replace(">", ">")
return data.encode(encoding, "xmlcharref... |
def get_suits(cards):
"""
Returns a list of strings containing the suit of each card in cards.
ex.
get_ranks(['2S','3C','5C','4D','6D'])
returns ['S','C','C','D','D']
"""
return [card[-1] for card in cards] |
def imt_check(grade_v, grade_i, grade_j):
"""
A check used in imt table generation
"""
# A_r . B_s = <A_r B_s>_|r-s|
# if r, s != 0
return (grade_v == abs(grade_i - grade_j)) and (grade_i != 0) and (grade_j != 0) |
def parse_stage_config(stage_cfg):
"""Parse config of STPP for three stages.
Args:
stage_cfg (int | tuple[int]):
Config of structured temporal pyramid pooling.
Returns:
tuple[tuple[int], int]:
Config of structured temporal pyramid pooling and
total numbe... |
def get_start(encounter):
"""
get start date from encounter
:param encounter:
:return:
"""
if 'period' in encounter:
if 'start' in encounter['period']:
return encounter['period']['start']
return |
def shift_rank(ranks):
"""
Shifts all scores by translations, so that the minimum is in zero
and the others are all positive
"""
min_r = min(ranks)
N = len(ranks)
for i in range(N):
ranks[i] = ranks[i] - min_r
return ranks |
def recursive_binomial_coefficient(n, k):
"""Calculates the binomial coefficient, C(n,k), with n>=k using recursion
Time complexity is O(k), so can calculate fairly quickly for large values of k.
>>> recursive_binomial_coefficient(5,0)
1
>>> recursive_binomial_coefficient(8,2)
28
>>> recu... |
def aggregate_f(
loc_fscore, length_acc, vessel_fscore, fishing_fscore, loc_fscore_shore
):
"""
Compute aggregate metric for xView3 scoring
Args:
loc_fscore (float): F1 score for overall maritime object detection
length_acc (float): Aggregate percent error for vessel length estimation
... |
def rectarea(r, incborder=1):
"""Returns the area of the given ``(x0, y0, x1, y1)`` rect.
If `incborder` is true (default) then includes that in calc. Otherwise doesn't.
If either width or height is not positive, returns 0."""
w = r[2]-r[0] + incborder
h = r[3]-r[1] + incborder
if w <= 0 or h <=... |
def smallest_prime_factor(x):
"""Returns the smallest prime number that is a divisor of x"""
# Start checking with 2, then move up one by one
n = 2
while n <= x:
if x % n == 0:
return n
n += 1 |
def realtime_format(seconds):
"""
As gametime format, but with real time units
"""
sec = int(seconds)
years, sec = sec/29030400, sec % 29030400
months, sec = sec/2419200, sec % 2419200
weeks, sec = sec/604800, sec % 604800
days, sec = sec/86400, sec % 86400
hours, sec = sec/3600, sec... |
def get_fontext_synonyms(fontext):
"""
Return a list of file extensions extensions that are synonyms for
the given file extension *fileext*.
"""
return {
'afm': ['afm'],
'otf': ['otf', 'ttc', 'ttf'],
'ttc': ['otf', 'ttc', 'ttf'],
'ttf': ['otf', 'ttc', 'ttf'],
}[fo... |
def _is_error_(code):
"""
Default status error checking
"""
code = str(code) if isinstance(code, int) else code
return code.startswith("5") or code.startswith("4") |
def get_nested(d, path, delimiter="/"):
"""
Address nested dicts via combined path
"""
def item_by_tag(d, tags):
# print(">>>>>>>>>>>>>> running nested", d, tags)
t = tags[-1]
child = d[t]
if len(tags) == 1:
return child
return item_by_tag(child, tags[... |
def combine_permutations(p1, p2):
""" p2 is applied first, then p1. """
p = tuple(map(p2.__getitem__, p1))
return p |
def twos_comp(val, bits):
"""compute the 2's complement of int `val`."""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is |
def _check_nfft(n, n_fft, n_overlap):
"""Helper to make sure n_fft and n_overlap make sense."""
n_fft = n if n_fft > n else n_fft
n_overlap = n_fft - 1 if n_overlap >= n_fft else n_overlap
return n_fft, n_overlap |
def json_escape(s):
"""
Escape JSON predefined sequences
"""
if isinstance(s, bool):
return "true" if s else "false"
if s is None:
return ""
return s.replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"') |
def n_dim_rc_combined(k):
""" Return the number of dimensions, for a given k, for the unique k-mer counts (forward - reverse complement) """
return 2**k + (4**k - 2**k)//2 if k % 2 == 0 else 4**k // 2 |
def env_lookup(env, var_name):
"""Function used by 'source' nodes in ExprNode graphs to model var lookup."""
try:
return env[var_name]
except KeyError:
raise NameError("Name '{}' is not defined in environment with names {}"
.format(var_name, env.keys())) |
def gallery_name(f):
"""Takes 'gallery/demo.js' -> 'demo'"""
return f.replace('gallery/', '').replace('.js', '') |
def get_unique_envs(envs):
"""extract all unique envs from envs dict"""
result = set()
for v in envs.values():
result.update(v.keys())
#sort envs for convenience in testing and display
return sorted(result), len(result) |
def teacher_comment(test_score):
"""
This function takes an <int> test score and returns a teacher comment based on the score.
Returns a string teacher comment
"""
if test_score > 90:
return 'Great Job'
elif test_score > 80:
return 'Pretty good'
else:
return 'You cou... |
def _soft_light(a, b):
"""
:type a: ImageMath._Operand
:type b: ImageMath._Operand
:rtype: ImageMath._Operand
"""
_cl = (a / 255) ** ((255 - b) / 128) * 255
_ch = (a / 255) ** (128 / b) * 255
return _cl * (b < 128) + _ch * (b >= 128) |
def funcname(func):
"""Get the name of a function."""
while hasattr(func, 'func'):
func = func.func
return func.__name__ |
def parseBoolean (b):
"""
http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python
"""
# Handle case where b is already a Boolean type.
if b == False or b == True:
return b
b = b.strip()
if len(b) < 1:
raise ValueError ('Cannot parse empty... |
def getxmltagname(tag_name: str) -> str:
"""Transform tag names."""
if tag_name == "source":
return "Source"
elif tag_name == "funcdeclaration":
return "Function"
elif tag_name == "classdeclaration":
return "Class"
elif tag_name == "vardeclaration":
return "Variable"
... |
def manhattan(rating1, rating2):
"""Computes thte Manhattan distance"""
distance = 0
for key in rating1:
if key in rating2:
distance += abs(rating1[key] - rating2[key])
return distance |
def layer_uid(use_spatial_hash, spatial_hash_cell_size):
"""
create a number that will always be unique for a spritelist with
the given properties.
"""
uid = spatial_hash_cell_size << use_spatial_hash
return uid |
def gridsize(nf):
"""
Fuzzy logic to determine optimal gridsize from full screen proportion
"""
col_row = [ [2,2], [2,3], [3,2], [3,3], [3,4], [4,3], [4,4],
[4,5], [5,4], [5,5], [5,6], [6,5], [6,6], [7,6], [6,7], [7,7], [8,7], [7,8], [8,8], [9,8], [8,9], [9,9] ]
c=9
r=9
for cr, rr in co... |
def _process_opt(opt):
"""
Helper function that extracts certain fields from the opt dict and assembles the processed dict
"""
return {'gelfhttp': opt.get('gelfhttp'),
'port': str(opt.get('port', '12022')),
'custom_fields': opt.get('custom_fields', []),
'sourcetype': ... |
def error500(error):
"""
handling 500 error
"""
return "Sorry! There's a bug. Try going back to homepage and reloading", 500 |
def page_exists(request_dict):
"""
Checks if page exists given the parsed request body
Parameters
----------
request_dict : dict
request output after parsing
Returns
-------
bool
if the page exists
"""
if 'error' in request_dict: # when using parse
rais... |
def specialsum(a,b):
""" make the sum of two variables
Parameters
-----------------
a = double(required)
first value to be summed
b = double(required)
second value to be summed
Returns
---------------
sum of two numbers
"""
results = a + b
return results |
def decode(s):
"""doc me"""
for encoding in "utf-8-sig", "utf-16":
try:
return s.decode(encoding)
except UnicodeDecodeError:
continue
return s.decode("latin-1") |
def mailer_obfuscate_email(email):
""" Helper functie om een email adres te maskeren
voorbeeld: nhb.ramonvdw@gmail.com --> nh####w@gmail.com
"""
try:
user, domein = email.rsplit("@", 1)
except ValueError:
return email
voor = 2
achter = 1
if len(user) <= 4:
voo... |
def inOrOut(coord):
"""
Take x,y coord and return "inside" if it's within the 6000x4000 image
Else, return "outside"
"""
x,y = coord
if 0 <= x <= 6000 and 0 <= y <= 4000:
return "inside"
else:
return "outside" |
def attemptedCredits(classes):
"""Calculates the number of credits a student attempted.
:param dict classes:
The class information. Format:
classes = {className: {"grade": grade, "credits",
numCredits}}
:return:
The number of credits the student attempted.
:rtype... |
def menu_toggle(n_clicks: int) -> dict:
"""
Args:
n_clicks:
Returns:
"""
if n_clicks and n_clicks % 2 == 1:
return {"display": "block"}
return {"display": "none"} |
def s3_read_write_policy_in_json(s3_bucket_name):
"""
Define an IAM policy statement for reading and writing to S3 bucket.
:return: an IAM policy statement in json.
"""
return {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"... |
def average_above_zero(tab):
"""
brief: computes the average of the positve values of a array
Args:
tab :a list of numeric value, expects at least one positive values, raise Exception if not
Returns:
the computed average as a float value
Raises:
ValueError if no positive va... |
def root_utility(x: float, exp: float = 2.0, mult: float = 3) -> float:
"""
A simple root utility function with u(x) = x**1/exp;
by default the quadratic root is used and loss aversion means
that losses are evaluated as 3 times as high as wins.
"""
return x ** (1 / exp) if x > 0 else -mult * (... |
def check_numbers(phrase):
"""Functions checks if the given phrase has numbers in it
Arguments
---------
phrase -- string
"""
return any(char.isdigit() for char in phrase) |
def _extract_param(arg, name):
"""Extract a parameter in the style of "key=value".
Return `''` if the `arg == name`,
:obj:`None` if the key does not match name,
value otherwise (might be `''`).
"""
if arg.startswith(name):
param = arg[len(name):]
if param == '':
... |
def float_to_1000(value):
""" convert float value into fixed exponent (8) number
returns 16 bit integer, as value * 256
"""
value = int(round(value*1000,0))
return value & 0xffff |
def find_number_of_pages_in_invoice(filename, data):
"""
This function will simply return the number of pages in the document OCR
:param filename: The name of the file that we are processing
:param data: The OCR for the record in question
:return: A json object with the fields and corresponding bou... |
def make_safe_label(label):
"""Avoid name clashes with GraphViz reserved words such as 'graph'."""
unsafe_words = ("digraph", "graph", "cluster", "subgraph", "node")
out = label
for word in unsafe_words:
out = out.replace(word, "%sX" % word)
return out.replace(".", "__").replace("*", "") |
def compute_bytes_per_voxel(file_data_type):
"""Returns number of bytes required to store one voxel for the given
ElementType """
switcher = {
'VolumeDataType_Float': 4
}
return switcher.get(file_data_type, 2) |
def _wrap_add(x, y, a, b):
"""add x+y modulu the answer being in range [a...b[
https://stackoverflow.com/a/51467186/271776
"""
y %= b - a
x = x + y
return x - (b - a) * (x >= b) |
def structure(status="", msg=""):
"""
basic JSON message structure
Args:
status: status (ok, failed)
msg: the message content
Returns:
a JSON message
"""
return {
"status": status,
"msg": msg
} |
def is_named_tuple(cls):
"""Return True if cls is a namedtuple and False otherwise."""
b = cls.__bases__
if len(b) != 1 or b[0] != tuple:
return False
f = getattr(cls, "_fields", None)
if not isinstance(f, tuple):
return False
return all(type(n) == str for n in f) |
def _or_types(field):
"""Return all the types in a doclet subfield like "params" or "returns"
with vertical bars between them, like "number|string"."""
return '|'.join(field.get('type', {}).get('names', [])) |
def check_table(table):
"""
Ensure the table is valid for converting to grid table.
* The table must a list of lists
* Each row must contain the same number of columns
* The table must not be empty
Parameters
----------
table : list of lists of str
The list of rows of strings t... |
def expand_range(rangeString):
"""
Turns page ranges into lists of pages.
E.g. turns 3-6 into [3, 4, 5, 6]
"""
s, e = [int(i) for i in rangeString.split('-')]
return list(range(s, e + 1)) |
def bitstring_to_number(bitstring):
"""
Convert a bitstring to a number.
E.g. ``10110101`` gives 181.
Args:
bitstring (str): String of ``1``\ s and ``0``\ s.
Returns:
int: The equivalent integer.
"""
return int(bitstring, 2) |
def combine_spans(span1, span2):
"""Merge two text span dictionaries
"""
new_span = {}
new_span['CharacterSpanList'] = span1['CharacterSpanList'] + \
span2['CharacterSpanList']
new_span['SpanList'] = span1['SpanList'] + span2['SpanList']
new_span['RawText'] = span1['RawText'] + span2['R... |
def remove_whitespace(tokens):
"""Remove any top-level whitespace and comments in a token list."""
return tuple(
token for token in tokens
if token.type not in ('whitespace', 'comment')) |
def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float:
"""
Convert a given value from Rankine to Celsius and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
"""
return round((ran... |
def toHex(input, remove=False):
"""
Transforms an input to hexadecimal.
:param input: Any input that can be transformed to hexadecimal.
:param remove: Boolean to remove "0x" from the output
:return: An hexadecimal number.
"""
if remove:
return str(hex(input))[2:]
else:
re... |
def full_community_name(community):
"""Combine community name with alt_name if it exists"""
if "alt_name" in community:
return "{0} ({1})".format(community["name"], community["alt_name"])
return community["name"] |
def reverse_num(num):
"""Returns an integer
Reverse of a number passed as argument
"""
rev = 0
while num > 0:
rev = (rev * 10) + (num % 10)
num //= 10
return rev |
def add_series_to_info_dict(series_id, mykey, info, acq=''):
""" adds a series to the 'info' dictionary """
if info is None or mykey == '':
return Exception
if mykey in info:
if acq == '':
info[mykey].append({'item': series_id})
else:
info[mykey].append({'it... |
def denormalize(tensor, stats):
"""
denormalize a tensor using a running mean and std
:param tensor: (TensorFlow Tensor) the normalized tensor
:param stats: (RunningMeanStd) the running mean and std of the input to normalize
:return: (TensorFlow Tensor) the restored tensor
"""
if stats is N... |
def short_message(message: str) -> str:
"""Return the first line of a message"""
return message.split("\n")[0] |
def mult(A, B):
"""matrix multiplication
"""
zipB = list(zip(*B))
return [[sum(a*b for a,b in zip(Ar,Bc)) for Bc in zipB] for Ar in A] |
def goobar08_law(lbd, lbdref, a, p):
"""
Goobar 08 extinction law.
From `Goobar08 <http://adsabs.harvard.edu/abs/2008ApJ...686L.103G>`_, *Low
R_V from Circumstellar Dust around Supernovae*
"""
return 1. - a + a * (lbd / lbdref) ** p |
def feca2leca(leaves):
"""Determines if clade fulfills FECA-2-LECA criteria: both sides of the root present"""
root_daughter_groups = set()
for leaf in leaves:
root_daughter_groups.add(leaf.root_daughter)
if len(root_daughter_groups) == 2:
break
else:
return False
... |
def ToBytes(string):
"""Convert a str type into a bytes type
Args:
string: string to convert
Returns:
A bytes type
"""
return string.encode('utf-8') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.