content
stringlengths 42
6.51k
|
|---|
def create_params_str(params, key_value_separator="_", param_separator="__"):
"""
All ``(key, value)`` pairs/parameters in ``params`` are concatenated using a single underscore
to separate ``key`` and ``value`` and a double underscore is prepended to each parameter
to separate the parameters, i.e., a string in the following format is created
``__key1_value1__key2_value2 ... __keyN_valueN``
If ``params`` is None or empty, an empty string is returned.
The single underscore and double underscore separators can be changed by specifying
the default parameters ``key_value_separator`` and ``param_separator``.
**IMPORTANT NOTE:**
This function is rather specific to time series characteristic features (such as tsfresh),
so it should be used only internally.
"""
return "".join([f"{param_separator}{k}{key_value_separator}{v}" for k, v in params.items()]) if params else ""
|
def has_palindrome(i, start, length):
"""Checks if the string representation of i has a palindrome.
i: integer
start: where in the string to start
length: length of the palindrome to check for
"""
s = str(i)[start:start+length]
return s[::-1] == s
|
def fill_empties(abstract):
"""Fill empty cells in the abstraction
The way the row patterns are constructed assumes that empty cells are
marked by the letter `C` as well. This function fill those in. The function
also removes duplicate occurrances of ``CC`` and replaces these with
``C``.
Parameters
----------
abstract : str
The abstract representation of the file.
Returns
-------
abstraction : str
The abstract representation with empties filled.
"""
while "DD" in abstract:
abstract = abstract.replace("DD", "DCD")
while "DR" in abstract:
abstract = abstract.replace("DR", "DCR")
while "RD" in abstract:
abstract = abstract.replace("RD", "RCD")
while "CC" in abstract:
abstract = abstract.replace("CC", "C")
if abstract.startswith("D"):
abstract = "C" + abstract
if abstract.endswith("D"):
abstract += "C"
return abstract
|
def curl_field_scalar(x, y, z, noise):
"""calculate a 3D velocity field using scalar curl noise"""
eps = 1.0e-4
def deriv(a1, a2):
return (a1 - a2) / (2.0 * eps)
dx = deriv(noise(x + eps, y, z), noise(x - eps, y, z))
dy = deriv(noise(x, y + eps, z), noise(x, y - eps, z))
dz = deriv(noise(x, y, z + eps), noise(x, y, z - eps))
return dy - dz, dz - dx, dx - dy
|
def redact_desc(desc, redact):
"""
Redacts bio for the final hint by removing any mention of
author's name, lastname, and any middle names, if present.
Returns a redacted string
"""
redacted_desc = desc
split_name = redact.split()
while split_name:
redacted_desc = redacted_desc.replace(split_name.pop(), "REDACTED")
return redacted_desc
|
def simplifyTitle(title, target):
"""
Simplify a given sequence title. Given a title, look for the first
occurrence of target anywhere in any of its words. Return a space-separated
string of the words of the title up to and including the occurrence of the
target. Ignore case.
E.g.,
# Suffix
simplifyTitle('Bovine polyomavirus DNA, complete genome', 'virus') ->
'Bovine polyomavirus'
# Prefix
simplifyTitle('California sea lion polyomavirus 1 CSL6994', 'polyoma') ->
'California sea lion polyoma'
# Contained
simplifyTitle('California sea lion polyomavirus 1 CSL6994', 'yoma') ->
'California sea lion polyoma'
title: The string title of the sequence.
target: The word in the title that we should stop at.
"""
targetLen = len(target)
result = []
for word in title.split():
if len(word) >= targetLen:
offset = word.lower().find(target.lower())
if offset > -1:
result.append(word[:offset + targetLen])
break
result.append(word)
return ' '.join(result)
|
def split_data(par):
"""
Splits the key and the value (in case they were indicated
from the user in the command-line, to be used in POSTs).
We had: par = "key=value";
We are returned: couple = ["key", "value"].
Args:
par -- parameters to be split
Returns:
couple -- list of two separated elements (key and value)
"""
couple = par.split('=')
return [couple[0], couple[1]]
|
def _get_edge_attrs(edge_attrs, concat_qualifiers):
""" get edge attrs, returns for qualifiers always a list """
attrs = dict()
if "qualifiers" not in edge_attrs:
attrs["qualifiers"] = []
elif edge_attrs["qualifiers"] is None:
attrs["qualifiers"] = edge_attrs["qualifiers"]
if attrs["qualifiers"] is None:
attrs["qualifiers"] = []
else:
attrs["qualifiers"] = edge_attrs["qualifiers"]
# add here the qualifiers afterwards from merged supernodes
if concat_qualifiers is not None:
attrs["qualifiers"] += concat_qualifiers
for key in edge_attrs.keys():
if key != "qualifiers":
attrs[key] = edge_attrs[key]
return attrs
|
def get_docker_command(container="telemetry"):
"""
API to return docker container command for execution
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param container:
:return:
"""
command = "docker exec -it {} bash".format(container)
return command
|
def noteToColour(note):
"""
Converts each note to it's corresponding valid BitTune note
note: Input letter (A-G | R)
returns: The string of the colour that represents note
"""
NOTES = {'A':'red','B':'orange','C':'yellow',
'D':'green','E':'blue','F':'indigo','G':'violet'
}
return NOTES[note]
|
def shorten(k):
"""
k an attrname like foo_bar_baz.
We return fbb, fbbaz, which we'll match startswith style if exact match
not unique.
"""
parts = k.split('_')
r = ''.join([s[0] for s in parts if s])
return r, r + parts[-1][1:]
|
def opdag(op):
"""Function that returns the string representing the conjugate transpose of
the operator.
"""
if '*' in op:
_op = op.split('*')
opout = opdag(_op[-1])
for i in range(len(_op)-1):
opout += '*'+opdag(_op[i-2])
elif '^' in op:
_op = op.split('^')
opout = opdag(_op[0])+'^'+_op[-1]
elif op == 'adag':
opout = 'a'
elif op == 'a':
opout = 'adag'
elif op == 'q':
opout = 'q'
elif op == 'p':
opout = 'p'
elif op == 'KE':
opout = 'KE'
elif op == 'n':
opout = 'n'
elif op == 'n+1':
opout = 'n+1'
else:
print(op)
raise ValueError("Not a valid operator for HO basis")
return opout
|
def zstrip(chars):
"""Return a string representing chars with all trailing null bytes removed.
chars can be a string or byte string."""
if isinstance(chars, bytes):
chars = str(chars.decode('ascii', 'ignore'))
if '\0' in chars:
return chars[:chars.index("\0")]
return chars
|
def check_equations_for_primes(var_a, var_b, primes):
"""Return the number of consecutive primes that result for variable
a and b for the formula: n**2 + an + b. Starting with zero.
"""
counter = 0
for i in range(0, 1_000):
temp = (i**2) + (i * var_a) + var_b
if temp not in primes:
break
counter += 1
return counter
|
def text_case_convert(text):
""" By default, use lower case
"""
return text.lower()
|
def oneline(sentence):
"""Replace CRs and LFs with spaces."""
return sentence.replace("\n", " ").replace("\r", " ")
|
def __assert_sorted(collection):
"""Check if collection is ascending sorted, if not - raises :py:class:`ValueError`
:param collection: collection
:return: True if collection is ascending sorted
:raise: :py:class:`ValueError` if collection is not ascending sorted
"""
if collection != sorted(collection):
raise ValueError('Collection must be ascending sorted')
return True
|
def fn_Z_squid(omega, L_squid, R_squid):
"""Dynamic squid impedance as a function of angular frequency omega and dynamical inductance L_squid and resistance R_squid."""
return ((1j * omega * L_squid)**-1 + (R_squid)**-1)**-1
|
def get_value(parent, match_address, match_value):
"""terraform 12 return json value"""
data = parent['resource_changes']
for x in range(len(data)):
if data[x]['address'] == match_address:
return data[x]['change']['after'][match_value]
return None
|
def validate_sample_name(query_name: str, sample_list):
"""
Function will validate the query name with a sample list of defined names and aliases
"""
verified_sample_name = [key for key, value in sample_list.items() if query_name.lower() in value['aliases']]
if verified_sample_name:
return verified_sample_name[0]
else:
return None
|
def get_html_attrs_tuple_attr(attrs, attrname):
"""Returns the value of an attribute from an attributes tuple.
Given a list of tuples returned by an ``attrs`` argument value from
:py:meth:`html.parser.HTMLParser.handle_starttag` method, and an attribute
name, returns the value of that attribute.
Args:
attrs (list): List of tuples returned by
:py:meth:`html.parser.HTMLParser.handle_starttag` method ``attrs``
argument value.
attrname (str): Name of the attribute whose value will be returned.
Returns:
str: Value of the attribute, if found, otherwise ``None``.
"""
response = None
for name, value in attrs:
if name == attrname:
response = value
break
return response
|
def pad_hexdigest(s, n):
"""Pad a hex string with leading zeroes
Arguments:
s (str): input hex string
n (int): number of expected characters in hex string
Returns:
(str): hex string padded with leading zeroes, such that its length is n
"""
return "0" * (n - len(s)) + s
|
def my_squares(iters):
"""list comprehension on squaring function"""
out=[i**2 for i in range(iters)]
return out
|
def scoreSolution( args, solution ) :
"""
Quantitatively rank a single solution.
Parameters:
args - the returned arguments from initAnnealer
solution - the solution to be measured
Higher scores are better.
Returns: A quantitative measure of goodness of the
proposed solution. The quantitative measure must be
greater than zero.
"""
cost = 0.0
for i in range(1, len(solution)) :
cost += args['matrix'][ solution[i-1] ][ solution[i] ]
return 1000000 - cost
|
def cycle_check(classes):
"""
Checks for cycle in clazzes, which is a list of (class, superclass)
Based on union find algorithm
"""
sc = {}
for clazz, superclass in classes:
class_set = sc.get(clazz, clazz)
superclass_set = sc.get(superclass, superclass)
if class_set != superclass_set:
# They belong to different sets. Merge disjoint set
for c in sc:
if sc[c] == class_set:
sc[c] = superclass_set
sc[superclass] = superclass_set
sc[clazz] = superclass_set
else:
# Part of same set. Cycle found!
return True
return False
|
def valid_input(instructions):
"""
Validate input to be a multi-line string containing directions [UDLR]+
:param instructions: Multiline string input
:return: Boolean value whether input is valid
"""
from re import match
m = match(r'[UDLR]+', ''.join(instructions))
return m is not None and m.span() == (0, sum(len(i) for i in instructions))
|
def mitad_doble(num1,num2):
"""
Entra un numero y se revisa si el primero es el doble del segundo
Num -> Str
:param num1: Numero a ser operado
:param num2: Numero a ser revisado
:return: Mensaje si uno es el doble del otro
>>> mitad_doble(7,14)
'Si es el doble de un impar'
>>> mitad_doble(7,15)
'No es el doble de un impar'
>>> mitad_doble('hola',5)
Traceback (most recent call last):
..
TypeError: No es valido
>>> mitad_doble(4,'jl')
Traceback (most recent call last):
..
TypeError: No es valido
"""
if str == type(num1) or str == type(num2):
raise TypeError('No es valido')
elif num1 % 2 != 0 and num1*2 == num2:
return 'Si es el doble de un impar'
else:
return 'No es el doble de un impar'
|
def std_chr_name(chrom_str):
"""Standardize chromosome name so it starts with 'chr'"""
if chrom_str.startswith("chr"):
return chrom_str
else:
if chrom_str.startswith("Chr"):
return "chr" + chrom_str[3:]
else:
return "chr" + chrom_str
|
def hex_color_for(rgb):
"""
Convert a 3-element rgb structure to a HTML color definition
"""
opacity_shade = 0.3
return "rgba(%d,%d,%d,%f)" % (rgb[0], rgb[1], rgb[2], opacity_shade)
|
def isnumber(obj):
"""
Tests if the argument is a number (complex, float or integer)
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(((obj is not None) and
(not isinstance(obj, bool)) and
(isinstance(obj, int) or
isinstance(obj, float) or
isinstance(obj, complex))))
)
|
def _to_list(a):
"""convert value `a` to list
Args:
a: value to be convert to `list`
Returns (list):
"""
if isinstance(a, (int, float)):
return [a, ]
else:
# expected to be list or some iterable class
return a
|
def actions_by_behavior(actions):
"""
Gather a dictionary grouping the actions by behavior (not SubBehaviors). The actions in each
list are still sorted by order of their execution in the script.
@param actions (list) of Action objects
@return (dict) where the keys are behaviors and the values are lists of actions
"""
split = {}
for action in actions:
for behavior in action.behaviors:
if behavior.name not in split:
split[behavior.name] = []
split[behavior.name].append(action)
return split
|
def probability_to_odds(prop):
"""Convert proportion to odds. Returns the corresponding odds
Returns odds
prop:
-proportion that is desired to transform into odds
"""
return prop / (1 - prop)
|
def _check_var_type(var_value, var_name, row):
"""
Function for check variable type and return dictionary in the format
{
"name": String,
"value": String
}
var_value: Input variable value
var_name: Input variable name
row: data
return: Variable dictionary.
"""
# Because we save as boolean string in db so it needs
# conversion
if var_value == 'false' or var_value == 'off':
var_value = False
var_dict = {
'name': var_name,
'value': var_value
}
if 'user_name' in row:
var_dict['role'] = row['user_name']
if 'db_name' in row:
var_dict['database'] = row['db_name']
return var_dict
|
def headers(token):
"""so far all headers are same. DRYs that up slightly."""
headers_obj = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
return headers_obj
|
def generate_instructions(instruction_info):
"""Generates an instruction string from a dictionary of instruction info given.
:params instruction_info: Dictionary
:returns: String of instructions
"""
return f"""Give {instruction_info['amount_per_dose']}
{'tablets' if instruction_info['form'] == 'tab' else 'ml'},
{instruction_info['frequency_day']}.
(every {instruction_info['frequency_hrs']} hrs)
for {instruction_info['duration']} days."""
|
def rad3d2(xyz):
""" Calculate radius to x,y,z inputted
Assumes the origin is 0,0,0
Parameters
----------
xyz : Tuple or ndarray
Returns
-------
rad3d : float or ndarray
"""
return xyz[0]**2 + xyz[1]**2 + xyz[-1]**2
|
def partition(message):
"""
Takes in a decoded message (presumably passed through prepare()) and
returns a list of all contained messages. The messages are strings
Example:
>>> partition("5 Hello6 World!")
['Hello', 'World!']
"""
messages = []
while len(message) > 0:
prefix = message[:4].strip()
try:
msg_len = int(prefix)
except ValueError:
print("Erroneous message prefix:", prefix)
msg_len = len(message) # assume that all that's left is this message
messages.append(message[4:4+msg_len]) # add message
message = message[4+msg_len:] # slice past current message to next message
return messages
|
def hamming_dist(puzzle):
"""Return the number of misplaced tiles."""
return len([i for i, v in enumerate(puzzle) if v != i+1 and v != len(puzzle)])
|
def walsh_iob_curve(t, insulin_action_duration):
"""Returns the fraction of a single insulin dosage remaining at the specified number of minutes
after delivery; also known as Insulin On Board (IOB).
This is a Walsh IOB curve, and is based on an algorithm that first appeared in GlucoDyn
See: https://github.com/kenstack/GlucoDyn
:param t: time in minutes since the dose began
:type t: float
:param insulin_action_duration: The duration of insulin action (DIA) of the patient, in minutes
:type insulin_action_duration: int
:return: The fraction of a insulin dosage remaining at the specified time
:rtype: float
"""
# assert insulin_action_duration in (3 * 60, 4 * 60, 5 * 60, 6 * 60)
iob = 0
if t >= insulin_action_duration:
iob = 0.0
elif t <= 0:
iob = 1.0
elif insulin_action_duration == 180:
iob = -3.2030e-9 * (t**4) + 1.354e-6 * (t**3) - 1.759e-4 * (t**2) + 9.255e-4 * t + 0.99951
elif insulin_action_duration == 240:
iob = -3.310e-10 * (t**4) + 2.530e-7 * (t**3) - 5.510e-5 * (t**2) - 9.086e-4 * t + 0.99950
elif insulin_action_duration == 300:
iob = -2.950e-10 * (t**4) + 2.320e-7 * (t**3) - 5.550e-5 * (t**2) + 4.490e-4 * t + 0.99300
elif insulin_action_duration == 360:
iob = -1.493e-10 * (t**4) + 1.413e-7 * (t**3) - 4.095e-5 * (t**2) + 6.365e-4 * t + 0.99700
return iob
|
def waterGmKgDryToPpmvDry(q):
"""
Convert water vapor Grams H2o / Kg dry air to ppmv dry air.
"""
Mair = 28.9648
Mh2o = 18.01528
return (q*1e3*Mair)/Mh2o
|
def mention_channel_by_id(channel_id):
"""
Mentions the channel by it's identifier.
Parameters
----------
channel_id : `int`
The channel's identifier.
Returns
-------
channel_mention : `str`
"""
return f'<#{channel_id}>'
|
def sum_numbers(seq_seq):
"""
Returns the sum of the numbers in the given sequence
of subsequences. For example, if the given argument is:
[(3, 1, 4), (10, 10), [1, 2, 3, 4]]
then this function returns 38
(which is 3 + 1 + 4 + 10 + 10 + 1 + 2 + 3 + 4).
Preconditions: the given argument is a sequences of sequences,
and each item in the subsequences is a number.
"""
# ------------------------------------------------------------------
# DONE: 4. Implement and test this function.
# Note that you should write its TEST function first (above).
# ------------------------------------------------------------------
sum = 0
for i in range(len(seq_seq)):
for j in range(len(seq_seq[i])):
sum += seq_seq[i][j]
return sum
|
def success_response(data):
""" When an API call is successful, the function is used as a simple envelope for the results,
using the data key, as in the following:
{
status : "success",
data : {
"posts" : [
{ "id" : 1, "title" : "A blog post", "body" : "Some useful content" },
{ "id" : 2, "title" : "Another blog post", "body" : "More content" },
]
}
required keys:
status: Should always be set to "success
data: Acts as the wrapper for any data returned by the API call. If the call returns no data (as in the last example), data should be set to null.
"""
return {'status': 'success','data': data}
|
def unpack(iter):
"""
Input: List of multiple comma seperated values as string.
Returns: list of unique values from the string.
"""
unique = []
for i in iter:
unique.extend(i.split(','))
return list(set(unique))
|
def remove_softclipped_reads(left, right, read_seq):
"""
Returns the read after removing softclipped bases.
:param left: int
left softclip
:param right: int
right softclip
:param read_seq: string
read sequence
:return softclipped_read_sequence: string
"""
if right == 0:
return read_seq[left:]
return read_seq[left:-right]
|
def _format_list(elems):
"""Formats the given list to use as a BUILD rule attribute."""
elems = ["\"{}\"".format(elem) for elem in elems]
if not elems:
return "[]"
if len(elems) == 1:
return "[{}]".format(elems[0])
return "[\n {},\n ]".format(",\n ".join(elems))
|
def accel_within_limits(v, a, v_range):
"""
Accelerate the car while clipping to a velocity range
Args:
v (int): starting velocity
a (int): acceleration
v_range (tuple): min and max velocity
Returns:
(int): velocity, clipped to min/max v_range
"""
v = v + a
v = max(v, v_range[0])
v = min(v, v_range[1])
return v
|
def to_node_label(label: str) -> str:
"""k8s-ifies certain special node labels"""
if label in {"instance_type", "instance-type"}:
return "node.kubernetes.io/instance-type"
elif label in {
"datacenter",
"ecosystem",
"habitat",
"hostname",
"region",
"superregion",
}:
return f"yelp.com/{label}"
return label
|
def get_remote_url(app_name):
"""Return the git remote address on Heroku."""
return "git@heroku.com:%s.git" % app_name
|
def perform_step(polymer: str, rules: dict) -> str:
"""
Performs a single step of polymerization by performing all applicable insertions; returns new polymer template string
"""
new = [polymer[i] + rules[polymer[i:i+2]] for i in range(len(polymer)-1)]
new.append(polymer[-1])
return "".join(new)
|
def make_wildcard(title, *exts):
"""Create wildcard string from a single wildcard tuple."""
return "{0} ({1})|{1}".format(title, ";".join(exts))
|
def GetExtension(filename):
"""Determine a filename's extension."""
return filename.lower().split('.')[-1]
|
def secondes(num_seconds: int) -> str:
"""Convert a number of seconds in human-readabla format."""
human_readable = []
if num_seconds >= 86400:
human_readable.append(f"{num_seconds//86400} days")
num_seconds %= 86400
if num_seconds >= 3600:
human_readable.append(f"{num_seconds//3600} hours")
num_seconds %= 3600
if num_seconds >= 60:
human_readable.append(f"{num_seconds//60} minutes")
num_seconds %= 60
if num_seconds > 0:
human_readable.append(f"{num_seconds} seconds")
return ", ".join(human_readable)
|
def hybrid_algorithm(avg, nearest, slope, silence=False):
"""hybrid algorithm based on average rating, nearest neighbour and slope one
I don't use slope one because it's hard to find the similar movie, so the performance
of slope one is poor.
"""
sign = (nearest - avg) / abs(nearest - avg)
ratio = 0.2
predict_value = nearest + sign * abs(nearest - avg) * ratio
if not silence:
print(' Hybrid Algorithm '.center(80, '#'))
print(round(predict_value), '(', predict_value, ')')
return predict_value
|
def remove_unicode(string):
"""
Removes unicode characters in string.
Parameters
----------
string : str
String from which to remove unicode characters.
Returns
-------
str
Input string, minus unicode characters.
"""
return ''.join([val for val in string if 31 < ord(val) < 127])
|
def opp(c):
"""
>>> opp('x'), opp('o')
('o', 'x')
"""
return 'x' if c == 'o' else 'o'
|
def left_bisect(sorted_list, element):
"""Find an element in a list (from left side)
"""
idxLeft = 0
idxRight = len(sorted_list) - 1
while idxLeft < idxRight:
# the middle is like taking the average of the left and right
# since we create an integer / truncate, this is a left bisection
idxMiddle = (idxLeft + idxRight) // 2
middle = sorted_list[idxMiddle]
# each time we take a step, get rid of half the range we have left
if middle < element:
idxLeft = idxMiddle + 1
elif middle >= element:
idxRight = idxMiddle
return idxLeft
|
def rename(imgName, char):
"""
Helper function for renaming output files
"""
title = imgName.split(".jpg")[0]
newTitle = "{}_{}.jpg".format(title, char)
return newTitle
|
def to_coord(width, height, coord):
""" returns the coordinate for a pixel in a list of pixels """
x = coord % width
y = coord // width
assert (y < height)
return (coord % width, coord // width)
|
def extract_lng(geocode):
"""Extract longitude from geocode result.
Extracts longitude from the geocode result (given by the google api).
Parameters
----------
geocode: dict
Dictionary of geocode results
"""
return geocode['geometry']['location']['lng']
|
def mapping_to_list(mapping):
"""Convert a mapping to a list"""
output = []
for key, value in mapping.items():
output.extend([key, value])
return output
|
def alleviate_cohorte(cohorte, threshold_alleviate):
"""
-> alleviate patient vector in cohorte : check the
discrete value of all parameter, if the count of
"normal" value is above the threshold_alleviate
the variable is deleted from all patient vector.
-> cohorte is a list of patient vector (i.e a list of lists)
-> threshold_alleviate is an int
-> return a cohorte ( i.e a list of lists)
"""
###################################
# Denombrement des variables avec #
# possedant une valeur normal #
###################################
paramToNormalCount = {}
for variable in cohorte[0]:
variableInArray = variable.split("_")
variableId = variableInArray[0]
paramToNormalCount[variableId] = 0
for patient in cohorte:
for variable in patient:
variableInArray = variable.split("_")
variableValue = variableInArray[1]
variableId = variableInArray[0]
if(variableValue == "normal"):
paramToNormalCount[variableId] = paramToNormalCount[variableId] + 1
###########################################
# Suppression des variables "trop normal" #
###########################################
listOfParameterToDelete = []
for variable in paramToNormalCount.keys():
if(paramToNormalCount[variable] > threshold_alleviate):
listOfParameterToDelete.append(variable)
for patient in cohorte:
for variable in patient:
variableInArray = variable.split("_")
variableValue = variableInArray[1]
variableId = variableInArray[0]
if(variableId in listOfParameterToDelete):
patient.remove(variable)
return cohorte
|
def sort_phrases(phrases):
"""Orders phrases alphabetically by their original text."""
def _sort_phrase(phrase):
original = phrase['original']
try: # Phrase numbers specified numerically for ordering purposes
int_val = int(original)
return str(int_val).zfill(4)
except ValueError:
return original
new_phrases = {}
for category_id, phrase_set in phrases.items():
new_phrases[category_id] = sorted(phrase_set, key=_sort_phrase)
return new_phrases
|
def clip_vertex(vertex, x_bounds, y_bounds):
"""Clips `Polygon` vertex within x_bounds and y_bounds.
Args:
vertex: 2-tuple, the x and y-coorinates of `Polygon` vertex.
x_bounds: 2-tuple, the min and max bounds in the x-dimension of the
original image.
y_bounds: 2-tuple, the min and max bounds in the y-dimension of the
original image.
Returns:
2-tuple, the clipped x and y-coorinates of `Polygon` vertex.
"""
x = vertex[0]
if x < x_bounds[0]:
x = x_bounds[0]
elif x > x_bounds[1]:
x = x_bounds[1]
y = vertex[1]
if y < y_bounds[0]:
y = y_bounds[0]
elif y > y_bounds[1]:
y = y_bounds[1]
return (x, y)
|
def pplummer(r, d0=1., rp=1.):
"""Derive a plummer sphere on r"""
return d0 / (1. + (r / rp)**2)**2
|
def no_filtering(
dat: str,
thresh_sam: int,
thresh_feat: int) -> bool:
"""Checks whether to skip filtering or not.
Parameters
----------
dat : str
Dataset name
thresh_sam : int
Samples threshold
thresh_feat : int
Features threshold
Returns
-------
skip : bool
Whether to skip filtering or not
"""
skip = False
if not thresh_sam and not thresh_feat:
print('Filtering threshold(s) of 0 do nothing: skipping...')
skip = True
thresh_sam_is_numeric = isinstance(thresh_sam, (float, int))
thresh_feat_is_numeric = isinstance(thresh_feat, (float, int))
if not thresh_sam_is_numeric or not thresh_feat_is_numeric:
print('Filtering threshold for %s not a '
'integer/float: skipping...' % dat)
skip = True
if thresh_sam < 0 or thresh_feat < 0:
print('Filtering threshold must be positive: skipping...')
skip = True
return skip
|
def first_one(n):
"""Replace each digit in a number with its distance -- in digits -- from the
first 1 to come *after* it. Any number that does not have a 1 after it will
be replaced by a 0, and two digits side-by-side have a distance of 1. For
example, 5312 would become 2100. '5' is 2 away from 1, and '3' is 1 away.
The '1' itself and '2' have no ones after it, so they both become 0s. Assume
there is no distance greater than 9.
>>> first_one(10001)
43210
>>> first_one(151646142)
214321000
"""
def next_dist(last, dist):
if last == 1:
return 1
return 0 if dist == 0 else dist + 1
dist, i, new = 0, 0, 0
while n:
n, last, new = n // 10, n % 10, new + (10**i * dist)
dist, i = next_dist(last, dist), i + 1
return new
|
def unconvert_from_RGB_255(colors):
"""
Return a tuple where each element gets divided by 255
Takes a (list of) color tuple(s) where each element is between 0 and
255. Returns the same tuples where each tuple element is normalized to
a value between 0 and 1
"""
return (colors[0]/(255.0),
colors[1]/(255.0),
colors[2]/(255.0))
|
def format_ucx(name, idx):
"""
Formats a name and index as a collider
"""
# one digit of zero padding
idxstr = str(idx).zfill(2)
return "UCX_%s_%s" % (name, idxstr)
|
def is_sha1(instring):
"""Check if instring is sha1 hash."""
if instring.endswith("-f"):
instring = instring[:-2]
if len(instring) != 40:
return False
try:
int(instring, 16)
except ValueError:
return False
return True
|
def time_to_min(time):
"""Convert time in this format hhmm into minutes passed sind 0000
0830->510
1345->825
"""
minutes = time%100
hours = time//100
return hours*60+minutes
|
def get_objects_names(xml_object_list):
"""
Method that returns a list with all object aliases/names from object's list
"""
object_name_list = []
# Create the xml [object_name (and object_alias)] list
for xml_object in xml_object_list:
object_name_list.append(xml_object.name)
try:
if len(xml_object.alias) > 0:
object_name_list.append(xml_object.alias)
except AttributeError:
# To avoid error when there is no alias attribute for the object
pass
return object_name_list
|
def describe_weather(degrees_fahrenheit):
""" Describes the weather (according to Marc)
Uses conditional logic to return a string description of the weather based
on degrees fahrenheit.
Parameters
----------
degrees_fahrenheit : int
The temperature in degrees fahrenheit. Used to reason about weather
conditions.
Returns
-------
string
String description of weather conditions.
"""
# Begins conditional logic with our baseline "if."
if degrees_fahrenheit < -40:
return(f"{degrees_fahrenheit} is unbelievably cold!")
# Elif means 'if the previous condition wasn't true, see if this one is true,"
# so there's no reason to state "if temperature >= -40 and temperature < 0.
elif degrees_fahrenheit < 0:
return(f"{degrees_fahrenheit} is too cold to do anything outside.")
elif degrees_fahrenheit < 30:
return(f"{degrees_fahrenheit} is freezing.")
elif degrees_fahrenheit < 50:
return(f"{degrees_fahrenheit} is chilly but manageable")
elif degrees_fahrenheit < 75:
return(f"{degrees_fahrenheit} is beautiful!")
elif degrees_fahrenheit < 100:
return(f"{degrees_fahrenheit} is pretty warm.")
else:
return(f"{degrees_fahrenheit} is hot!")
|
def _get_parent(child_index, parent_diff, parent_indices):
"""Private function to find the parent of the given child peak. At child peak index, follow the
slope of parent scale upwards to find parent
Parameters
----------
child_index: int
Index of the current child peak
parent_diff: list of ?
?
parent_indices: list of int ?
Indices of available parents
Returns
_______
int
The parent index or None if there is no parent
"""
for i in range(0, len(parent_indices)):
if (parent_indices[i] > child_index):
if (parent_diff[int(child_index)] > 0):
return parent_indices[i]
else:
if i > 0:
return parent_indices[i-1]
else:
return parent_indices[0]
if len(parent_indices) > 0:
return parent_indices[-1]
return None
|
def find_gc(seq: str) -> float:
""" Calculate GC content """
if not seq:
return 0
gc = len(list(filter(lambda base: base in 'CG', seq.upper())))
return (gc * 100) / len(seq)
|
def cmps(s1, s2):
"""
helper to compare two strings
:param s1: left string
:param s2: right string
:return comparison result as -1/0/1
"""
if (s1 == s2):
return 0
if (s1 < s2):
return -1
return 1
|
def sum_numbers(*values: float) -> float:
""" calculates the sum of all the numbers passed as arguments """
sum = 0
for value in values:
sum += value
return sum
# return sum(values)
|
def index_restrict(i, arr):
"""
Quick Internal Function - ensure that index i is appropriately bounded for the given arr;
i.e. 0 <= i < len(arr)
:param i:
:param arr:
:return:
"""
if i < 0:
i = 0
elif i > len(arr) - 1:
i = len(arr) - 1
return i
|
def calculate_q_c1n(qc, CN):
"""
qc1n from CPT, Eq 2.4
"""
q_c1n = CN * qc * 1000 / 100
return q_c1n
|
def is_multiple_of(a: int, b: int):
"""Check if a is a multiple of b"""
return a % b == 0
|
def to_huf(amount: int) -> str:
"""
Amount converted to huf with decimal marks, otherwise return 0 ft
e.g. 1000 -> 1.000 ft
"""
if amount == "-":
return "-"
try:
decimal_marked = format(int(amount), ',d')
except ValueError:
return "0 ft"
return f"{decimal_marked.replace(',', '.')} ft"
|
def unf_gas_density_kgm3(t_K, p_MPaa, gamma_gas, z):
"""
Equation for gas density
:param t_K: temperature
:param p_MPaa: pressure
:param gamma_gas: specific gas density by air
:param z: z-factor
:return: gas density
"""
m = gamma_gas * 0.029
p_Pa = 10 ** 6 * p_MPaa
rho_gas = p_Pa * m / (z * 8.31 * t_K)
return rho_gas
|
def flatten(_list):
"""Flatten a 2D list to 1D"""
# From http://stackoverflow.com/a/952952
return [item for sublist in _list for item in sublist]
|
def subreddit_idx_to_subreddit(idx):
"""
Warning: temporarily hardcoded for convenience. Beware!
:param idx:
:return:
"""
subreddits = {0: '100DaysofKeto',
1: 'AskMen',
2: 'AskMenOver30',
3: 'AskWomen',
4: 'AskWomenOver30',
5: 'LGBTeens',
6: 'OkCupid',
7: 'Tinder',
8: 'childfree',
9: 'fatlogic',
10: 'financialindependence',
11: 'infertility',
12: 'infj',
13: 'keto',
14: 'loseit',
15: 'proED',
16: 'sexover30',
17: 'short',
18: 'tall',
19: 'xxketo'}
return subreddits[idx]
|
def _is_odd(num):
"""
Check if a number is even or odd. Returns True if odd and False if even.
Parameters
----------
num : int
Integer number to check
Returns
-------
condition : bool
True if odd and False if even
"""
return bool(num & 0x1)
|
def trunc(x):
"""Implementation of `trunc`."""
return x.__trunc__()
|
def queenCanTattack(board, size, row, column):
"""Check if the new queen will not be able to attack an other one.
Args:
board (array): board on which the queen will be
size (int): size of the board
row (int): row position on the board
column (int): column position on the board
Returns:
[boolean]: True, if unable to attack
"""
can_t_attack = True
# check cardinals
for idx_row in range(size):
if idx_row != row and board[idx_row][column] == 1:
return not can_t_attack
for idx_column in range(size):
if idx_column != column and board[row][idx_column] == 1:
return not can_t_attack
# check diagonals
for idx_row, idx_column in zip(range(row - 1, -1, -1),
range(column + 1, size)):
if board[idx_row][idx_column] == 1:
return not can_t_attack
for idx_row, idx_column in zip(range(row + 1, size),
range(column + 1, size)):
if board[idx_row][idx_column] == 1:
return not can_t_attack
for idx_row, idx_column in zip(range(row - 1, -1, -1),
range(column - 1, -1, -1)):
if board[idx_row][idx_column] == 1:
return not can_t_attack
for idx_row, idx_column in zip(range(row + 1, size),
range(column - 1, -1, -1)):
if board[idx_row][idx_column] == 1:
return not can_t_attack
return can_t_attack
|
def fix_saving_name(name):
"""Neutralizes backslashes in Arch-Vile frame names"""
return name.rstrip('\0').replace('\\', '`')
|
def to_unicode_repr(_letter):
"""helpful in situations where browser/app may recognize Unicode encoding
in the \u0b8e type syntax but not actual unicode glyph/code-point"""
# Python 2-3 compatible
return "u'" + "".join(["\\u%04x" % ord(l) for l in _letter]) + "'"
|
def insertionsort(x, count = False):
"""
For each element e of x, move through the array until you come to a value
that is less than e, or the end of the array, then place e at the new location.
"""
assignments, conditionals = 0, 0
for i in range(1, len(x)):
element = x[i]
j = i - 1
assignments += 2
while j > -1 and x[j] > element:
conditionals += 2
x[j+1] = x[j]
j -= 1
assignments += 2
x[j+1] = element
assignments += 1
if not count:
return x
else:
return assignments, conditionals
|
def interval_str_to_int_values(s):
"""
Converts a string in the format '1-5,10-100:10,1000,1000' to a list ordered numbers:
[1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 1000].
a-b will be converted to all numbers between a and b, including a and b and incrementing by 1.
a-b:n will be converted to all numbers between a and b, including a and b and incrementing by n.
All values are separated by a comma and single values are included as-is.
If repeated values are generated, they are included only once.
"""
int_values = []
intervals = s.split(',')
for interval in intervals:
parts = interval.split('-')
if len(parts) == 1:
int_values.append(int(parts[0]))
else:
start = int(parts[0])
end_by = parts[1].split(':')
end = int(end_by[0])
if len(end_by) == 1:
int_values.extend(list(range(start, end + 1)))
else:
by = int(end_by[1])
int_values.extend(list(range(start, end + 1, by)))
return sorted(set(int_values))
|
def tpatt(tag):
"""
Return pattern matching a tag found in comma separated string.
(?i) : case-insensitive flag
^{tag}\\s*, : matches beginning
,\\s*{tag}\\s*, : matches middle
,\\s*{tag}$ : matches end
^{tag}[^\\w+] : matches single entry ( no commas )
"""
patt = fr"(?i)(^{tag}\s*,|,\s*{tag}\s*,|,\s*{tag}$|^{tag}$)"
return patt
|
def actions(context, request):
""" Renders the drop down menu for Actions button in editor bar.
:result: Dictionary passed to the template for rendering.
:rtype: dict
"""
actions = []
if hasattr(context, "type_info"):
actions = [
a for a in context.type_info.action_links if a.visible(context, request)
]
return {"actions": actions}
|
def fibonacci(n: int) -> int:
"""Return the nth fibonacci number
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(10)
55
>>> fibonacci(20)
6765
>>> fibonacci(-2)
Traceback (most recent call last):
...
ValueError: n must be >= 0
"""
if n < 0:
raise ValueError("n must be >= 0")
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
|
def pretty_size_kb(value):
"""
More human-readable value instead of zillions of digits
"""
if value < 1024:
return str(value) + " KB"
if value < 1024 * 1024:
return str(value/1024) + " MB"
return str(value/(1024*1024)) + " GB"
|
def find_low_index(arr, key):
"""Find the low index of the key in the array arr.
Time: O(log n)
Space: O(1)
"""
lo, hi = 0, len(arr)
while lo < hi:
mi = (lo + hi) // 2
if arr[mi] < key:
lo = mi + 1
elif arr[mi] == key and (mi == 0 or arr[mi - 1] < key):
return mi
else:
hi = mi
return -1
|
def adjust_edges(outer, inner):
"""
outer: foo bar bat ham spam
inner: ar bat ha
returns: bar bat ham
"""
# :(
# assert inner in outer, f"WTF: {inner} NOT IN {outer}"
orig_outer = outer
outer = outer.lower()
inner = inner.lower()
left = outer.find(inner)
right = left + len(inner)
while left != 0 and outer[left - 1] != " ":
left -= 1
while right != len(outer) and outer[right] != " ":
right += 1
return orig_outer[left:right]
|
def get_latest_checkpoint(file_names):
"""Get latest checkpoint from list of file names.
Only necessary
if manually saving/loading Keras models, i.e., not using the
tf.train.Checkpoint API.
Args:
file_names: List[str], file names located with the `parse_keras_models`
method.
Returns:
str, the file name with the most recent checkpoint
"""
if not file_names:
return None
checkpoint_epoch_and_file_name = []
for file_name in file_names:
try:
checkpoint_epoch = file_name.split('/')[-2].split('_')[-1]
except ValueError:
raise Exception('Expected Keras checkpoint directory path of format '
'gs://path_to_checkpoint/keras_model_{checkpoint_epoch}/')
checkpoint_epoch = int(checkpoint_epoch)
checkpoint_epoch_and_file_name.append((checkpoint_epoch, file_name))
return sorted(checkpoint_epoch_and_file_name, reverse=True)[0][1]
|
def remove_end_plus(s):
"""Remove plusses at the end."""
r = s[::-1]
new_s = ""
seen_minus = False
for el in r:
if not seen_minus:
if el == "-":
seen_minus = True
new_s = el
else:
new_s += el
return new_s[::-1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.