content stringlengths 42 6.51k |
|---|
def rest(s):
"""Return all elements in a sequence after the first"""
return s[1:] |
def instances_security_groups(instances):
"""
Return security groups associated with instances.
:param instances: list of ec2 instance objects
:type instances: list
:return: list of dicts with keys GroupId and GroupName
:rtype: list
"""
# we turn the groups into frozensets to make them hashable,
# so we can use set to deduplicate.
# On the way out, we turn them back into dicts.
unique = set(
frozenset(group.items())
for instance in instances
for group in instance["SecurityGroups"]
)
return [dict(group) for group in unique] |
def parse_dist_text(text: str) -> float:
"""
"""
try:
return float(text[:-3])
except ValueError:
for i in range(0, -11, -1):
try:
return float(text[:i])
except ValueError:
continue
else:
raise ValueError('Unable to parse distance from string') |
def factorial_r(number):
"""
Calculates the factorial of a number, using a recursive process.
:param number: The number.
:return: n!
"""
# Check to make sure the argument is valid.
if number < 0:
raise ValueError
# This is the recursive part of the function.
if number == 0:
# If the argument is 0, then we simply return the value of 0!, which is 1.
return 1
else:
# Otherwise, return n multiplied by the (n - 1)!
return number * factorial_r(number - 1) |
def set_config_var(from_file, from_env, default):
"""
Set a configuration value based on the hierarchy of:
default => file => env
:param from_file: value from the configuration file
:param from_env: value from the environment
:param default: default configuration value
:return: value to use as configuration
"""
if from_env is not None:
return from_env
elif from_file is not None:
return from_file
else:
return default |
def rwh_primes1(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Returns a list of primes < n """
sieve = [True] * (n // 2)
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i // 2]:
sieve[i * i // 2 :: i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]] |
def get_imageurl(img):
"""Get the image url helper function."""
result = 'https://www.buienradar.nl/'
result += 'resources/images/icons/weather/30x30/'
result += img
result += '.png'
return result |
def prev_heart_rate(patient):
"""Gives list of all posted heart rates for a patient
Method curated by Braden Garrison
The accepted patient database is analyzed to produce a list of
all previously posted heart rates for that patient.
Args:
patient (dict): accepts patient dict containing all patient info
Returns:
list: all heart rate values stored in specified patient database
"""
if len(patient["HR_data"]) == 0:
return "ERROR: no heart rate values saved for patient"
else:
hr_list = []
for x in patient["HR_data"]:
hr_list.append(x["heart_rate"])
return hr_list |
def add_default_module_params(module_parameters):
"""
Adds default fields to the module_parameters dictionary.
Parameters
----------
module_parameters : dict
Examples
--------
>> module = add_default_module_params(module)
Returns
-------
module_parameters : dict
Same as input, except default values are added for the following fields:
'Mbvoc' : 0
'FD' : 1
'iv_model' : 'sapm'
'aoi_model' : 'no_loss'
"""
if not 'Mbvoc' in module_parameters:
module_parameters['Mbvoc'] = 0
if not 'FD' in module_parameters:
module_parameters['FD'] = 1
if not 'iv_model' in module_parameters:
module_parameters['iv_model'] = 'sapm'
if not 'aoi_model' in module_parameters:
module_parameters['aoi_model'] = 'no_loss'
return module_parameters |
def add_arrays(x, y):
"""
This function adds together each element of the two passed lists.
Args:
x (list): The first list to add
y (list): The second list to add
Returns:
list: the pairwise sums of ``x`` and ``y``.
Examples:
>>> add_arrays([1, 4, 5], [4, 3, 5])
[5, 7, 10]
"""
if len(x) != len(y):
raise ValueError("Both arrays must have the same length.")
z = []
for x_, y_ in zip(x, y):
z.append(x_ + y_)
return z |
def reformat_prop(obj):
"""
Map over ``titles`` to get properties usable for looking up from
node instances.
Change properties to have 'node_id' instead of 'id', and 'label'
instead of 'type', so that the props can be looked up as dictionary
entries:
.. code-block:: python
node[prop]
"""
new_obj = {k: v for (k, v) in obj.items() if v is not None}
if "node_id" in new_obj:
new_obj["id"] = new_obj["node_id"]
del new_obj["node_id"]
if "label" in new_obj:
new_obj["type"] = new_obj["label"]
del new_obj["label"]
return new_obj |
def objective_function(x, y, name="rosenbrock"):
"""Return value of the objective function at coordinates x1, x2."""
if name == "rosenbrock":
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
else:
raise NotImplementedError |
def getPathToGoal(start, goal, parents):
"""Given the hash of parental links, follow back and return the
chain of ancestors."""
try:
results = []
while (goal != start):
results.append(goal)
goal = parents[goal]
# end while (goal != start)
results.append(start)
results.reverse()
return results
except KeyError: return [] |
def list2str(lst, short=True):
""" Returns a string representing a list """
try:
if short:
return ', '.join(lst)
else:
return str(lst)
except:
if short:
return ""
else:
return "[]" |
def get_nextupsegs(graph_r, upsegs):
"""Get adjacent upsegs for a list of segments
as a single flat list.
Parameters
----------
graph_r : dict
Dictionary of upstream routing connections.
(keys=segments, values=adjacent upstream segments)
upsegs : list
List of segments
Returns
-------
nextupsegs : list
Flat list of next segments upstream from upsegs
"""
nextupsegs = set()
for s in upsegs:
nextupsegs.update(graph_r.get(s, {}))
#nextupsegs.update(graph_r[s])
return nextupsegs |
def handle(seq):
"""
Return only string surrounded by ().
:param seq: (string) the string to process
:return: (list of string) list of word in seq sourrounded by ()
"""
seq = seq.replace("()", "")
start = 0
res = []
word = ""
for w in seq:
if w == "(":
start += 1
if start == 1:
word = "("
else:
word += "("
elif w == ")":
start -= 1
word += ")"
if start == 0:
res.append(word)
elif start > 0:
word += w
return res |
def safe_div(dividend, divisor, divide_by_zero_value=0):
"""Return the result of division, allowing the divisor to be zero."""
return dividend / divisor if divisor != 0 else divide_by_zero_value |
def create_surrogate_string(instr: str):
"""
Preserve newlines and replace all other characters with spaces
:return whitespace string with same length as instr and with the same line breaks
"""
return ''.join(['\n' if e == '\n' else ' ' for e in instr]) |
def modinv(a, b):
"""Returns the modular inverse of a mod b.
Pre: a < b and gcd(a, b) = 1
Adapted from https://en.wikibooks.org/wiki/Algorithm_Implementation/
Mathematics/Extended_Euclidean_algorithm#Python
"""
saved = b
x, y, u, v = 0, 1, 1, 0
while a:
q, r = b // a, b % a
m, n = x - u*q, y - v*q
b, a, x, y, u, v = a, r, u, v, m, n
return x % saved |
def car_current(t):
"""
Piecewise constant current as a function of time in seconds. This is adapted
from the file getCarCurrent.m, which is part of the LIONSIMBA toolbox [1]_.
References
----------
.. [1] M Torchio, L Magni, R Bushan Gopaluni, RD Braatz, and D. Raimondoa.
LIONSIMBA: A Matlab framework based on a finite volume model suitable
for Li-ion battery design, simulation, and control. Journal of The
Electrochemical Society, 163(7):1192-1205, 2016.
"""
current = (
1 * (t >= 0) * (t <= 50)
- 0.5 * (t > 50) * (t <= 60)
+ 0.5 * (t > 60) * (t <= 210)
+ 1 * (t > 210) * (t <= 410)
+ 2 * (t > 410) * (t <= 415)
+ 1.25 * (t > 415) * (t <= 615)
- 0.5 * (t > 615)
)
return current |
def to_height(data: float, height: int, max_value: float, min_value: float) -> float:
"""translate the data to a height"""
return (data - min_value) / (max_value - min_value) * height |
def build_flags_string(flags):
"""Format a string of value-less flags.
Pass in a dictionary mapping flags to booleans. Those flags set to true
are included in the returned string.
Usage:
build_flags_string({
'--no-ttl': True,
'--no-name': False,
'--verbose': True,
})
Returns:
'--no-ttl --verbose'
"""
flags = {flag: is_set for flag, is_set in flags.items() if is_set}
return " ".join(flags.keys()) |
def is_monotonic(x, increasing=True):
""" This function checks whether a given list is monotonically increasing
(or decreasing). By definition, "monotonically increasing" means the
same as "strictly non-decreasing".
Adapted from: http://stackoverflow.com/questions/4983258/python-how-to-check-list-monotonicity
Args:
x (sequence) : a 1-d list of numbers
increasing (bool) : whether to check for increasing monotonicity
"""
import numpy as np
dx = np.diff(x)
if increasing:
return np.all(dx >= 0)
else:
return np.all(dx <= 0) |
def check_template_sample(template_object, sample_set):
"""
check_template_sample checks if a template has a sample associated in the samples/ folder
Args:
template_object: the template dict to check, which got parsed from the file content
sample_set: set of sample kinds (string) built by build_sample_set
Raises:
yaml.YAMLError if the input template or any sample file is not a valid YAML file
Returns:
Boolean - True if a sample was found for this template, False otherwise.
"""
# retrieve the template kind
template_kind = template_object["spec"]["crd"]["spec"]["names"]["kind"]
sample_found = template_kind in sample_set
# if not, error out
if not sample_found:
print("No sample found for template {}".format(template_kind))
return sample_found |
def check_direction(direction_string, valid_directions):
"""check direction string
:param direction_string - string
:param valid_directions - string
:return boolean"""
if direction_string is None or len(direction_string) == 0:
return False
for direction in direction_string:
if direction not in valid_directions and len(direction) != 1:
return False
return True |
def mars_exploration(s):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/mars-exploration/problem
Sami's spaceship crashed on Mars! She sends a series of SOS messages to Earth for help.
Letters in some of the SOS messages are altered by cosmic radiation during transmission. Given the signal received
by Earth as a string, s, determine how many letters of Sami's SOS have been changed by radiation.
For example, Earth receives SOSTOT. Sami's original message was SOSSOS. Two of the message characters were changed
in transit.
Args:
s (str): string to compare with SOS message (must be divisible by 3)
Returns:
int: the number of characters that differ between the message and "SOS"
"""
sos = int(len(s)/3) * "SOS"
return sum(sos[i] != s[i] for i in range(len(s))) |
def populate_table_data(tenants):
"""Generates entries used to populate tenant table."""
result = []
for tenant in tenants:
name = str(tenant.name)
checkbox_html_template = '<input type="checkbox" id="{name}" name="{name}" {option} checked>'
import_option = 'class="table_checkbox" onchange="toggle_import_checkboxes(this, \'{}\', 1)"'.format(name)
other_option = 'class="table_checkbox" onchange="get_and_toggle_column_header_checkbox({index})"'
import_name = name + '_import'
endpoint_devices_name = name + '_import_endpoint_devices'
overwrite_name = name + '_overwrite'
result.append([name,
checkbox_html_template.format(name=import_name, option=import_option),
checkbox_html_template.format(name=endpoint_devices_name, option=other_option.format(index=2)),
checkbox_html_template.format(name=overwrite_name, option=other_option.format(index=3)),
])
return result |
def check_pal(phrase):
"""
Checks whether a phrase is a palindrome or not.
>>> check_pal('Reviled did I live, said I, as evil I did deliver')
True
"""
import re
p = re.compile('\W')
phrase = p.sub('', phrase).lower()
# With list
# rev = list(phrase)
# rev.reverse()
#
# return list(phrase) == rev
# With iterator
# rev = ""
# for i in reversed(phrase):
# rev += i
# With recursion
def srev(string):
if len(string) == 1:
return string[0]
else:
return srev(string[1:]) + string[0]
return phrase == srev(phrase) |
def RemoveDuplicatedVertices(vertices, faces, vnorms=None):
"""Remove duplicated vertices and re-index the polygonal faces such that
they share vertices"""
vl = {}
vrl = {}
nvert = 0
vertList = []
normList = []
for i, v in enumerate(vertices):
key = "%f%f%f" % tuple(v)
if key not in vl:
vl[key] = nvert
vrl[i] = nvert
nvert += 1
vertList.append(v)
if vnorms is not None:
normList.append(vnorms[i])
else:
nind = vl[key]
vrl[i] = nind
if vnorms is not None:
vn1 = normList[nind]
vn2 = vnorms[i]
normList[nind] = [
(vn1[0] + vn2[0]) / 2,
(vn1[1] + vn2[1]) / 2,
(vn1[2] + vn2[2]) / 2,
]
faceList = []
for f in faces:
faceList.append(list(map(lambda x, l=vrl: vrl[x], f)))
if vnorms is not None:
return vertList, faceList, normList
return vertList, faceList |
def to_cmd_param(variable: str) -> str:
"""
Convert a variable in a command parameter format
"""
return variable.replace('_', '-') |
def compute_giou(arg_obj, ref_obj):
"""
Compute the generalized intersection over union code described in the paper available from:
https://giou.stanford.edu/GIoU.pdf Page 4 of the paper has the psuedocode for this algorithm
:param arg_obj: The argument object represented as a bounding box
:param ref_obj: The referrant object represented as a bounding box
:return: The IoU and GIoU scores for the arg and ref objects
"""
arg_x1 = arg_obj[0]
arg_y1 = arg_obj[1]
arg_x2 = arg_obj[2]
arg_y2 = arg_obj[3]
area_arg_obj = (arg_x2 - arg_x1) * (arg_y2 - arg_y1)
# Compute the area of the ref obj
ref_x1 = ref_obj[0]
ref_y1 = ref_obj[1]
ref_x2 = ref_obj[2]
ref_y2 = ref_obj[3]
area_ref_obj = (ref_x2 - ref_x1) * (ref_y2 - ref_y1)
# Calculate the intersection between the arg and ref objects
x_1_I = max(arg_x1, ref_x1)
x_2_I = min(arg_x2, ref_x2)
y_1_I = max(arg_y1, ref_y1)
y_2_I = min(arg_y2, ref_y2)
if x_2_I > x_1_I and y_2_I > y_1_I: # Double check this, I think and is correct here.
I = (x_2_I - x_1_I) * (y_2_I - y_1_I)
else:
I = 0
# Find the coordinates of the smallest bounding box that encloses both objects
x_1_c = min(ref_x1, arg_x1)
x_2_c = max(ref_x2, arg_x2)
y_1_c = min(ref_y1, arg_y1)
y_2_c = max(ref_y2, arg_y2)
# Calculate the area of the smallest enclosing bounding box
area_b_c = (x_2_c - x_1_c) * (y_2_c - y_1_c)
# Calculate the IOU (Intersection over Union)
# IoU = I/U, where U = Area_ref + Area_arg - I
U = area_arg_obj + area_ref_obj - I
IoU = I / U
# Calculate GIoU (Generalized Intersection over Union)
# GIoU = IoU - (Area_c - U)/Area_c
GIoU = IoU - ((area_b_c - U) / area_b_c)
return GIoU, IoU |
def is_enz (node):
"""Tells if node is an enzyme (EC) or not"""
split = node.split(".")
if len(split) == 4 :#and np.all(np.array([sp.isdigit() for sp in split]) == True) :
return True
else:
return False |
def method_available(klass, method):
"""Checks if the provided class supports and can call the provided method."""
return callable(getattr(klass, method, None)) |
def number_greater_than(element, value, score):
"""Check if element is greater than config value.
Args:
element (float) : Usually vcf record
value (float) : Config value
score (integer) : config score
Return:
Float: Score
"""
if element > value:
return score |
def create_node(n,*args):
"""
Parameters:
-----------
n : int
Node number
*args: tuple, int, float
*args must be a tuple of (x,y,z) coordinates or x, y and z
coordinates as arguments.
::
# Example
node1 = 1
node2 = 2
create_node(node1,(0,0,0)) # x,y,z as tuple
create_node(node2,1,1,1) # x,y,z as arguments
"""
if len(args)==1 and isinstance(args[0],tuple):
x,y,z = args[0][0],args[0][1],args[0][2]
else:
x,y,z = args[0], args[1], args[2]
_nd = "N,%g,%g,%g,%g"%(n,x,y,z)
return _nd |
def str_to_dpid (s):
"""
Convert a DPID in the canonical string form into a long int.
"""
if s.lower().startswith("0x"):
s = s[2:]
s = s.replace("-", "").split("|", 2)
a = int(s[0], 16)
if a > 0xffFFffFFffFF:
b = a >> 48
a &= 0xffFFffFFffFF
else:
b = 0
if len(s) == 2:
b = int(s[1])
return a | (b << 48) |
def add_nested_field_to_es(nested_field, text, es_doc):
""" Add a text to an appropriate field in
a given elasticsearch-form document."""
if nested_field not in es_doc:
# create a new
es_doc[nested_field] = text
else:
# append to existed one
es_doc[nested_field] = "|".join([es_doc[nested_field], text])
return es_doc |
def find_ask(asks, t_depth: float):
"""find best ask in the orderbook needed to fill an order of amount t_depth"""
price = 0.0
depth = 0.0
for a in asks:
price = float(a['price'])
depth += float(a['amount'])
if depth >= t_depth:
break
return round(price + 0.000001, 7) |
def getObjectName(o):
"""
Return the name of an host object
@type o: hostObject
@param o: an host object
@rtype: string
@return: the name of the host object
"""
name=""
return name |
def wood_mono_to_string(mono, latex=False):
"""
String representation of element of Wood's Y and Z bases.
This is used by the _repr_ and _latex_ methods.
INPUT:
- ``mono`` - tuple of pairs of non-negative integers (s,t)
- ``latex`` - boolean (optional, default False), if true, output
LaTeX string
OUTPUT: ``string`` - concatenation of strings of the form
``Sq^{2^s (2^{t+1}-1)}`` for each pair (s,t)
EXAMPLES::
sage: from sage.algebras.steenrod.steenrod_algebra_misc import wood_mono_to_string
sage: wood_mono_to_string(((1,2),(3,0)))
'Sq^{14} Sq^{8}'
sage: wood_mono_to_string(((1,2),(3,0)),latex=True)
'\\text{Sq}^{14} \\text{Sq}^{8}'
The empty tuple represents the unit element::
sage: wood_mono_to_string(())
'1'
"""
if latex:
sq = "\\text{Sq}"
else:
sq = "Sq"
if len(mono) == 0:
return "1"
else:
string = ""
for (s,t) in mono:
string = string + sq + "^{" + \
str(2**s * (2**(t+1)-1)) + "} "
return string.strip(" ") |
def is_letter_guessed_correctly(player_input, secret_word):
""" check whether the (guessed_letter/ player_input) is in the secret_word
Arguments:
player_input (string): the player_input
secret_word (string): the secret, random word that the player should guess
Returns:
boolean: True if the player_input is in the secret_word; False otherwise
"""
for i in secret_word:
if player_input == i:
return True
return False |
def get_leaf_branch_nodes(neighbors):
""""
Create list of candidates for leaf and branching nodes.
Args:
neighbors: dict of neighbors per node
"""
all_nodes = list(neighbors.keys())
leafs = [i for i in all_nodes if len(neighbors[i]) == 1]
candidates = leafs
next_nodes = []
for l in leafs:
next_nodes += [n for n in neighbors[l] if len(neighbors[n]) == 2]
while next_nodes:
s = next_nodes.pop(0)
candidates.append(s)
next_nodes += [n for n in neighbors[s] if len(neighbors[n]) == 2 and n not in candidates and n not in next_nodes]
return candidates |
def set_metrics_facts_if_unset(facts):
""" Set cluster metrics facts if not already present in facts dict
dict: the facts dict updated with the generated cluster metrics facts if
missing
Args:
facts (dict): existing facts
Returns:
dict: the facts dict updated with the generated cluster metrics
facts if they were not already present
"""
if 'common' in facts:
if 'use_cluster_metrics' not in facts['common']:
use_cluster_metrics = False
facts['common']['use_cluster_metrics'] = use_cluster_metrics
return facts |
def edgesFromNode(n):
"""Return the two edges coorsponding to node n"""
if n == 0:
return 0, 2
if n == 1:
return 0, 3
if n == 2:
return 1, 2
if n == 3:
return 1, 3 |
def transcribe(dna):
"""Return DNA string as RNA string."""
return dna.replace('T', 'U').replace('t','u') |
def num_cycle_scenarios(k):
"""Compute the number (and the length) of scenarios for a cycle with
the given size."""
if k % 2 == 1:
print("ERROR: Odd cycle size.")
exit(-1)
l = (k // 2) - 1
s = (l + 1) ** (l - 1)
return s, l |
def application_instance_multiplier(value, app, dig_it_up, api_version=None):
"""Digs up the number of instances of the supplied app,
and returns the value multiplied by the number of instances
"""
response = None
instances = dig_it_up(app, 'instances')
if instances is not None:
response = value * instances
return response |
def matches(item, *, plugins=None, subregions=None):
"""
Checks whether the item matches zero or more constraints.
``plugins`` should be a tuple of plugin classes or ``None`` if the type
shouldn't be checked.
``subregions`` should be set of allowed ``subregion`` attribute values or
``None`` if the ``subregion`` attribute shouldn't be checked at all.
Include ``None`` in the set if you want ``matches`` to succeed also when
encountering an item without a ``subregion`` attribute.
"""
if plugins is not None and not isinstance(item, plugins):
return False
if subregions is not None and getattr(item, "subregion", None) not in subregions:
return False
return True |
def _denominate(total):
"""
Coverts bucket size to human readable bytes.
"""
total = float(total)
denomination = ["KB", "MB","GB","TB"]
for x in denomination:
if total > 1024:
total = total / 1024
if total < 1024:
total = round(total, 2)
total = str(total) + " " + x
break
return total |
def analysis_nindex_usages(analysis):
"""
Returns a dictionary of namespace usages by name.
'nindex' stands for 'namespace index'.
"""
return analysis.get("nindex_usages", {}) |
def is_dictionary(obj):
"""Helper method for testing if the object is a dictionary.
>>> is_dictionary({'key':'value'})
True
"""
return type(obj) is dict |
def _intervalOverlap(a, b):
""" Return overlap between two intervals
Args:
a (list or tuple): first interval
b (list or tuple): second interval
Returns:
float: overlap between the intervals
Example:
>>> _intervalOverlap( [0,2], [0,1])
1
"""
return max(0, min(a[1], b[1]) - max(a[0], b[0])) |
def methods_hydrodynamic():
"""
Returns a list containing the valid method keys that have used
hydrodynamic simulations.
"""
hydro = [
"Batten2021",
]
return hydro |
def crosses(split1, split2):
"""
Check whether the splits intersect.
"""
intersect = False
#print(split1, split2)
#if bool(set(split1).intersection(split2)):
if not (set(split1).isdisjoint(split2) or set(split1).issubset(split2) or set(split2).issubset(split1)):
intersect = True
return intersect |
def get_unsupported_pytorch_ops(model_path):
""" return unsupported layers in caffe prototxt
A List.
"""
ret = list()
return ret |
def get_arxiv_id(result_record):
"""
:param result_record:
:return:
"""
identifiers = result_record.get("identifier", [])
for identifier in identifiers:
if "arXiv:" in identifier:
return identifier.replace("arXiv:", "")
if "ascl:" in identifier:
return identifier.replace("ascl:", "")
return "" |
def _unique_item_counts(iterable):
""" Build a dictionary giving the count of each unique item in a sequence.
:param iterable: sequence to obtain counts for
:type iterable: iterable object
:rtype: dict[obj: int]
"""
items = tuple(iterable)
return {item: items.count(item) for item in sorted(set(items))} |
def depth(d):
"""Check dictionary depth"""
if isinstance(d, dict):
return 1 + (max(map(depth, d.values())) if d else 0)
return 0 |
def get_record_list(data, record_list_level):
"""
Dig the raw data to the level that contains the list of the records
"""
if not record_list_level:
return data
for x in record_list_level.split(","):
data = data[x]
return data |
def gcd(a,b):
"""Returns the greatest common divisor of two numbers.
"""
if (b==0):
return a
else:
return(gcd(b,a % b)) |
def is_command(text: str) -> bool:
"""Returns true if specified message is a command."""
return text.startswith("pp") |
def fractional_part(numerator, denominator):
"""The fractional_part function divides the numerator by the denominator, and
returns just the fractional part (a number between 0 and 1)."""
if denominator != 0:
return (numerator % denominator) / denominator
return 0 |
def bitxor(a, b):
"""
Xor two bit strings (trims the longer input)
"""
return "".join([str(int(x) ^ int(y)) for (x, y) in zip(a, b)]) |
def construct_regex(parser_names):
"""
This regex is a modified version of wordpress origianl shortcode parser found here
https://core.trac.wordpress.org/browser/trunk/src/wp-includes/shortcodes.php?rev=28413#L225
'\[' // Opening bracket
'(\[?)' // 1: Optional second opening bracket for escaping shortcodes: [[tag]]
"(parser_names)" // 2: Shortcode name
'(?![\w-])' // Not followed by word character or hyphen
'(' // 3: Unroll the loop: Inside the opening shortcode tag
'[^\]\/]*' // Not a closing bracket or forward slash
'(?:'
'\/(?!\])' // A forward slash not followed by a closing bracket
'[^\]\/]*' // Not a closing bracket or forward slash
')*?'
')'
'(?:'
'(\/)' // 4: Self closing tag ...
'\]' // ... and closing bracket
'|'
'\]' // Closing bracket
'(?:'
'(' // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags
'[^\[]*' // Not an opening bracket
'(?:'
'\[(?!\/\2\])' // An opening bracket not followed by the closing shortcode tag
'[^\[]*' // Not an opening bracket
')*'
')'
'\[\/\2\]' // Closing shortcode tag
')?'
')'
'(\]?)'
"""
parser_names_reg = '|'.join(parser_names)
return '\\[(\\[?)('+parser_names_reg+')(?![\\w-])([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:\\[(?!\\/\\2\\])[^\\\\[]*)*)\\[\\/\\2\\])?)(\\]?)' |
def qiime_to_maaslin(in_datafile, outfile):
"""Converts a tsv file from qiime to a maaslin format
:param in_datafile: String; file of the qiime tsv format (from
biom_to_tsv)
:param outfile: String; file of the tsv format for input to maaslin
External dependencies
- QiimeToMaaslin: https://bitbucket.org/biobakery/qiimetomaaslin
"""
cmd="qiimeToMaaslin.py < " + in_datafile + \
" > " + outfile
return {
"name": "qiime_to_maaslin: " + in_datafile,
"actions": [cmd],
"file_dep": [in_datafile],
"targets": [outfile]
} |
def discount(cost, parameters, capex):
"""
Discount costs based on asset_lifetime.
"""
# asset_lifetime = parameters['return_period']
# discount_rate = parameters['discount_rate'] / 100
# if capex == 1:
# capex = cost
# opex = round(capex * (parameters['opex_percentage_of_capex'] / 100))
# total_cost_of_ownership = 0
# total_cost_of_ownership += capex
# for i in range(0, asset_lifetime ):
# total_cost_of_ownership += (
# opex / (1 + discount_rate) ** i
# )
# else:
# opex = cost
# total_cost_of_ownership = 0
# for i in range(0, asset_lifetime ):
# total_cost_of_ownership += (
# opex / (1 + discount_rate) ** i
# )
return cost*10 |
def _resolve_callable(c):
"""Helper to resolve a callable to its value, even if they are embedded.
:param c: FN() -> value-or-callable
:returns: fn(fn(fn....))
:raises: possibly anything, depending on the callable
"""
while callable(c):
c = c()
return c |
def check_bool(text: str) -> bool:
"""Check if a string is bool-like and return that."""
text = text.lower()
if text in ('true', 't', '1', 'yes', 'y', 'on'):
return True
else:
return False |
def flatten(nums):
"""flatten a list: [1,2,[3,4. [5],[6,7,[8,[9]]]]]
"""
result = []
for num in nums:
print(result)
if type(num) is list:
for i in num:
if type(i) is list:
result.extend(i)
else:
result.append(i)
else:
result.append(num)
return result |
def get_stack_name(job_identifier, obj):
"""Formats the stack name and make sure it meets LEO and CloudFormations naming requirements."""
stack_name = "{}-{}".format(job_identifier, obj)
# Below checks if the stack_name meets all requirements.
stack_name_parts = []
if not stack_name[0].isalpha():
stack_name = "s-" + stack_name
if len(stack_name) > 255:
stack_name = stack_name[:255]
for s in stack_name:
if not s.isalnum():
s = s.replace(s, "-")
stack_name_parts.append(s)
else:
stack_name_parts.append(s)
stack_name = "".join(stack_name_parts)
return stack_name |
def region(lat, lon):
""" Return the SRTM3 region name of a given lat, lon.
Map of regions:
http://dds.cr.usgs.gov/srtm/version2_1/Documentation/Continent_def.gif
"""
if -45 <= lat and lat < -25 and -180 <= lon and lon < -175:
# southern hemisphere, near dateline
return 'Islands'
elif 15 <= lat and lat < 30 and -180 <= lon and lon < -150:
# around hawaii
return 'Islands'
elif -60 <= lat and lat < -35 and -40 <= lon and lon < 80:
# south atlantic ocean
return 'Islands'
elif -35 <= lat and lat < -5 and -30 <= lon and lon < -5:
# mid-atlantic, between africa and south america
return 'Islands'
elif -60 <= lat and lat < -40 and 155 <= lon and lon < 180:
# southern half of new zealand
return 'Islands'
elif -40 <= lat and lat < -25 and 165 <= lon and lon < 180:
# northern half of new zealand
return 'Islands'
if 15 <= lat and lat < 61 and -170 <= lon and lon < -40:
return 'North_America'
elif -60 <= lat and lat < 15 and -95 <= lon and lon < -30:
return 'South_America'
elif -35 <= lat and lat < 35 and -30 <= lon and lon < 60:
return 'Africa'
elif -20 <= lat and lat < -15 and 60 <= lon and lon < 65:
return 'Africa'
elif 35 <= lat and lat < 40 and -35 <= lon and lon < -20:
return 'Africa'
elif -10 <= lat and lat < 61 and -15 <= lon and lon < 180:
return 'Eurasia'
elif -10 <= lat and lat < 61 and -180 <= lon and lon < -135:
return 'Eurasia'
elif -15 <= lat and lat < -10 and 95 <= lon and lon < 100:
return 'Eurasia'
elif -45 <= lat and lat < -10 and 110 <= lon and lon < 180:
return 'Australia'
raise ValueError('Unknown location: %s, %s' % (lat, lon)) |
def towards(a, b, amount):
"""amount between [0,1] -> [a,b]"""
return (amount * (b - a)) + a |
def is_parser(parser):
"""
Parsers are modules with a parse function dropped in the 'parsers' folder.
When attempting to parse a file, QCRI will load and try all parsers,
returning a list of the ones that worked.
todo: load them from config
"""
return hasattr(parser, 'parse') and hasattr(parser, 'ATTACH_LIST') |
def get_pacer_case_id_from_docket_url(url):
"""Extract the pacer case ID from the docket URL.
In: https://ecf.almd.uscourts.gov/cgi-bin/DktRpt.pl?56120
Out: 56120
In: https://ecf.azb.uscourts.gov/cgi-bin/iquery.pl?625371913403797-L_9999_1-0-663150
Out: 663150
"""
param = url.split('?')[1]
if 'L' in param:
return param.rsplit('-', 1)[1]
return param |
def get_region(zone):
"""Converts us-central1-f into us-central1."""
return '-'.join(zone.split('-')[:2]) |
def gon2deg(ang):
""" convert from gon to degrees
Parameters
----------
ang : unit=gon, range=0...400
Returns
-------
ang : unit=degrees, range=0...360
See Also
--------
deg2gon, deg2compass
"""
ang *= 360/400
return ang |
def children(tree):
"""
Given an ast tree get all children. For PHP, children are anything
with a nodeType.
:param tree_el ast:
:rtype: list[ast]
"""
assert isinstance(tree, dict)
ret = []
for v in tree.values():
if isinstance(v, list):
for el in v:
if isinstance(el, dict) and el.get('nodeType'):
ret.append(el)
elif isinstance(v, dict) and v.get('nodeType'):
ret.append(v)
return ret |
def is_in_any_txt(txt, within_txts_list, case_insensitive=False):
"""is "txt" in any of the texts list ?"""
for within_txt in within_txts_list:
if case_insensitive: # slower
if txt.lower() in within_txt.lower():
return True
else:
if txt in within_txt:
return True
return False |
def setBillNumberQuery(billnumber: str) -> dict:
"""
Sets Elasticsearch query by bill number
Args:
billnumber (str): billnumber (no version)
Returns:
dict: [description]
"hits" : [
{
"_index" : "billsections",
"_type" : "_doc",
"_id" : "yH0adHcByMv3L6kFHKWS",
"_score" : null,
"fields" : {
"date" : [
"2019-03-05T00:00:00.000Z"
],
"billnumber" : [
"116hr1500"
],
"id" : [
"116hr1500ih"
],
"bill_version" : [
"ih"
],
"dc" : [
...
]
},
"sort" : [
1558569600000
]
},
"""
return {
"sort" : [
{ "date" : {"order" : "desc"}}
],
"query": {
"match": {
"billnumber": billnumber
}
},
"fields": ["id", "billnumber", "billversion", "billnumber_version", "date"],
"_source": False
} |
def fahrenheit(value):
"""
Convert Celsius to Fahrenheit
"""
return round((value * 9 / 5) + 32, 1) |
def generate_occluder_pole_position_x(
wall_x_position: float,
wall_x_scale: float,
sideways_left: bool
) -> float:
"""Generate and return the X position for a sideways occluder's pole object
using the given properties."""
if sideways_left:
return -3 + wall_x_position - wall_x_scale / 2
return 3 + wall_x_position + wall_x_scale / 2 |
def validate_boolean(value, label):
"""Validates that the given value is a boolean."""
if not isinstance(value, bool):
raise ValueError('Invalid type for {0}: {1}.'.format(label, value))
return value |
def load_text_file(filename):
""" Returns a list of sequences separated by carriage returns in the file.
Words are strings of characters. Whitespace is stripped.
Capital letters removed.
"""
in_file = open(filename, 'r')
wordlist = []
for line in in_file:
wordlist.append(line.strip().lower())
return wordlist |
def in_range(low, high, max):
""" Determines if the passed values are in the range. """
if (low < 0 or low > high):
return 0
if (high < 0 or high > max):
return 0
return 1 |
def is_anagram(str1: str, str2: str) -> bool:
"""Check if the given two strings are anagrams
Worst: O(nlog n)
Best: O(n)
"""
str1_list = sorted(str1)
str2_list = sorted(str2)
return str1_list == str2_list |
def validate_comma_separated_list(setting, value, option_parser,
config_parser=None, config_section=None):
"""Check/normalize list arguments (split at "," and strip whitespace).
"""
# `value` is already a ``list`` when given as command line option
# and "action" is "append" and ``unicode`` or ``str`` else.
if not isinstance(value, list):
value = [value]
# this function is called for every option added to `value`
# -> split the last item and append the result:
last = value.pop()
items = [i.strip(u' \t\n') for i in last.split(u',') if i.strip(u' \t\n')]
value.extend(items)
return value |
def filter_object_parameters(ob, list_of_parameters):
"""Return an object of just the list of paramters."""
new_ob = {}
for par in list_of_parameters:
try:
new_ob[par] = ob[par]
except KeyError:
new_ob[par] = None
return new_ob |
def is_leap(year: int) -> bool:
""" https://stackoverflow.com/a/30714165 """
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) |
def has_navigation(node, key=None):
"""Returns ``True`` if the node has a :class:`.Navigation` with the given key and ``False`` otherwise. If ``key`` is ``None``, returns whether the node has any :class:`.Navigation`\ s at all."""
try:
return bool(node.navigation[key])
except:
return False |
def get_html(html: str):
"""Convert HTML so it can be rendered."""
WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>"""
# Newlines seem to mess with the rendering
html = html.replace("\n", " ")
return WRAPPER.format(html) |
def default(v, d):
"""Returns d when v is empty (string, list, etc) or false"""
if not v:
v = d
return v |
def iobes_iob(tags):
"""
IOBES -> IOB
"""
new_tags = []
for i, tag in enumerate(tags):
if tag.split('-')[0] == 'B':
new_tags.append(tag)
elif tag.split('-')[0] == 'I':
new_tags.append(tag)
elif tag.split('-')[0] == 'S':
new_tags.append(tag.replace('S-', 'B-'))
elif tag.split('-')[0] == 'E':
new_tags.append(tag.replace('E-', 'I-'))
elif tag.split('-')[0] == 'O':
new_tags.append(tag)
else:
raise Exception('Invalid format!')
return new_tags |
def to_lower(string):
"""The lower case version of a string"""
return string.lower() |
def fail_rate(num_fail, num_pass):
"""Computes fails rate, return N/A if total is 0."""
total = num_fail + num_pass
if total:
return "{:.3f}".format(round(num_fail / total, 3))
return "N/A" |
def _convert_scale(target_value, max_value):
"""If target_value is float, mult with max_value otherwise take it straight"""
if target_value <= 1:
return int(max_value * target_value)
assert target_value <= max_value
return target_value |
def make_readable(seconds):
"""
seconds: number of seconds to translate into hours, minutes and second
return: seconds into hours, minutes and seconds in a digital clock format
"""
second = 0
minute = 0
hour = 0
if seconds <= 359999:
for i in range(seconds):
second += 1
if second >= 60:
second -= 60
minute += 1
if minute >= 60:
minute -= 60
hour += 1
if second < 10:
second = "0"+str(second)
if minute < 10:
minute = "0"+str(minute)
if hour < 10:
hour = "0"+str(hour)
return str("{}:{}:{}".format(hour, minute, second)) |
def rotate_voxel(xmin, ymin, xmax, ymax):
"""
Given center position, rotate to the first quadrant
Parameters
----------
xmin: float
low point X position, mm
ymin: float
low point Y position, mm
xmax: float
high point X position, mm
ymax: float
high point Y position, mm
returns: floats
properly rotated voxel in the first quadrant
"""
xc = 0.5 * (xmin + xmax)
yc = 0.5 * (ymin + ymax)
if xc >= 0.0 and yc >= 0.0: # no rotation
return (xmin, ymin, xmax, ymax)
if xc < 0.0 and yc >= 0.0: # CW 90 rotation
return (ymin, -xmax, ymax, -xmin)
if xc < 0.0 and yc < 0.0: # CW 180 rotation
return (-xmax, -ymax, -xmin, -ymin)
# xc > 0.0 && yc < 0.0: # CW 270 rotation
return (-ymax, xmin, -ymin, xmax) |
def residcomp(z1, z0, linelength=1):
"""
Residual Compensation Factor Function.
Evaluates the residual compensation factor based on the line's positive and
zero sequence impedance characteristics.
Parameters
----------
z1: complex
The positive-sequence impedance
characteristic of the line, specified in
ohms-per-unit where the total line length
(of same unit) is specified in
*linelength* argument.
z0: complex
The zero-sequence impedance characteristic
of the line, specified in ohms-per-unit
where the total line length (of same unit)
is specified in *linelength* argument.
linelength: float, optional
The length (in same base unit as impedance
characteristics) of the line. default=1
Returns
-------
k0: complex
The residual compensation factor.
"""
# Evaluate Z1L and Z0L
Z1L = z1 * linelength
Z0L = z0 * linelength
# Calculate Residual Compensation Factor (k0)
k0 = (Z0L - Z1L) / (3 * Z1L)
return k0 |
def dumb_fibonacci(i, seq=None):
"""Dumb solution"""
if i <= 1:
return 1, 0, [0]
if i == 2:
return 2, 1, [0, 1]
result1 = dumb_fibonacci(i - 1)
result2 = dumb_fibonacci(i - 2)
seq = result1[2]
seq.append(result1[1] + result2[1])
return i, seq[i - 1], seq[:i] |
def label2tag(label_sequence, tag_vocab):
"""
convert label sequence to tag sequence
:param label_sequence: label sequence
:param tag_vocab: tag vocabulary, i.e., mapping between tag and label
:return:
"""
inv_tag_vocab = {}
for tag in tag_vocab:
label = tag_vocab[tag]
inv_tag_vocab[label] = tag
tag_sequences = []
n_tag = len(tag_vocab)
for seq in label_sequence:
tag_seq = []
for l in seq:
if l in inv_tag_vocab:
tag_seq.append(inv_tag_vocab[l])
elif l == n_tag or l == n_tag + 1:
tag_seq.append("O")
else:
raise Exception("Invalid label %s" % l)
tag_sequences.append(tag_seq)
return tag_sequences |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.