content stringlengths 42 6.51k |
|---|
def tile2xystr(tile):
"""indexed from 0"""
return "{:02d},{:02d}".format(tile['x'], tile['y']) |
def sorted_data(data, reversed):
"""
Sorted data by date desc
"""
data_tuple = data['locations']
data_tuple = sorted(data_tuple, key=lambda k: k.get('total', 0), reverse=reversed)
return {
'data': data_tuple,
'total': data['total']
} |
def region_matches_partition(region, partition):
"""
Returns True if the provided region and partition are a valid pair.
"""
valid_matches = [
("cn-", "aws-cn"),
("us-gov-", "aws-us-gov"),
("us-gov-iso-", "aws-iso"),
("us-gov-iso-b-", "aws-iso-b"),
]
for prefix, expected_partition in valid_matches:
if region.startswith(prefix):
return partition == expected_partition
return partition == "aws" |
def cap_feature(s):
"""
Capitalization feature:
0 = low caps
1 = all caps
2 = first letter caps
3 = one capital (not first letter)
"""
if s.lower() == s:
return 0
elif s.upper() == s:
return 1
elif s[0].upper() == s[0]:
return 2
else:
return 3 |
def _no_stop_codon(aa_seq):
""" Returns True if a sequence does not contain a stop codon,
otherwise returns False
"""
if '*' not in aa_seq:
return True
else:
return False |
def get_output_filename(dest_dir, class_name):
"""Creates the output filename.
Args:
dataset_dir: The dataset directory where the dataset is stored.
split_name: The name of the train/test split.
Returns:
An absolute file path.
"""
return '%s/PASCAL3D_%s.tfrecord' % (dest_dir, class_name) |
def find(path, data):
"""
Extract element from nested dictionary given a path using dot notation
Parameters
----------
path : str
Path to nested element using dot notation
E.g. 'NEMSPDCaseFile.NemSpdInputs.RegionCollection.Region'
data : dict
Nested dictionary
Returns
-------
output : list or int or str or float
Value corresponding to path in nested dictionary
"""
keys = path.split('.')
output = data
for key in keys:
output = output[key]
return output |
def get_start_position(grid_data, clue_num):
"""Find the start co-ordinates for a particular clue number in ipuz data."""
for y, row in enumerate(grid_data):
for x, cell in enumerate(row):
if cell == clue_num:
return {'x': x, 'y': y}
return None |
def merge_dict(a, b, path=None):
"""
Merge dict b into a
"""
if not path:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dict(a[key], b[key], path + [str(key)])
else:
continue
else:
a[key] = b[key]
return a |
def merge_dicts(a, b):
"""
Merge dicts a and b, with values in b overriding a
Merges at the the second level. i.e. Merges dict top level values
:return: New dict
"""
c = a.copy()
for k in b:
if k not in c:
c[k] = b[k]
else:
c[k].update(b[k])
return c |
def get_dbtype_from_file_exten(infp):
"""Determine data type from fasta filename extension.
"""
dbtype = None
exten = infp.rsplit('.', 1)[1]
if exten == 'faa':
dbtype = 'prot'
elif exten == 'fna':
dbtype = 'nucl'
elif exten == 'hmmdb':
dbtype = 'prot'
elif exten == 'sql':
dbtype = 'annotations'
assert dbtype is not None, """Could not determine datase type based on
filename extension: %s""" % exten
return dbtype |
def glitter_head(context):
"""
Template tag which renders the glitter CSS and JavaScript. Any resources
which need to be loaded should be added here. This is only shown to users
with permission to edit the page.
"""
user = context.get('user')
rendered = ''
template_path = 'glitter/include/head.html'
if user is not None and user.is_staff:
template = context.template.engine.get_template(template_path)
rendered = template.render(context)
return rendered |
def dsigmoid(x):
"""
return differential for sigmoid
"""
##
# D ( e^x ) = ( e^x ) - ( e^x )^2
# - --------- --------- ---------
# Dx (1 + e^x) (1 + e^x) (1 + e^x)^2
##
return x * (1 - x) |
def _reverse(lst):
"""Return the reverse of lst without mutating lst"""
nlst = lst.copy()
nlst.reverse()
return nlst |
def url_pattern(pattern: str):
"""
Convert a string *pattern* where any occurrences of ``{{NAME}}`` are replaced by an equivalent
regex expression which will assign matching character groups to NAME. Characters match until
one of the RFC 2396 reserved characters is found or the end of the *pattern* is reached.
The function can be used to map URLs patterns to request handlers as desired by the Tornado web server, see
http://www.tornadoweb.org/en/stable/web.html
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters::
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
:param pattern: URL pattern
:return: equivalent regex pattern
:raise ValueError: if *pattern* is invalid
"""
name_pattern = '(?P<%s>[^\;\/\?\:\@\&\=\+\$\,]+)'
reg_expr = ''
pos = 0
while True:
pos1 = pattern.find('{{', pos)
if pos1 >= 0:
pos2 = pattern.find('}}', pos1 + 2)
if pos2 > pos1:
name = pattern[pos1 + 2:pos2]
if not name.isidentifier():
raise ValueError('name in {{name}} must be a valid identifier, but got "%s"' % name)
reg_expr += pattern[pos:pos1] + (name_pattern % name)
pos = pos2 + 2
else:
raise ValueError('no matching "}}" after "{{" in "%s"' % pattern)
else:
reg_expr += pattern[pos:]
break
return reg_expr |
def _key_labels_layout(sign, zero_vals, labels):
""" Format the leaf labels to be shown on the axis. """
layout = {
"tickvals": [sign * zv for zv in zero_vals],
"ticktext": labels,
"tickmode": "array",
}
return layout |
def gcd(a, b):
"""
gcDen(a, b) -> number
A traditional implementation of Euclid's algorithm
for finding the greatest common denominator.
"""
while b > 0:
a, b = b, a % b
return a |
def addND(v1, v2):
"""Adds two nD vectors together, itemwise"""
return [vv1 + vv2 for vv1, vv2 in zip(v1, v2)] |
def camel_to_snake(name: str) -> str:
"""Change name from CamelCase to snake-case."""
return name[0].lower() + \
''.join(['-' + x.lower() if x.isupper() else x for x in name][1:]) |
def addMiddlePoints(p1, p2, n = 2):
""" Function to calculate the middle point between two points
Args:
p1: (Required) set of coordinates of first point
p2: (Required) set of coordinates of second point
n: (Required) number of divisions
"""
x_1 = p1[0]
y_1 = p1[1]
x_2 = p2[0]
y_2 = p2[1]
dx = (x_2 - x_1)/n
dy = (y_2 - y_1)/n
ps = [[x_1,y_1]]
for i in range(1,n):
x = x_1 + i*dx
y = y_1 + i*dy
ps.append([x,y])
ps.append([x_2,y_2])
return ps |
def cloudtrail_network_acl_ingress_anywhere(rec):
"""
author: @mimeframe
description: Alert on AWS Network ACLs that allow ingress from anywhere.
reference_1: http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html
reference_2: http://docs.aws.amazon.com/AWSEC2/
latest/APIReference/API_CreateNetworkAclEntry.html
"""
if rec['detail']['eventName'] != 'CreateNetworkAclEntry':
return False
req_params = rec['detail']['requestParameters']
return (
req_params['cidrBlock'] == '0.0.0.0/0' and
req_params['ruleAction'] == 'allow' and
req_params['egress'] is False
) |
def select_zmws(zmws, min_requested_bases):
"""
>>> select_zmws([], 0)
([], 0)
>>> select_zmws([], 10)
([], 0)
>>> select_zmws([('zmw/1', 1), ('zmw/2', 2), ('zmw/3', 5), ('zmw/4', 7), ('zmw/5', 10), ('zmw/6', 15)], 10)
(['zmw/1', 'zmw/2', 'zmw/3', 'zmw/4'], 15)
>>> select_zmws([('zmw/1', 1), ('zmw/2', 2), ('zmw/3', 5), ('zmw/4', 7), ('zmw/5', 10), ('zmw/6', 15)], 20)
(['zmw/1', 'zmw/2', 'zmw/3', 'zmw/4', 'zmw/5'], 25)
>>> select_zmws([('zmw/1', 1), ('zmw/1', 2), ('zmw/1', 5), ('zmw/1', 7), ('zmw/1', 10), ('zmw/1', 15)], 20)
(['zmw/1', 'zmw/1', 'zmw/1', 'zmw/1', 'zmw/1'], 25)
"""
# Select the first N ZMWs which sum up to the desired coverage.
num_bases = 0
subsampled_zmws = []
for zmw_name, seq_len in zmws:
num_bases += seq_len
subsampled_zmws.append(zmw_name)
if num_bases >= min_requested_bases:
break
return subsampled_zmws, num_bases |
def dev(default):
"""Function which is used by entry points for getting settings for dev environment.
:param default: it is dependency which will be calculated in moment of getting settings from this env.
"""
default['ANSWER'] = 42
return default |
def _extract_error_from_ansible_stderr(stderr: str):
"""
Extract ansible error message from ansible stderr log
>>> this = _extract_error_from_ansible_stderr
>>> this('''
... [WARNING]: conditional statements should not include jinja2 templating
... [DEPRECATION WARNING]: Use errors="ignore" instead of skip. This feature will
... ''')
''
>>> this('''
... [WARNING]: conditional statements should not include jinja2 templating
... ERROR! the role 'monitoring' was not found
... include_role:
... name: monitoring
... ^ here
... [DEPRECATION WARNING]: Use errors="ignore" instead of skip. This feature will
... ''')
"ERROR! the role \'monitoring\' was not found\\n include_role:\\n name: monitoring\\n ^ here\\n"
>>> this('''
... [WARNING]: conditional statements should not include jinja2 templating
... ERROR! the role 'monitoring' was not found
... include_role:
... name: monitoring
... ^ here
... ''')
"ERROR! the role \'monitoring\' was not found\\n include_role:\\n name: monitoring\\n ^ here"
"""
err_start = stderr.find("ERROR!")
if err_start > -1:
err_end = stderr.rfind("[", err_start)
return stderr[err_start:err_end]
return "" |
def ccall_except_check(x):
"""
>>> ccall_except_check(41)
42
>>> ccall_except_check(-2)
-1
>>> ccall_except_check(0)
Traceback (most recent call last):
ValueError
"""
if x == 0:
raise ValueError
return x+1 |
def readdata(file, size):
"""read and return data from file
file: file object with read(size) method
size: read this many bytes
returns: bytes object of data read
raises: EOFError if end of file is encountered before all bytes are read
"""
data = file.read(size)
if len(data) < size:
raise EOFError(
f"Tried to read {size} bytes from file, but there were only {len(data)} "
"bytes remaining"
)
return data |
def tree_normalize(tree):
"""
Takes a list of line segments defining a tree and normalizes them by
making all coordinates positive.
"""
# Find the minimum x and y values
x_vals = [(i[0], i[2]) for i in tree]
x_vals = [item for sublist in x_vals for item in sublist]
y_vals = [(i[1], i[3]) for i in tree]
y_vals = [item for sublist in y_vals for item in sublist]
x_shift = abs(min(x_vals))
y_shift = abs(min(y_vals))
# Add the shift values to each point
new_tree = []
for line in tree:
new_tree.append((
line[0] + x_shift,
line[1] + y_shift,
line[2] + x_shift,
line[3] + y_shift
))
return new_tree |
def clamp(x, x0, x1):
"""Clamp a provided value to be between x0 and x1 (inclusive). If value is
outside the range it will be truncated to the min/max value which is closest.
"""
if x > x1:
return x1
elif x < x0:
return x0
else:
return x |
def list_from_generator(generator_function):
"""Utility method for constructing a list from a generator function"""
ret_val = []
for list_results in generator_function:
ret_val.extend(list_results)
return ret_val |
def skip_trna(entry):
"""
Some tRNAs should not be drawn and need to be skipped.
"""
if 'pseudo' in entry['note'] or entry['isotype'] in ['Undet', 'Sup']:
return True
return False |
def fnv1a_64(string):
""" Hashes a string using the 64 bit FNV1a algorithm
For more information see:
https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
@param string The key to hash
@returns Hashed key
"""
fnv_offset = 0xcbf29ce484222325 # The standard FNV 64 bit offset base
fnv_prime = 0x100000001b3 # The standard FNV 64 digit prime
hash = fnv_offset
uint64_max = 2 ** 64
# Iterate through the bytes of the string, ie the characters
for char in string:
# ord() converts the character to its unicode value
hash = hash ^ ord(char)
hash = (hash * fnv_prime) % uint64_max
return hash |
def parse(arg):
"""Convert a series of zero or more arguments to a string tuple."""
return tuple(arg.split()) |
def ceaser_cipher(text: str, s: int) -> str:
""" Returns the input text in encrypted form """
result = ""
for i in range(len(text)): # Traverse the text
char = text[i]
# Encrypt According to the case
if (char.isupper()):
result += chr((ord(char) + s - 65) % 26 + 65)
elif (char.islower()):
result += chr((ord(char) + s - 97) % 26 + 97)
else: # Do not encrypt non alpha characters
result += char
return result |
def concatenate_url(endpoint, url):
""" concatenate endpoint & url
:param endpoint: the base url for example http://localhost:port/v1
:param url: the target url for example "/dashboard"
:return: concatenated url for example http://localhost:port/v1/dashboard
"""
return "%s/%s" % (endpoint.rstrip("/"), url.rstrip("/")) |
def mean_tuple(*args):
"""Return the mean values along the columns of the supplied values."""
return tuple(sum(x) / len(x) for x in zip(*args)) |
def _WrapLogicOp(op_fn, sentences, ctx, item):
"""Wrapper for logic operator functions.
"""
return op_fn(fn(ctx, item) for fn in sentences) |
def A002275(n: int) -> int:
"""Repunits: (10^n - 1)/9. Often denoted by R_n."""
if n == 0:
return 0
return int("1" * n) |
def make_title(text,underline="="):
"""
Turn a string into a Markdown/rst title
Arguments:
text (str): text to make into title
underline (str): underline character (defaults to
'=')
Returns:
String: title text.
"""
return "%s\n%s" % (text,underline*len(text)) |
def _ToWebSafeString(per_result, internal_cursor):
"""Returns the web safe string combining per_result with internal cursor."""
return str(per_result) + ':' + internal_cursor |
def ip_string_to_int(ipstr):
""" Convert a string IPv4 address to integer"""
if ipstr == '':
return 0
if len(ipstr) > 15: # max len of ipv4 in string (could be less)
#print "Damn:", ipstr
return 0
parts = ipstr.split('.')
return (int(parts[0]) << 24) + (int(parts[1]) << 16) + \
(int(parts[2]) << 8) + int(parts[3]) |
def partition_1(a,l,r):
"""
partition array a[l...r]
Pivot: Always the 1st element of the array
"""
p = a[l]
i = l+1
j = l+1
while j <= r:
if a[j] <= p:
temp = a[j]
a[j] = a[i]
a[i] = temp
i+=1
j+=1
else:
j+=1
temp = a[l]
a[l] = a[i-1]
a[i-1] = temp
return i-1 |
def trimArray(a):
"""Deletes entries which are empty strings in an array."""
return [e for e in a if e != ""] |
def sub(val, char="-"):
"""
Message formatter used to block off sections in log files with visually
distinctive separators. Defined as individual functions to reduce call
length.
Sub: For sub-critical messages, describing things like notes and warnings
.. rubric::
>>> print(msg.mnr("Sub-critical message here"))
OR
>>> logger.info.(msg.sub("Sub-critical message here"))
:type val: str
:param val: formatted message to return
:type char: str
:param char: border character to separate the message from remainder of logs
:rtype: str
:return: formatted string message to be printed to std out
"""
return f"\n{val}\n{char*80}" |
def isImageType(t):
"""
Checks if an object is an image object.
.. warning::
This function is for internal use only.
:param t: object to check if it's an image
:returns: True if the object is an image
"""
return hasattr(t, "im") |
def get_field_or_message(message, field_str):
"""Get the field value or entire message if it is already a leaf."""
data = message
if field_str is not None:
fields = field_str.split('/')
while len(fields) > 0:
field = fields.pop(0)
data = getattr(data, field)
return data |
def getdistname(distribname=None):
"""
Translates probability distribution names into scipy.stats names.
Arguments:
distribname - the distribution name, or None.
Returns:
If distribname is given (and not None), the "scipy.stats" name for
the probability distribution given in distribname, or None if
the probability distribution name is not recognized or supported.
If distribname is not given (or None), returns a list of string
tuples, where the first name in each tuple is the scipy.stats
name, the second name is a "full name" and any other names are
other recognized aliases.
"""
namelist = (
( "beta", "Beta", ),
( "binom", "Binomial", ),
( "cauchy", "Cauchy", ),
( "chi", "Chi", ),
( "chi2", "Chi-Square", ),
( "expon", "Exponential", ),
( "exponweib", "Exponentiated-Weibull", ),
( "f", "F", "Fisher", ),
( "gamma", "Gamma", ),
( "geom", "Geometric", "Shifted-Geometric", ),
( "hypergeom", "Hypergeometric", ),
( "invgamma", "Inverse-Gamma", ),
( "laplace", "Laplace", ),
( "lognorm", "Log-Normal", ),
( "nbinom", "Negative-Binomial", ),
( "norm", "Normal", ),
( "pareto", "Pareto", ),
( "poisson", "Poisson", ),
( "randint", "Random-Integer", "Discrete-Uniform", ),
( "t", "Students-T", ),
( "uniform", "Uniform", ),
( "weibull_min", "Weibull", ),
)
if distribname is None:
return namelist
lcdistname = str(distribname).lower()
# Testing below verifies the above names are all recognized in the following
if lcdistname == "beta":
return "beta"
if (lcdistname == "binom") or (lcdistname == "binomial"):
return "binom"
if lcdistname == "cauchy":
return "cauchy"
if lcdistname == "chi":
return "chi"
if (lcdistname == "chi2") or (lcdistname == "chi-square"):
return "chi2"
if (lcdistname == "expon") or (lcdistname == "exponential"):
return "expon"
if (lcdistname == "exponweib") or (lcdistname == "exponentiated-weibull"):
return "exponweib"
if (lcdistname == "f") or (lcdistname == "fisher"):
return "f"
if lcdistname == "gamma":
return "gamma"
if (lcdistname == "geom") or (lcdistname == "geometric") or (lcdistname == "shifted-geometric"):
return "geom"
if (lcdistname == "hypergeom") or (lcdistname == "hypergeometric"):
return "hypergeom"
if (lcdistname == "invgamma") or (lcdistname == "inverse-gamma"):
return "invgamma"
if lcdistname == "laplace":
return "laplace"
if (lcdistname == "lognorm") or (lcdistname == "log-normal"):
return "lognorm"
if (lcdistname == "nbinom") or (lcdistname == "negative-binomial"):
return "nbinom"
if (lcdistname == "norm") or (lcdistname == "normal"):
return "norm"
if lcdistname == "pareto":
return "pareto"
if lcdistname == "poisson":
return "poisson"
if (lcdistname == "randint") or (lcdistname == "random-integer") or (lcdistname == "discrete-uniform"):
return "randint"
if (lcdistname == "t") or (lcdistname == "students-t"):
return "t"
if lcdistname == "uniform":
return "uniform"
if (lcdistname == "weibull_min") or (lcdistname == "weibull"):
return "weibull_min"
return None |
def getter_name(a):
"""
>>> getter_name('userId')
'getUserId'
"""
return 'get%s%s' % (a[0].upper(), a[1:]) |
def chart_type(arg):
"""
Set the chart type. Valid arguments are anything the chart API understands,
or the following human-readable alternates:
* 'line'
* 'xy'
* 'xy' / 'line-xy'
* 'bar' / 'bar-grouped'
* 'column' / 'column-grouped'
* 'bar-stacked'
* 'column-stacked'
* 'pie'
* 'pie-3d'
* 'venn'
* 'scatter'
* 'map'
"""
types = {
'line': 'lc',
'sparkline': 'ls',
'xy': 'lxy',
'line-xy': 'lxy',
'bar': 'bhg',
'column': 'bvg',
'bar-stacked': 'bhs',
'column-stacked': 'bvs',
'bar-grouped': 'bhg',
'column-grouped': 'bvg',
'pie': 'p',
'pie-3d': 'p3',
'venn': 'v',
'scatter': 's',
'google-o-meter': 'gom',
'map': 't',
}
return {"cht": types.get(arg, arg)} |
def assume(mapping, a, b):
"""assume that a -> b and return the resulting mapping"""
res = {k: v.copy() for k, v in mapping.items()}
res[a] = set(b)
for k, v in res.items():
if b in v and k != a:
v.remove(b)
return res |
def _FirewallSourceRangesToCell(firewall):
"""Comma-joins the source ranges of the given firewall rule."""
return ','.join(firewall.get('sourceRanges', [])) |
def get_filter_value_from_question_option(option):
"""
Processes `option` into a search term value suitable for the Search API.
The Search API does not allow commas in filter values, because they are used
to separate the terms in an 'OR' search - see `group_request_filters`. They
are removed from the field values by the indexer by the Search API itself,
see `dm-search-api:app.main.services.conversions.strip_and_lowercase`.
:return: normalized string value
"""
return (option.get('value') or option.get('label', '')).lower().replace(',', '') |
def name_matches_classpath(cls):
"""
Decorates a class, ensuring that its ``name`` attribute matches its
classpath.
This is useful for providing a convenient way to configure
:py:class:`TriggerTask` subclasses in trigger configurations during
unit tests.
"""
cls.name = '{cls.__module__}.{cls.__name__}'.format(cls=cls)
return cls |
def metric_format(num, unit="s", digits=1, align_unit=False):
# type: (float, str, int, bool) -> str
"""Format and scale output with metric prefixes.
Example
-------
>>> metric_format(0)
'0.0 s'
>>> metric_format(0, align_unit=True)
'0.0 s '
>>> metric_format(0.002, unit='B')
'2.0 mB'
>>> metric_format(2001, unit='B')
'2.0 KB'
>>> metric_format(2001, unit='B', digits=3)
'2.001 KB'
"""
if num is None:
return "<unknown>"
prefix = ""
if (num >= 1.0) or (num == 0.0):
if num >= 1000.0:
num /= 1000.0
for p in ["K", "M", "G", "T", "P", "E", "Z", "Yi"]:
prefix = p
if abs(num) < 1000.0:
break
num /= 1000.0
else:
num *= 1000.0
for p in ["m", "u", "n", "p", "f"]:
prefix = p
if abs(round(num, digits + 3)) >= 1:
break
num *= 1000.0
if (prefix == "") and align_unit:
return ("%." + str(digits) + "f %s ") % (num, unit)
else:
return ("%." + str(digits) + "f %s%s") % (num, prefix, unit) |
def set_device(c):
"""
returns a string for training on cpu or gpu
"""
if c['CPU_ONLY']:
return '/cpu:0'
else:
return '/device:GPU:1' |
def release_object_group(objectGroup: str) -> dict:
"""Releases all remote objects that belong to a given group.
Parameters
----------
objectGroup: str
Symbolic object group name.
"""
return {
"method": "Runtime.releaseObjectGroup",
"params": {"objectGroup": objectGroup},
} |
def FFT(w, s):
""""
w should be a complex numbers such that w^n = 1
where n is the number of elements in the list s
of numbers.
"""
n = len(s)
if n==1: return [s[0]]
f0 = FFT(w*w, [s[i] for i in range(n) if i % 2 == 0])
f1 = FFT(w*w, [s[i] for i in range(n) if i % 2 == 1])
return [f0[j]+w**j*f1[j] for j in range(n//2)] + [f0[j]-w**(j+n//2)*f1[j] for j in range(n//2)] |
def reverse(x: int) -> int:
"""
Given a 32-bit signed integer, reverse digits of an integer.
"""
str_num = str(x)
is_negative = False
if str_num[0] == '-':
is_negative = True
str_num = str_num[1:]
sign = '-' if is_negative else '+'
num = int(sign + "".join(list(reversed(str_num))))
return num |
def multipleNumbers(i):
"""
Function with logic to know if numbers are multiples of 3, 5 or 3 and 5
"""
entry = ''
if i%3 == 0:
entry += 'Three'
if i%5 == 0:
entry += 'Five'
if not entry:
entry += str(i)
return entry |
def mutate_string(string: str, position: int, character: str) -> str:
"""
>>> mutate_string('abracadabra', 5, 'k')
'abrackdabra'
"""
lst = list(string)
lst[position] = character
return ''.join(lst) |
def levenshtein(s1: str, s2: str) -> int:
"""
Compute the Levenshtein edit distance between 2 strings.
Args:
s1 (str): First string
s2 (str): Second string
Returns:
int: Computed edit distance
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = list(range(len(s2) + 1))
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1] |
def black(pixel):
"""
Determinates if a pixel is black
Parameters
----------
pixel(color) : RGB pixel
Returns
-------
bool : T if black || F if not black
"""
if(pixel[0]== 255):
return False
else:
return True |
def getMonth(month):
"""Method to return the month in a number format
Args:
month (string): the month in a string format
Returns:
string: month in the number format
"""
if month == 'Jan':
return '01'
elif month == 'May':
return '05'
elif month == 'Jun':
return '06'
elif month == 'Jul':
return '07'
elif month == 'Aug':
return '08'
elif month == 'Dec':
return '12'
else:
return None |
def FloatDivision(x1, x2):#{{{
"""
Return the division of two values
"""
try:
return float(x1)/x2
except ZeroDivisionError:
return 0.0 |
def update_yeardatatext(value):
"""
Function to update HTML text for Yearly Data Plot
Input: value
Output: html.Div child text
"""
return "Data for year {}".format(value) |
def _fix_package_name(package_name: str) -> str:
"""
Fix the package name so it could be placed in the __init__.py file.
:param package_name: mystery package name.
:type package_name: str
:return: fixed mystery package name.
:rtype: str
"""
# Transform to eligible package name.
fixed_package_name = package_name.replace('-', '_')
# Special case for the 'backports' modules.
if fixed_package_name.startswith('backports_'):
fixed_package_name.replace('_', '.', 1)
return fixed_package_name |
def determine_rad_rad(rxn_muls):
""" determine if reaction is radical-radical
"""
rct_muls = rxn_muls[0]
if len(rct_muls) > 1:
mul1, mul2 = rct_muls
rad_rad = bool(mul1 > 1 and mul2 > 1)
else:
prd_muls = rxn_muls[1]
if len(prd_muls) > 1:
mul1, mul2 = prd_muls
rad_rad = bool(mul1 > 1 and mul2 > 1)
else:
rad_rad = False
return rad_rad |
def to_years(days):
""" Convert days to approximate years and days """
return "{} y {} d".format(int(days/365), days % 365) |
def sexpr2str(e):
"""convert a sexpr into Lisp-like representation."""
if not isinstance(e, list):
return e
return "(" + " ".join(map(sexpr2str, e)) + ")" |
def is_white(r, g, b):
"""
Check if an RGB code is white.
:param r: Red byte.
:param g: Green byte.
:param b: Blue byte.
:return: True if the pixel is white, False otherwise.
"""
if r == 255 and g == 255 and b == 255:
return True
else:
return False |
def mean(F):
"""Return the mean of the Fourier series with coefficients F."""
n = len(F)
mu = F[int(n/2)]
return mu |
def print_columns(objects, cols=3, gap=2):
""" Print a list of items in rows and columns """
# if the list is empty, do nothing
if not objects:
return ""
# make sure we have a string for each item in the list
str_list = [str(x) for x in objects]
# can't have more columns than items
if cols > len(str_list):
cols = len(str_list)
max_length = max([len(x) for x in str_list])
# get a list of lists which each represent a row in the output
row_list = [str_list[i:i+cols] for i in range(0, len(str_list), cols)]
# join together each row in the output with a newline
# left justify each item in the list according to the longest item
output = '\n'.join([
''.join([x.ljust(max_length + gap) for x in row_item])
for row_item in row_list
])
return output |
def units_distance(p, q, distance):
"""
Parameters
----------
p: list
first element is x1 val and second element is y1 value
q: list
first element is x2 val and second element is y2 value
distance: float
what is going to be the upper threshold to calculating distance between p and q
Returns
-------
float:
distance between p and q
"""
a = 1600
b = 1600
rad_0 = 50
rad_1 = 200
rad_2 = 600
rad_3 = 1000
rad_4 = 1400
rad_5 = 1800
point_1 = ((p[0] - a) * (p[1] - b))
point_2 = ((q[0] - a) * (q[1] - b))
if (point_1 < rad_0 * rad_0) and (point_2 < rad_0 * rad_0):
return distance
elif((point_1 > rad_0 * rad_0) and (point_2 > rad_0 * rad_0) and
(point_1 < rad_1 * rad_1) and (point_2 < rad_1 * rad_1)):
return distance + 5
elif((point_1 > rad_1 * rad_1) and (point_2 > rad_1 * rad_1) and
(point_1 < rad_2 * rad_2) and (point_2 > rad_2 * rad_2)):
return distance + 10
elif((point_1 > rad_2 * rad_2) and (point_2 > rad_2 * rad_2) and
(point_1 < rad_3 * rad_3) and (point_2 < rad_3 * rad_3)):
return distance + 15
elif((point_1 > rad_3 * rad_3) and (point_2 > rad_3 * rad_3) and
(point_1 < rad_4 * rad_4) and (point_2 < rad_4 * rad_4)):
return distance + 20
elif((point_1 > rad_4 * rad_4) and (point_2 > rad_4 * rad_4) and
(point_1 < rad_5 * rad_5) and (point_2 < rad_5 * rad_5)):
return distance + 25
elif((point_1 > rad_5 * rad_5) and (point_2 > rad_5 * rad_5)):
return distance + 30
else:
return distance |
def num_sevens(n):
"""Returns the number of times 7 appears as a digit of n.
>>> num_sevens(3)
0
>>> num_sevens(7)
1
>>> num_sevens(7777777)
7
>>> num_sevens(2637)
1
>>> num_sevens(76370)
2
>>> num_sevens(12345)
0
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'num_sevens',
... ['Assign', 'AugAssign'])
True
"""
return str(n).count('7') |
def getIsotropicFactor(tags):
"""
factor to get x_resolution to equal z resolution.
"""
x = tags['x_resolution']
sp = tags['spacing']
return x*sp |
def mean(data):
"""
Return the sample arithmetic mean of data.
"""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data) / float(n) |
def integerize(number):
"""
Check if number is integer, if False make it integer
"""
if isinstance(number,int): return number
if isinstance(number,float):
if number.is_integer(): return int(number)
else: return integerize(number*10) |
def rotate_point(x0, y0, x1, y1, phi):
"""Rotate the coordinates of a point.
Args:
x0 (float) : X coordinate of ceter of rotation.
y0 (float) : Y coordinate of center of rotation.
x1 (float) : X coordinate of point to be rotated.
y1 (float) : Y coordinate of point to be rotated.
phi (float) : Angle of clockwise rotation in radians.
Returns:
Tupple of rotated x and y coordinates.
"""
from numpy import cos, sin
x1r = x0 + (x1-x0)*cos(-phi) - (y1-y0)*sin(-phi)
y1r = y0 + (y1-y0)*cos(-phi) + (x1-x0)*sin(-phi)
return (x1r, y1r) |
def znes_colors(n=None):
"""Return dict with ZNES colors.
Examples
--------
>>> znes_colors().keys() # doctest: +ELLIPSIS
dict_keys(['darkblue', 'red', 'lightblue', 'orange', 'grey',...
Original author: @ckaldemeyer
"""
colors = {
'darkblue': '#00395B',
'red': '#B54036',
'lightblue': '#74ADC0',
'orange': '#EC6707',
'grey': '#BFBFBF',
'dimgrey': 'dimgrey',
'lightgrey': 'lightgrey',
'slategrey': 'slategrey',
'darkgrey': '#A9A9A9'
}
# allow for a dict of n colors
if n is not None:
if n > len(colors):
raise IndexError('Number of requested colors is too big.')
else:
return {k: colors[k] for k in list(colors)[:n]}
else:
return colors |
def get_loc(x:float, domain:list,closest=False):
"""
Returns the indices of the entries in domain that border 'x'
Raises exception if x is outside the range of domain
Assumes 'domain' is sorted!! And this _only_ works if the domain is length 2 or above
This is made for finding bin numbers on a list of bin edges
"""
if len(domain)<=1:
raise ValueError("get_loc function only works on domains of length>1. This is length {}".format(len(domain)))
# I think this is a binary search
min_abs = 0
max_abs = len(domain)-1
lower_bin = int(abs(max_abs-min_abs)/2)
upper_bin = lower_bin+1
while not (domain[lower_bin]<=x and domain[upper_bin]>=x):
if abs(max_abs-min_abs)<=1:
print("{} in {}".format(x, domain))
raise Exception("Uh Oh")
if x<domain[lower_bin]:
max_abs = lower_bin
if x>domain[upper_bin]:
min_abs = upper_bin
# now choose a new middle point for the upper and lower things
lower_bin = min_abs + int(abs(max_abs-min_abs)/2)
upper_bin = lower_bin + 1
assert(x>=domain[lower_bin] and x<=domain[upper_bin])
if closest:
return( lower_bin if abs(domain[lower_bin]-x)<abs(domain[upper_bin]-x) else upper_bin )
else:
return(lower_bin, upper_bin) |
def fact_o(n):
"""
>>> fact_o(5)
120
"""
p= 1
for i in range(2, n+1):
p *= i
return p |
def best_geo_match(possibles, ordered_locations):
"""Pick the dataset from ``possibles`` whose location is first in ``ordered_locations``.
``possibles`` is an interable with the field ``location``.
``ordered_locations`` is a list of locations in sorting order.
Returns an element from ``possibles``, or ``None``.
"""
weights = {y: x for x, y in enumerate(ordered_locations)}
filtered = (obj for obj in possibles if obj["location"] in weights)
ordered = sorted(filtered, key=lambda x: weights[x["location"]])
if ordered:
return ordered[0] |
def find_cols(defline, header_char='='):
"""
return a sorted list of (start, end) indexes into defline that
are the beginning and ending indexes of column definitions
based on a reStructuredText table header line.
Note that this is a braindead simple version that only understands
header_chars and spaces (no other whitespace)
"""
i = 0;
colstarts = []
colends = []
while i < len(defline):
if len(colstarts) <= len(colends):
nextstart = defline.find(header_char, i)
if nextstart >= 0:
colstarts.append(nextstart)
i = nextstart
else:
break
else:
nextend = defline.find(' ',i)
if nextend >= 0:
colends.append(nextend)
i = nextend
else:
colends.append(len(defline))
break
return list(zip(colstarts, colends)) |
def z_inverse(x, mean, std):
"""The inverse of function z_score"""
return x * std + mean |
def is_intersecting(trace, dt1, dt2, timestamp_key):
"""
Check if a trace is intersecting in the given interval
Parameters
-----------
trace
Trace to check
dt1
Lower bound to the interval
dt2
Upper bound to the interval
timestamp_key
Timestamp attribute
Returns
-----------
boolean
Is true if the trace is contained
"""
if trace:
condition1 = dt1 <= trace[0][timestamp_key].replace(tzinfo=None) <= dt2
condition2 = dt1 <= trace[-1][timestamp_key].replace(tzinfo=None) <= dt2
condition3 = trace[0][timestamp_key].replace(tzinfo=None) <= dt1 <= trace[-1][timestamp_key].replace(
tzinfo=None)
condition4 = trace[0][timestamp_key].replace(tzinfo=None) <= dt2 <= trace[-1][timestamp_key].replace(
tzinfo=None)
if condition1 or condition2 or condition3 or condition4:
return True
return False |
def transform_globs_into_regexes(globs):
"""Turns glob patterns into regular expressions."""
return [glob.replace("*", ".*").replace("?", ".") for glob in globs] |
def getFiles(inDirectory):
"""
Reads files from given directory
"""
listOfFiles = list()
from os import walk, path
for root, subFolders, files in walk(u"" + inDirectory):
for eachFile in files:
listOfFiles.append(path.join(root, eachFile))
return listOfFiles |
def index_tuples_log_ces(factor, factors, period):
"""Index tuples for the log_ces production function."""
ind_tups = [("transition", period, factor, rhs_fac) for rhs_fac in factors]
return ind_tups + [("transition", period, factor, "phi")] |
def slice_name_to_components( slice_name ):
"""
Decomposes a slice name into a map of its unique components. This is the
inverse of build_slice_name(). Also handles slice_name's which have been
converted into a path or URL as a prefix.
Takes 1 argument:
slice_name - String specifying the slice's name, as generated by build_slice_name().
Returns 1 value:
slice_map - Dictionary containing the decomposed metadata from slice_name.
Has the following keys:
"experiment": Experiment name
"variable": Variable name
"z_index": XY slice index
"time_step_index": Time step index
"""
slice_components = slice_name.split( "-" )
# handle slice names that have been turned into paths with extensions.
if "." in slice_components[-1]:
slice_components[-1] = slice_components[-1].split( "." )[0]
# map the individual components to their names.
#
# NOTE: we use negative indexing to handle the case where the experiment
# name may contain one or more hyphens.
#
slice_map = {
"experiment": "-".join( slice_components[:-3] ),
"variable": slice_components[-3],
"z_index": int( slice_components[-2].split( "=" )[1] ),
"time_step_index": int( slice_components[-1].split( "=" )[1] )
}
return slice_map |
def map_int(to_int) -> int:
"""Maps value to integer from a string.
Parameters
----------
to_int: various (usually str)
Value to be converted to integer
Returns
-------
mapped_int: int
Value mapped to integer.
Examples
--------
>>> number_one = "1"
>>> error_value = "will cause error"
>>> one_to_float = map_int(number_one) # will convert to 1
>>> error_to_float = map_int(error_value) # will cause exception
"""
try:
mapped_int = int(to_int)
except ValueError:
raise ValueError("Integer Value Expected Got '{}'".format(to_int))
return mapped_int |
def num_full_weekends(x,wkendtype):
"""
Returns number of full weekends (both days) worked in a given weekends worked pattern.
Inputs:
x - list of 2-tuples representing weekend days worked. Each list
element is one week. The tuple of binary values represent the
first and second day of the weekend for that week. A 1 means
the day is worked, a 0 means it is off.
wkend_type - 1 --> weekend consists of Saturday and Sunday
2 --> weekend consists of Friday and Saturday
Output:
Number of full weekends worked
Example:
n = num_full_weekends([(0,1),(1,0),(0,1),(1,0)],1)
# n = 2
n = num_full_weekends([(0,1),(1,0),(0,1),(0,0)],1)
# n = 1
n = num_full_weekends([(1,1),(1,0),(1,1),(1,0)],2)
# n = 2
n = num_full_weekends([(0,1),(1,0),(0,1),(0,0)],2)
# n = 0
"""
if wkendtype == 2:
L1 = [sum(j) for j in x]
n = sum([(1 if j == 2 else 0) for j in L1])
else:
n = 0
for j in range(len(x)):
if j < len(x) - 1:
if x[j][1] == 1 and x[j+1][0] == 1:
n += 1
else:
if x[j][1] == 1 and x[0][0] == 1:
n += 1
return n |
def listmofize(x):
"""
Return x inside a list if it isn't already a list or tuple.
Otherwise, return x.
>>> listmofize('abc')
['abc']
>>> listmofize(['abc', 'def'])
['abc', 'def']
>>> listmofize((1,2))
(1, 2)
"""
if not isinstance(x, (list, tuple)): return [x]
else: return x |
def generate_single_type_function_pointer_declarations(functions):
"""
Generate lines "extern tFoo foo_impl;"
"""
if not functions:
return []
lines = []
suffix = "_impl" if functions[0].type == 'WRAPPER' else ""
for function in functions:
line = "extern t{} {}{};" . format(function.name, function.name, suffix)
lines.append(line)
return lines |
def hamming_distance(s1, s2):
"""return the Hamming distance b/t equal-length sequences
"""
if len(s1) != len(s2):
raise ValueError("undefined for sequences of unequal length")
result = sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
return (len(s1) - result) / len(s1) |
def cross_product(u, v):
"""returns the cross product (vector) of vectors u and v"""
if len(u) == len(v) == 3:
return (u[1]*v[2] - u[2]*v[1],
u[2]*v[0] - u[0]*v[2],
u[0]*v[1] - u[1]*v[0])
else:
print('Cross product not calculated: dimension mismatch')
return None |
def MakeMajorChords(n_semis, base_i):
"""Given a count of notes ascending by semitones, and an index into
that (virtual) array, generate indices to the notes, including all
extensions and reflections that can comprise the major chord based
on the indexed semitone. Return an array of indices of these notes.
"""
chord = []
skips = [4, 3, 5]
base_i = base_i % 12
if (base_i - 8) >= 0:
ind = base_i - 8
skipi = 1
elif (base_i - 5) >= 0:
ind = base_i - 5
skipi = 2
else:
ind = base_i
skipi = 0
while ind < n_semis:
chord.append(ind)
ind += skips[skipi]
skipi = (skipi + 1) % len(skips)
return chord |
def is_parameter(value):
"""Returns True if the given value is a reference to a template parameter.
Parameters
----------
value: string
String value in the workflow specification for a REANA template
Returns
-------
bool
"""
# Check if the value matches the template parameter reference pattern
return value.startswith('$[[') and value.endswith(']]') |
def str_replace(string, value, new_value, occurences = -1):
"""
Replaces the value of `value` to `new_value` in `string`.
If occurences is defined, will only replace the first n occurences. A negative value replaces all values.
"""
return string.replace(value, new_value, occurences) |
def int2fl(x, deci=3):
"""
Convert integer to floating point number.
"""
return round(float(x / pow(10, deci)), int(deci)) |
def _is_x_first_dim(dim_order):
"""Determine whether x is the first dimension based on the value of dim_order."""
if dim_order is None:
dim_order = 'yx'
return dim_order == 'xy' |
def subtract_offset(sequence, offset):
"""Subtracts an offset from the sequence number while considering wraparound"""
new_sequence = sequence - offset
if new_sequence < 0:
new_sequence += 0x100000000
return new_sequence |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.