content stringlengths 42 6.51k |
|---|
def splitMyString(c, str_in):
"""
Version 1: Manually as an exercise.
Returns a list of strings separated by character 'c' where 'c' is the
"splitter" character and 'str_in' is the string.
Example Usage:
splitMyString('*', 'aaa*sss*fff') returns: ['aaa', 'sss', 'fff']
spli... |
def tuple_int(pairstr):
"""Convert NxNx... or N,N,... to tuple."""
return tuple(int(_s) for _s in pairstr.replace('x', ',').split(',')) |
def get_complement(nucleotide):
""" Returns the complementary nucleotide
nucleotide: a nucleotide (A, C, G, or T) represented as a string
returns: the complementary nucleotide
>>> get_complement('A')
'T'
>>> get_complement('C')
'G'
>>> get_complement('G')
'C'
>>> get_comp... |
def max_bitrate_ext(val):
"""
Given ESM value, return extended maximum bit rate (Kbps).
Please refer to 10.5.6.5, TS24.008 for more details.
:param val: the value encoded in the ESM NAS message
"""
if val <= 74:
return 8600 + val * 100
elif val <= 186:
return 16000 + (val - ... |
def GetNextObject(obj, stop_objs=None):
""" Return the next object in the hierarchy using a depth-first traversal scheme.
If stop_objs is a c4d.BaseObject or a list of c4d.BaseObjects and the next
operation would encounter this object (or the first object in the list) None
will be returned. This is... |
def merge_two_dicts(x, y):
"""
Given two dictionaries, merge them into a new dict as a shallow copy.
"""
for key, value in y.items():
x[key] = value
return x |
def mini_batch_size_update(mini_batch_size, gpu_count):
"""Increase mini-batch size to accommodate more than 1 GPU."""
if gpu_count <= 1:
return mini_batch_size
elif gpu_count > 1:
return mini_batch_size * gpu_count |
def combine(main_busytime_list, merging_list):
"""
given two lists of busytimes, returns list of busytimes that have events of the same day together
"""
merged = [ ]
days = { }
current_date = ''
#this creates the dates dict
for busytime in main_busytime_list:
if busytime['date'] ... |
def find_outlier(integers):
"""Return whatever number is an outlier from a list, even or odd."""
def is_even(number):
if number % 2:
return -1
else:
return 1
odd_or_even = is_even(integers[0])
+ is_even(integers[1]) + is_even(integers[2])
if odd_or_even > 0:... |
def RPL_ENDOFWHOIS(sender, receipient, message):
""" Reply Code 318 """
return "<" + sender + ">: " + message |
def get_command_help_messsage(command: str) -> str:
"""
Get the help message for a command.
Parameters
----------
command : str
Name of the command.
Returns
-------
str
Command's help message.
"""
return f'Show {command} command help message.' |
def check_runs(run0, run1, runs):
"""Checks run parameters, and returns necessary values
Behaviour:
if runs is None: assume full span from run0-run1
if runs is not None: use runs specified
Returns:
run0, run1, runs
"""
if (run0 is None
and run1 is None
... |
def crossPoint(lineA, lineB):
"""
the intersection point of two line. Note that if the intersection point is the start of line B,
then return the start of line B, but if the intersection point is the end of line B, it will be regarded as
there is no intersection point, avoiding repeated calculation.... |
def normalize_newlines(a_string):
"""Given a string (can be Unicode or not), turns all newlines into '\n'."""
return a_string.replace('\r\n', '\n').replace('\r', '\n') |
def reverse_word(word):
"""
Reverses the order of the characters in the given word.
For example:
- If we call reverse_word("abcde"), we'll get "edcba" in return
- If we call reverse_word("a b c d e"), we'll get "e d c b a" in return
- If we call reverse_word("a b"), we'll get "b a" in return
... |
def ferret_result_limits(efid):
"""
Abstract axis limits for the shapefile_writexyval PyEF
"""
return ( (1, 1), None, None, None, None, None, ) |
def remove_suffix(s, suffix):
"""
Removes a prefix from a string.
Raises ValueError if the prefix is not there.
"""
if s.endswith(suffix):
return s[:-len(suffix)]
else:
msg = 'Expected suffix %r in %r' %( suffix, s)
raise ValueError(msg) |
def right(spiral: list, coordinates: dict) -> bool:
"""
Move spiral right
:param coordinates: starting point
:param spiral: NxN spiral 2D array
:return: boolean 'done'
"""
done = True
while coordinates['col'] < len(spiral[coordinates['row']]):
row = coordinates['row']
col = coordinates['c... |
def Fahrenheit_C(Celsius):
"""Usage: Convert to Fahrenheit from Celsius
Fahrenheit_C(Celsius)"""
return (Celsius* 9/5)+32 |
def expand_slice(sel, n, nowrap=False):
"""Expands defaults and negatives in a slice to their implied values.
After this, all entries of the slice are guaranteed to be present in their final form.
Note, doing this twice may result in odd results, so don't send the result of this
into functions that expect an unexpa... |
def normalize(match):
"""
Keep the right links
:param match: the match line
:return: a clear line
"""
partition = match.split("|")
normal_form = ""
if len(partition) >= 1:
normal_form = partition[0]
return normal_form |
def validate_email(email):
""" validate an email string """
import re
a = re.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")
if a.match(email):
return False
return True |
def non_repeat_substring(s):
"""Find the length of the longest substring with no repeating characters.
Time: O(n)
Space: O(1) // size of the alphabet for the set
>>> non_repeat_substring("")
0
>>> non_repeat_substring("a")
1
>>> non_repeat_substring("aabccbb")
3
>>> non_repeat... |
def title(name):
""" Write title keyword"""
return [f'*TITLE\n{name:s}\n'] |
def _show_table_set_segment_insert_new_column(segment, column):
"""
Insert a new column into the current segment.
"""
segment['columns'].append(column)
segment['length'] += 3 + segment['table']['lengths'][column]
return len(segment['columns']) - 1 |
def adder2(a, b, adder2_offset=0):
"""Adder + offset
"""
return (a + b) + adder2_offset |
def f(x):
"""
"""
return x**2 + x + 3 |
def calculateCheckDigit(number):
"""Calculate a check digit with mod 10, weight 3.
This check digit calculation is the same as for EAN/GTIN.
See also: https://en.wikipedia.org/wiki/Check_digit and
https://www.gs1.org/services/check-digit-calculator
"""
checkDigit = 0
sum = 0
... |
def get_fuel_from(mass: int) -> int:
"""Gets fuel from mass.
Args:
mass (int): mass for the fuel
Returns:
int: fuel necessary for the mass
"""
return mass // 3 - 2 |
def matrix_vector_multiply(M, v):
"""
Multiply n * n matrix M with a
n-dimensional vector v
"""
return [
sum([v[k] * m for k, m in enumerate(M[i])])
for i in range(len(M))
] |
def split_fqdn(fqdn):
"""
Unpack fully qualified domain name parts.
"""
if not fqdn:
return [None] * 3
parts = fqdn.split(".")
return [None] * (3 - len(parts)) + parts[0:3] |
def infinite_slope(vector_one, vector_two):
"""Check if provided vectors for line imply an infinite slope"""
return(vector_one[0] == vector_two[0]) |
def _parse_svg_color(color):
"""Return RGB integers from Inkscape color.
@type color: `str`
@rtype: `tuple` (triplet)
"""
if color[0] != '#':
raise Exception('only hash-code colors are supported!')
red = int(color[1:3], 16)
green = int(color[3:5], 16)
blue = int(color[5:7], 16)
... |
def parse_float_tuble(par_tup):
"""
Formates the raw input from ConfigParser (e.g. '(0, 0, 1)') to
(0.0, 0.0, 1.0)
"""
return tuple([float(i) for i in par_tup.strip('(').strip(')').split(',')]) |
def f1(predictions, gold):
"""
F1 (a.k.a. DICE) operating on two lists of offsets (e.g., character).
>>> assert f1([0, 1, 4, 5], [0, 1, 6]) == 0.5714285714285714
:param predictions: a list of predicted offsets
:param gold: a list of offsets serving as the ground truth
:return: a score between 0 ... |
def get_temporary_submission_data_name(sid: str, file_hash: str) -> str:
"""The HashMap used for tracking auxiliary processing data."""
return '/'.join((sid, file_hash, 'temp_data')) |
def is_odd(number):
"""Determine if a number is odd."""
if number % 2 == 0:
return False
else:
return True |
def pack(pieces=()):
"""
Join a sequence of strings together.
:param list pieces: list of strings
:rtype: bytes
"""
return b''.join(pieces) |
def project(atts, row, renaming={}):
"""Create a new dictionary with a subset of the attributes.
Arguments:
- atts is a sequence of attributes in row that should be copied to the
new result row.
- row is the original dictionary to copy data from.
- renaming is a mapping of name... |
def get_number_of_bills (budget, denomination):
"""
:param budget: float - the amount of money you are planning to exchange.
:param denomination: int - the value of a single bill.
:return: int - number of bills after exchanging all your money.
"""
return int (budget / denomination) |
def predict_gender(x_coverage, y_coverage):
"""Make a simple yet accurate prediction of a samples gender.
The calculation is based on the average coverage across the X and Y
chromosomes. Note that an extrapolation from a subsection of bases is
usually quite sufficient.
Args:
x_coverage (float): estimate... |
def fscore(precision, recall):
"""Computes F1-score based on precision and recall."""
fscore = 0.0
if precision + recall > 0:
fscore = 2*(precision*recall)/(precision+recall)
return fscore |
def get_metric_name(metric_label):
"""Returns pushgateway formatted metric name."""
return 'mq_manager_{0}'.format(metric_label) |
def sumdiffsquared(x, y):
"""
Takes pairwise differences of the values in lists x and y, squares
these differences, and returns the sum of these squares.
Usage: lsumdiffsquared(x,y)
Returns: sum[(x[i]-y[i])**2]
"""
sds = 0
for i in range(len(x)):
sds = sds + (x[i] - y[i]) ** 2
return sds |
def getCriticality(cvss):
""" color convention fot the cells of the PDF """
if cvss == 0.0:
return ("none", "#00ff00", (0, 255, 0))
if cvss < 3.1:
return ("low", "#ffff00", (255, 255, 0))
if cvss < 6.1:
return ("medium", "#ffc800", (255, 200, 0))
if cvss < 9.1:
return... |
def powerResidue(N, seed=None, a=273673163155, c=13, M=2**48):
""" Calculate a series of random numbers
"""
import datetime
if seed == None:
#print("Seed value set to NONE, defaulting to system time.")
seed=int(datetime.datetime.now().strftime("%Y%M%d%H%M%S"))
else:
pass
... |
def likelihood_start_end_times_close(filetimes: list, compare_times: list, allowable_diff: int = 2):
"""
Take in a list of [starttime, endtime] and find the closest match to compare_times. Times are provided in terms of
utc seconds. If none are close in allowable_diff seconds, returns empty list
Othe... |
def all_chars_to_hex(source):
"""
Converts input string into hex for all chars.
:param source: input string.
:return: output string witch exchanged chars.
"""
output = ""
for char in source:
output += "\\x{:02x}".format(ord(char))
return output |
def euclid2cosine(euclid_dis):
"""
Convert normalized euclidean distance -> cosine
Note: this's lossy method.
"""
return (euclid_dis ** 2) / 2 |
def decrementday(year, month, day):
"""
Given values for year, month, and day, the values of the previous day are
returned. At the moment, the function assumes that every month has 31 days,
so that it will return February 31st when given values for March 1.
Parameters
----------
year : inte... |
def celsius(fah):
"""Pasa una cantidad de grados Fahrenheit a Celsius"""
c = 5/9 * (fah - 32)
return c |
def every(pred, seq):
""" returns True iff pred is True for every element in seq """
for x in seq:
if not pred(x): return False
return True |
def is_src(node):
"""
Returns True if node has attr 'is_src', as is thereby
implicitly set
"""
return hasattr(node, "is_src") |
def fibonacci(n):
"""
Memoixation solution to fibonacci.
:param n: an integer value.
:return: the fibonacci number.
"""
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2) |
def int_pairs_leq_n_when_summed(n):
"""
Construct a list of pairs of integers (>=0) such that the sum of each pair
is less or equal `n`.
Parameters
----------
n : int
Upper bound for the sum of each pair.
Returns
-------
pairs_list : list
A list of tuples. Each tupl... |
def setdefault(s,default):
"""
>>> setdefault('message','default')
'message'
>>> setdefault('','default')
'default'
>>> setdefault(None,'default')
'default'
"""
if s:
return s
else:
return default |
def overlap(reg1, reg2):
"""
Return overlap between two regions.
e.g. [10, 30], [20, 40] returns [20, 30]
"""
try:
intersect = set(range(reg1[0], reg1[1] + 1)).intersection(
set(range(reg2[0], reg2[1] + 1)))
intersect = sorted(intersect)
return [intersect[0]] + [i... |
def dec2bcd(dec):
"""Decimal to Binary Coded Decimal conversion
Parameters
----------
dec : decimal number
Returns
----------
bcd : int, binary coded decimal
"""
t = dec // 10
o = dec - t * 10
return (t << 4) + o |
def hamming(set1, set2):
"""
Hamming distance between sets `set1` and `set2`.
The Hamming distance for sets is the size of their symmetric difference,
or, equivalently, the usual Hamming distance when sets are viewed as 0-1-strings.
Parameters
----------
set1, set2 : set of int
... |
def get_cds_obj(cds_id, pred_cds):
"""Find the CDS object given an id
:param cds_id: id of the CDS to find
:param pred_cds: dictionary of the predicted CDS
:return: a CDS object
"""
if cds_id not in pred_cds:
raise ValueError("CDS not found for %s" % (cds_id))
return pred_cds[cds_i... |
def exp_move(x, loan_repay_fn, bounds=[300, 850], move_vec=[-150, 75]):
"""compute expected move in score"""
move_down = move_vec[0]
move_up = move_vec[1]
move = (1 - loan_repay_fn(x)) * move_down + loan_repay_fn(x) * move_up
move_to_within_bounds = max(min(x + move, bounds[1]), bounds[0])
move_... |
def validateRefs(cmodel):
"""Validate references for models and layers.
Args:
cmodel (dict): Sub-dictionary from config for specific model.
Returns:
tuple: (modelrefs, longrefs, shortrefs) where:
* modelrefs: dictionary of citation information for model
keys='lo... |
def strip_dots(path):
"""Strip '.' and '..' components from path"""
if (path == "/"):
return path
out = []
for p in path[1:].split('/'):
if p == "..":
if len(out) != 0:
del out[-1]
else:
out.append(p)
elif p != ".":
out.append(p)
return "/" + "/".join(out) |
def textwrap_unwrap_first_paragraph(text):
"""Join by single spaces all the leading lines up to the first empty line"""
index = (text + "\n\n").index("\n\n")
lines = text[:index].splitlines()
chars = " ".join(_.strip() for _ in lines)
alt_text = chars + text[index:]
return alt_text |
def get_entry_or_none(base: dict, target, var_type=None):
"""Helper function that returns an entry or None if key is missing.
:param base: dictionary to query.
:param target: target key.
:param var_type: Type of variable this is supposed to be (for casting).
:return: entry or None.
"""
if ... |
def init(client, **kwargs):
"""
:param client:
:param kwargs:
:return:
"""
global g_client
g_client = client
return True |
def sortnodes(nodes, parentfunc):
"""Topologically sorts the nodes, using the parentfunc to find
the parents of nodes."""
nodes = set(nodes)
childmap = {}
parentmap = {}
roots = []
# Build a child and parent map
for n in nodes:
parents = [p for p in parentfunc(n) if p in nodes]
... |
def normalize_medical_kind(shape, properties, fid, zoom):
"""
Many medical practices, such as doctors and dentists, have a speciality,
which is indicated through the `healthcare:speciality` tag. This is a
semi-colon delimited list, so we expand it to an actual list.
"""
kind = properties.get('k... |
def _rear_left_tire_pressure_value(data, unit_system):
"""Get the rear left tire pressure value."""
return round(data["status"]["tirePressure"]["rearLeftTirePressurePsi"]) |
def bingify(s):
""" because bing has to be an asshole and require special params """
return "'{}'".format(s) |
def parse_delay(delay):
"""Parses delay strings - strips non-numerics and converts from str to int
Args:
delay (str): The delay in str format
Returns:
int: The delay value
"""
number_str_array = [c for c in delay if c.isdigit()]
number = int(''.join(number_str_array))
if de... |
def tab_in_leading(s):
"""Returns True if there are tabs in the leading whitespace of a line,
including the whitespace of docstring code samples."""
n = len(s)-len(s.lstrip())
if not s[n:n+3] in ['...', '>>>']:
check = s[:n]
else:
smore = s[n+3:]
check = s[:n] + smore[:len(sm... |
def fontInfoPostscriptOtherBluesValidator(values):
"""
Version 2+.
"""
if not isinstance(values, (list, tuple)):
return False
if len(values) > 10:
return False
if len(values) % 2:
return False
for value in values:
if not isinstance(value, (int, float)):
return False
return True |
def efd_name(csc, topic):
"""Get a fully qualified EFD topic name.
Parameters
----------
csc : str
The name of the CSC.
topic : str
The name of the topic.
"""
return f"lsst.sal.{csc}.{topic}" |
def get_longest_string(in_list):
"""
Get the longest string(s) in a list.
:param in_list: list of strings
:return: single string if there's only one with the max length,
or a list of strings if there are several.
"""
if len(in_list) == 0:
return None
max_length = max(le... |
def practice_problem2b(sequence):
"""
What comes in:
-- A sequence of strings, e.g. ('hello', 'Bye', 'ok joe')
What goes out:
-- Returns the string that contains the first letter in
each of the strings in the given sequence,
in the order in which they appear in the sequence... |
def select_exp_metadata(metadata):
"""select the metadata that is valid for all data in an exp_data collection"""
avoid = ['medium_app_key', 'full_app_key', 'iteration_index', 'id', 't']
selection = {}
for k, v in metadata.items():
if k in avoid:
continue
selection[k] = v
... |
def reverse_lookup(d,val):
"""
build a list of k's
search k s.t d[k] = val
"""
listed = []
for k in d:
if d[k]==val:
listed.append(k)
return listed |
def conductivity_to_imaginary_permittivity(freq: float,
conductivity: float) -> float:
"""Converts between conductivity and imaginary permittivity
This is a simple and straightforward conversion between the value
of conductivity, in S/m, and the imaginary part of ... |
def formatTime(seconds: int) -> str:
"""Fortmats youtube time"""
hours = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hours == 0:
return "%02i:%02i" % (minutes, seconds)
else:
return "%02i:%02i:%02i" % (hours, minutes, seconds) |
def _get_nton_name(nton, prefix=''):
"""Given the number of strains in which a polymorphism/substitution is found, give the appropriate SFS name."""
named = {1: 'single', 2: 'double', 3: 'triple', 4: 'quadruple', 5: 'quintuple'}
middle = named.get(nton, str(nton) + '-')
return prefix + middle + 'tons' |
def mini(a,b):
""" Minimal value
>>> mini(3,4)
3
"""
if a < b:
return a
return b |
def snake_case(name):
"""Converts a CamelCase string to snake_case.
Parameters
----------
name : str
Returns
-------
str
"""
import re
sub_1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', sub_1).lower() |
def _parse_resource_path(resource,
to_fully_qualified,
resource_type=None,
subscription_id=None,
resource_group_name=None,
account_name=None):
"""Returns a properly formatted mongo role defin... |
def count_syllables(verse, syllable_separator="|"):
"""
Example input:
|Nel |mez|zo |del |cam|min |di |no|stra |vi|ta
Example output:
11
"""
syll = verse.split(syllable_separator)
syll = list(filter(lambda x: x.strip() != "", syll))
return len(syll) |
def get_insert_query(table_name):
"""Build a SQL query to insert a RDF triple into a PostgreSQL dataset"""
return f"INSERT INTO {table_name} (subject,predicate,object) VALUES (%s,%s,%s) ON CONFLICT (subject,predicate,object) DO NOTHING" |
def option_payoff(type, S, K):
"""calculate stock present value at t"""
try:
if type == 'C':
return max(S - K, 0.0) # values for European call option
elif type == 'P':
return max(K - S, 0.0) # values for European put option
except:
print('please conf... |
def parse_mac_address(mac_address):
"""Converts a MAC address string.
Returns a list containing the mac address bytes.
"""
return [int(v,16) for v in reversed(mac_address.split(':', 5))] |
def rule_regex(rule_number, rules):
"""Create rule_number regex from rules."""
if rules[rule_number] in 'ab':
return rules[rule_number]
sub_rules = rules[rule_number].split(' | ')
for index, sub_rule in enumerate(sub_rules):
sub_rule_regex = ''.join(rule_regex(int(number), rules)
... |
def _space_to(n, str):
"""
Generate a string of spaces to achieve width n given string str
If length of str >= n, return one space
"""
spaces = n - len(str)
if spaces > 0:
return " " * spaces
return " " |
def mock_literal(s):
"""
For use as the literal keyword argument to the RenderEngine constructor.
Arguments:
s: a byte string or unicode string.
"""
if isinstance(s, str):
# Strip off unicode super classes, if present.
u = str(s)
else:
u = str(s, encoding='ascii'... |
def list_type_prefix(list_type):
"""from a JATS list list-type attribute return a list style prefix"""
if list_type:
if list_type == "simple":
return "none"
if list_type == "order":
return "number"
return list_type
return "none" |
def list_to_dict(l):
"""Convert list to dict."""
return {k: v for k, v in (x.split("=") for x in l)} |
def underline(s):
"""Returns the string s, underlined."""
return '\x1F%s\x1F' % s |
def didGen64(vk64u, method="dad"):
"""
didGen accepts a url-file safe base64 key in the form of a string and returns a DID.
:param vk64u: base64 url-file safe verifier/public key from EdDSA (Ed25519) key
:param method: W3C did method string. Defaults to "dad".
:return: W3C DID string
"""
if... |
def is_eoc(lbl, iob, prev_lbl, prev_iob, otag='O'):
"""
is end of a chunk
supports: IOB, IOBE, BILOU schemes
- {E,L} --> last
- {S,U} --> unit
:param lbl: current label
:param iob: current iob
:param prev_lbl: previous label
:param prev_iob: previous iob
:param ... |
def isblank(indict):
"""
Passed an indict of values it checks if any of the values are set.
Returns ``True`` if every member of the indict is empty (evaluates as False).
I use it on a form processed with getform to tell if my CGI has been
activated without any values.
"""
return n... |
def locationGenerator(r,t,c,data='data', contextMgr=False):
"""
Given R, T, C, this funtion will generate a path to data in an imaris file
default data == 'data' the path will reference with array of data
if data == 'attrib' the bath will reference the channel location where attributes are stored
""... |
def _convert_to_list(data):
"""Accepts a list or a numpy.ndarray and returns a list."""
# The following check is performed as a string comparison
# so that ipy_table does not need to require (import) numpy.
if str(type(data)) == "<type 'numpy.ndarray'>":
return data.tolist()
return... |
def _xfs_prune_output(out, uuid):
"""
Parse prune output.
"""
data = {}
cnt = []
cutpoint = False
for line in [l.strip() for l in out.split("\n") if l]:
if line.startswith("-"):
if cutpoint:
break
else:
cutpoint = True
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.