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., ... |
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``.
P... |
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(no... |
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.r... |
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.,
# S... |
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... |
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 at... |
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 NO... |
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('^... |
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:
... |
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(coll... |
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... |
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.
A... |
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)) + ... |
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 solutio... |
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 !=... |
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 a... |
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'
>>> mi... |
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
... |
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... |
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.
"""
# ... |
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'] ==... |
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) ... |
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://gi... |
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 argum... |
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"... |
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 rig... |
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
... |
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",
"sup... |
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(... |
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//3... |
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)
rati... |
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 <... |
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 bisecti... |
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... |
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)
... |
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 ... |
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
... |
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 ... |
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),
... |
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)
tr... |
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 reaso... |
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: lis... |
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.... |
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 =... |
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',... |
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
Retu... |
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... |
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 co... |
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 )
"""
... |
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 ... |
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:
ra... |
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):
... |
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 + le... |
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, t... |
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.