content stringlengths 42 6.51k |
|---|
def bleep_out(string1, string2):
"""
>>> bleep_out('i freaking love carrots', 'freaking')
'i *** love carrots'
>>> bleep_out('oh dang oh dang oh dang', 'dang')
'oh *** oh *** oh ***'
"""
return string1.replace(string2, "***") |
def calc_ar1_dof_pearsonr(phi1, phi2=1.0, n=1):
"""Calculate degrees of freedom for correlation between
two autocorrelated time series with autocorrelation coefficients
phi1 and phi2
Parameter
----------
phi1, phi2 : float
Lag-one autocorrelations of the two timeseries
n : int
... |
def add_job_category(jobs):
"""
Determine which category job belong to among: build, run or merge and add 'category' param to dict of a job
Need 'processingtype', 'eventservice' and 'transformation' params to make a decision
:param jobs: list of dicts
:return: jobs: list of updated dicts
"""
... |
def interval_distance(label1, label2):
"""Krippendorff's interval distance metric
>>> from nltk.metrics import interval_distance
>>> interval_distance(1,10)
81
Krippendorff 1980, Content Analysis: An Introduction to its Methodology
"""
try:
return pow(label1 - label2, 2)
# ... |
def _flag_single_gifti(img_files):
"""Test if the paired input files are giftis."""
flag_single_gifti = [] # gifti in pairs
for img in img_files:
ext = ".".join(img.split(".")[-2:])
flag_single_gifti.append((ext == "func.gii"))
return all(flag_single_gifti) |
def unescape(str):
"""
Removes some of the html characters and replaces them.
:param str: Input string
:return: unescaped string
"""
str = str.replace('\n', "\n\t")
str = str.replace('\r', "\r")
str = str.replace('\t', "\t")
str = str.replace('\\\\', '\\')
return str |
def simple_select(vals, labels=None):
"""Returns an object for use in the dropdown filter. Selected is the initial value to highlight"""
if labels is None:
labels = vals
obj = [vals, labels]
return obj |
def copytree_ignore_backup(src, names):
""" Returns files to ignore when doing a backup of the rules. """
return [".cache"] |
def cnn_output_length(input_length, filter_size, border_mode, stride, dilation=1):
""" Compute the length of the output sequence after 1D convolution along
time. Note that this function is in line with the function used in
Convolution1D class from Keras.
Params:
input_length (int): Lengt... |
def get_jobid_from_location(location):
"""Extracts an HTTP error message from an VO response.
Parameters
----------
location : HTTP VO 303 response location header, mandatory
HTTP VO redirection location
Returns
-------
A jobid.
"""
pos = location.rfind('/')+1
jobid = l... |
def indent(str, dent):
"""Simple function to uniformly add whitespace to the front of lines."""
return '\n'.join(map(lambda x: ' ' * dent + x, str.split('\n'))) |
def mean_of_list(vals):
"""
avg value of a list
:param vals:
:return:
"""
return sum(vals)/float(len(vals)) if vals else 0 |
def getSurroundings(array, idx, window=2):
"""
Return words +-2 from idx
"""
surroundings = []
if idx > 1:
surroundings.append(array[idx - 2])
else:
surroundings.append('---')
if idx > 0:
surroundings.append(array[idx - 1])
else:
surroundings.append('---')
if idx < len(array) - 1:
surroundings.append... |
def make_nonterminal(label, children):
"""returns a tree node with root node label and children"""
return [label]+children |
def transform_event(ctx, param, value):
"""Callback to transform event into title case."""
if value is not None:
return value.title()
return value |
def _computePolyVal(poly, value):
"""
Evaluates a polynomial at a specific value.
:param poly: a list of polynomial coefficients, (first item = highest degree to last item = constant term).
:param value: number used to evaluate poly
:return: a number, the evaluation of poly with value
"""
#return numpy.polyval... |
def addToAverage(totalCount, totalValue, newValue):
""" simple sliding average calculation """
return ((1.0 * totalCount * totalValue) + newValue) / (totalCount + 1) |
def _strip_split(data, sep, maxsplit=-1):
"""
Just like str.split(), but remove ambient whitespaces from all items
"""
return [item.strip() for item in data.split(sep, maxsplit)] |
def _upper(string):
"""Custom upper string function.
Examples:
foo_bar -> FooBar
"""
return string.title().replace("_", "") |
def removeDuplicates(head):
"""Function to remove the duplicate value nodes from a linked list
Args:
head (SinglyLinkedListNode): Head of the linked list to check
Returns:
(SinglyLinkedListNode): The head of the linked list after removing duplicates
"""
if head is None:
ret... |
def example(x,t,a,b):
"""
an example right hand side function
"""
return x*a - t*b,1 |
def mean_reciprocal_rank(sort_data):
"""
Evaluate MRR
"""
sort_lable = [s_d[1] for s_d in sort_data]
assert 1 in sort_lable
return 1.0 / (1 + sort_lable.index(1)) |
def num_windows_of_length_M_on_buffers_of_length_N(M, N):
"""
For a window of length M rolling over a buffer of length N,
there are (N - M) + 1 legal windows.
Example:
If my array has N=4 rows, and I want windows of length M=2, there are
3 legal windows: data[0:2], data[1:3], and data[2:4].
... |
def pformat(obj):
"""Format an object using :func:`pprint.pformat`."""
from pprint import pformat
return pformat(obj) |
def reformat_alignment_title(alignment_title):
"""
Replaces white space with _ character in BLAST annotation
:param (str) alignment_title: annotation
:return (str): reformatted annotation
"""
return alignment_title.replace(" ", "_") |
def equals(x, y, delta=0.0000001):
"""Compares two floating point numbers."""
return abs(x - y) < delta |
def prod(*x):
"""
Returns the product of elements, just like built-in function `sum`.
Example:
----------
>>> prod([5, 2, 1, 4, 2])
80
"""
if len(x) == 1 and isinstance(x[0], list): x = x[0]
p = 1
for i in x:
if hasattr(i, "__mul__"):
p *= i
return p |
def create_edges(dc):
"""
Create edges (lines) connecting each pair of stars
Arguments
---------
dc : dictionary of constellations
Returns
-------
edges : list of all edges
"""
edges = []
for k,v in dc.items():
for i in v:
edges.append(i)
... |
def DAY_OF_WEEK(expression):
"""
Returns the day of the week for a date as a number between 1 (Sunday) and 7 (Saturday).
See https://docs.mongodb.com/manual/reference/operator/aggregation/dayOfWeek/
for more details
:param expression: expression or variable of a Date, a Timestamp, or an ObjectID
... |
def get_intensity_matrix(pixels, option):
"""Function to set the measure of brightness to be used depending upon the
option, choose between three measures namely luminance,
lightness and average pixel values
"""
intensity_matrix = []
for row in pixels:
intensity_matrix_row = []
f... |
def filter_context_processor(request):
""" Fills up variables filter_params, filter_form_hidden.
"""
if hasattr(request, 'filter'):
return vars(request.filter)
else:
return {} |
def int_left_most_bit(v):
""" Could be replaced by better raw implementation
"""
b = 0
while v != 0:
v //= 2
b += 1
return b |
def rgb2html(r, g, b): # {{{1
"""
Converts an RGB color to a HTML color string.
All the arguments are clamped to the appropriate range for their type.
Arguments:
r: Red value, integer (0--255) or float (0--1.0).
g: Green value, idem.
b: Blue value, idem.
Returns:
h... |
def type_n_queries(value):
"""Custom type used for --n_queries argument.
Parameters
----------
value: str
The argument value for --n_queries
Returns
-------
type_n_queries:
A string containing 'min' or an integer.
"""
if value == 'min':
return value
else... |
def convert_floats_to_ints(in_floats, multiplier):
"""Convert floating points to integers using a multiplier.
:param in_floats: the input floats
:param multiplier: the multiplier to be used for conversion. Corresponds to the precisison.
:return the array of integers encoded"""
return [int(round(x *... |
def RGBtoHSV(r, g, b):
"""Convert RGB values to HSV
Algorithm is taken from https://www.cs.rit.edu/~ncs/color/t_convert.html
"""
# If we were given black, return black
if r == 0 and g == 0 and b == 0:
return 0,0,0
# We need RGB from 0-1, not 0-255
r /= 255
g /= 255
b /= 255... |
def checkinstance(csp):
"""Check if a given instance is valid."""
if type(csp) != dict:
print("Instance has to be a dictionary and it has type ",
type(csp))
return 1
try:
for item in csp:
if len(item) != len(csp[item].shape):
stt = "(" + "2,"... |
def max2(x, y):
"""
>>> max2(1, 2)
2
>>> max2(1, -2)
1
>>> max2(10, 10.25)
10.25
>>> max2(10, 9.9)
10.0
>>> max2(0.1, 0.25)
0.25
>>> max2(1, 'a')
Traceback (most recent call last):
...
UnpromotableTypeError: Cannot promote types int and string
"""
... |
def rotate(given_array):
"""
n = # rows = # columns in the given 2d array.
Time: O(rows * cols)
Space: O(2*1) = O(1)
"""
n = len(given_array)
rotated = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
rotated[j][n - 1 - i] = given_ar... |
def cluster_url_to_name(cluster_url, clusters):
"""
Given a cluster URL and the configured clusters, returns the
corresponding cluster name, or throws if none is found
"""
matched_clusters = [c for c in clusters if c['url'].lower().rstrip('/') == cluster_url.lower()]
if len(matched_clusters) == ... |
def get_zoom_user_context(event):
"""
Parses the operation_detail field of Zoom.Operation events related to Users
to provide usable fields for use in detections
"""
operation_context = {}
raw_string = event.get("operation_detail", "")
category_type = event.get("category_type")
action = e... |
def get_metadata_filename(preprocess_id, version=None):
"""Return a filename used for a preprocess download"""
assert preprocess_id, "preprocess_id cannot be None"
assert str(preprocess_id).isdigit(), "preprocess_id must be numeric"
if not version:
version = '1.0'
version = str(version).re... |
def _read_value(input_string: str) -> str:
"""Convert various numeric forms to regular decimal format if possible."""
ret_val = ""
if not input_string:
ret_val = ""
if "0x" in input_string:
ret_val = int(input_string, 16)
elif "." in input_string:
try:
ret_val = f... |
def yearmonthplusoffset(year, month, offset):
""" calculate new year/month from year/month and offset """
month += offset
# handle offset and under/overflows - quick and dirty, yes!
while month < 1:
month += 12
year -= 1
while month > 12:
month -= 12
year += 1
ret... |
def build_passport(data):
"""
Takes in a string of key:value pairs separated by spaces
and returns a dictionary
"""
result = {}
for part in data.split(" "):
if ":" in part:
parts = part.split(":")
result[parts[0]] = parts[1]
return result |
def format_func(value, tick_number):
"""
Function to convert tick labels from seconds elapsed to
day of date.
"""
return int(value / (24*60*60)) |
def code(text):
"""Formats text as code in Markdown format.
Args:
text(string): Text to format
Return:
string: Formatted text.
"""
return '`{0:s}`'.format(text.strip()) |
def _endpoint_from_image_ref(image_href):
"""Return the image_ref and guessed endpoint from an image url.
:param image_href: href of an image
:returns: a tuple of the form (image_id, endpoint_url)
"""
parts = image_href.split('/')
image_id = parts[-1]
# the endpoint is everything in the url... |
def _global_unique_search(lines):
"""Remove repeated lines so that the entire file is unique.
Returns the unique lines.
lines: the lines of the file to deduplicate
"""
unique_lines = []
_idx = {}
for line in lines:
try:
_idx[line]
except KeyError:
_id... |
def compute_iou(boxA, boxB):
"""
Compute intersection over union
Args:
boxA: first bounding box
boxB: second bounding box
Returns: intersection over union
"""
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], b... |
def pythonic(num_steps: int) -> int:
"""Same as `recursive()` but using built in cache.
We can safely use a cache of size 3 to save some space.
Args:
num_steps:
Returns:
The number of possible ways to climb the stairs
"""
if num_steps <= 2:
return num_steps
if num_... |
def order_flat_list(l):
"""
['1','2','3','2','4','3']--->['1','2','4','3']
:param l:
:return:
"""
if type(l) != list:
return ''
ret = ''
tmp = []
tmp += l
length = len(tmp)
for i in range(length):
value = tmp.pop(0)
if value not in tmp:
ret... |
def read_limitsandfixed(fname):
"""
Read a text file e.g.
PARAM1 0 1 # interpreted as fixed param
PARAM2 0.54444 # interpreted as limits
"""
limits, fixed = {}, {}
if fname is not None:
with open(fname) as f:
for l in f:
if not l.startswi... |
def extract(d, keys):
"""
Extract a key from a dict.
:param d: The dict.
:param keys: A list of keys, in order of priority.
:return: The most important key with an value found.
"""
if not d:
return
for key in keys:
tmp = d.get(key)
if tmp:
return tmp |
def _is_ectopic(qidx):
"""
Checks if a QRS index is an ectopic beat in a trigeminy, according to its
index.
Parameters
----------
qidx:
Index of the QRS complex within the QRS observations of this pattern.
Returns
-------
out:
True if the index corresponds to an ect... |
def try_pop(df, key, default=None):
"""
Like pandas.DataFrame.pop but accepts a default return like dict.pop does.
"""
try:
return df.pop(key)
except KeyError:
return default |
def _normalise_format_name(name):
"""
>>> _normalise_format_name('GEOTIFF')
'GeoTIFF'
>>> _normalise_format_name('MD')
'MD'
"""
if not name:
return name
if name.lower() == 'geotiff':
return 'GeoTIFF'
return name |
def format_value(value, context=None):
"""
Resole the Variable/FilterExpression value else nothing happens
"""
try:
return value.resolve(context)
except AttributeError:
return value |
def is_a_power_of_2(x: int) -> bool:
"""Check if an integer is a power of two.
Args:
x (int): Number to check
Returns:
bool: True if the number is a power of two
"""
# https://stackoverflow.com/questions/57025836/how-to-check-if-a-given-number-is-a-power-of-two
return x > 0 an... |
def crear_matriz(filas, columnas):
"""
Crea una matriz Mmxn hecha de ceros. m = filas, n = columas.
"""
matriz = []
for i in range(filas):
matriz.append([0] * columnas)
return matriz |
def getCameraIndex(gltf, idname):
"""
Return the camera index in the gltf array.
"""
if gltf.get('cameras') is None:
return -1
index = 0
for camera in gltf['cameras']:
key = 'id' if camera.get('id') != None else 'name'
if camera.get(key) == idname:
return in... |
def calculate_final_scores(n_gram_scores, consecutive_scores, w1, w2):
""" Returns a list with the final scores for a given list of n_gram and consecutive scores """
return [w1*score1 + w2*score2 for (score1, score2) in zip(n_gram_scores, consecutive_scores)] |
def sqrt(x):
"""returns the square root of a number: Docstring for sqrt.
:x: number
:returns: square root
"""
if x >= 0:
return x ** 0.5
else :
return 'Invalid Negative number' |
def parse_pred(item, min_width=0.5, score_thresh=0.5):
""" Use px to represent bbx """
impath = item["path"]
preds = item["layout"]
h = item["h"]
w = item["w"]
bbxes = []
for l, t, r, b, c, s in preds:
if (r - l) < min_width or s < score_thresh:
continue
l = in... |
def dups(lst):
"""
>>> dups([1, 2, 1, 3, 2, 5])
[1, 2]
"""
return list(set(filter(lambda x: lst.count(x) != 1, lst))) |
def filtermetadata(text):
"""Extract just the revision data from source text.
Returns ``text`` unless it has a metadata header, in which case we return
a new buffer without hte metadata.
"""
if not text.startswith(b'\x01\n'):
return text
offset = text.index(b'\x01\n', 2)
return tex... |
def list_filter_none(l):
"""
filter none values from a list
"""
return [v for v in l if v is not None] |
def form_concat_RE(re1, re2):
"""Helper for del_one_gnfa_state
---
Given two non-eps REs, form their concatenation.
"""
if re1=="":
return re2
elif re2=="":
return re1
else:
return ('.', (re1, re2)) |
def str_remove(x, remove_lst):
"""
Remove specified strings from a value.
"""
remove_lst = [remove_lst] if not isinstance(remove_lst, list) else remove_lst
for item in remove_lst:
x = str(x).replace(item, '')
return x |
def safe2f(x):
"""converts to float if possible, otherwise is a string"""
try:
return float(x)
except BaseException:
return x |
def calc_chunksize(n_workers, len_iterable, factor=4):
"""Calculate chunksize argument for Pool-methods.
Resembles source-code within `multiprocessing.pool.Pool._map_async`.
"""
chunksize, extra = divmod(len_iterable, n_workers * factor)
if extra:
chunksize += 1
return chunksize |
def deep_merge(a, b):
"""
Merges b into a, recursively.
This is a special recursive dictionary merge, made specifically for docker compose files.
If a and b are both dictionaries, their keys are recursively merged. Keys in b write over keys in a.
If a and b are both lists, the elements of b are adde... |
def generateListLocation(username, list_name):
""" generates file placement in S3 based on standardized storage
"""
return username + '/' + list_name + '.txt' |
def lr_scheduler(epoch,lr):
"""
Learning rate scheduler decays the learning rate by factor of 0.1 every 10 epochs after 20 epochs
"""
decay_rate = 0.1
if epoch==20:
return lr*decay_rate
elif epoch%10==0 and epoch >20:
return lr*decay_rate
return lr |
def get_distance(source, target):
"""Get Manhattan distance from source to target."""
return sum(abs(num1 - num2) for num1, num2 in zip(source, target)) |
def remove_leading_zeros(numeric_string):
"""
>>> remove_leading_zeros("0033")
'33'
"""
ret_val = ""
for n in numeric_string:
if n != "0":
ret_val += n
return ret_val |
def get_wcets(utils, periods):
""" Returns WCET """
return [ui * ti for ui, ti in zip(utils, periods)]
# return [math.ceil(ui * ti) for ui, ti in zip(utils, periods)] |
def programExists(name):
"""Check whether `name` is on PATH and marked as executable."""
# from whichcraft import which
from shutil import which
return which(name) is not None |
def parse_phrase_strings(phrase_strings):
"""Parse a phrase string passed from the JS application and return the
corresponding sequence texts.
"""
sequence_texts = list()
for phrase_string in phrase_strings:
# Split on underscore to remove the unnecessary components, then
# restor... |
def rename_list_to_dict(rlist):
"""
Helper for main to parse args for rename operator. The args are
assumed to be a pair of strings separated by a ":". These are
parsed into a dict that is returned with the old document key to
be replaced as the (returned) dict key and the value of the return
... |
def is_positive_symbol(s):
""" Function to find if s is a positive symbol by checking if its not a list and
length of the string s is equal to 1 """
return (not isinstance(s, list)) and len(s) == 1 |
def rep2kmer(rep, k=6):
""" Encode a repertoire using kmers
Args:
rep: a list of BCR CDR3s
k: the size of the kmer
Returns:
list: a list of kmers
"""
germ = set()
out = []
info = {}
for s in rep:
if type(s) == float:
... |
def repeat(s, exclaim):
"""
Return the string 's' repeated 3 times.
If exclaim is true, add exclamation mark.
"""
result = s + s + s
if exclaim:
result = result + '!!!'
return result |
def check_https(https_result: dict) -> bool:
"""
It will check if page output from HTTPS has been OK.
:param https_result: Result from webserver_stats module
:return: Boolean value.
"""
if https_result and https_result.get('status') == 200:
return True
return False |
def bisect_jump_time(tween, value, b, c, d):
"""
**** Not working yet
return t for given value using bisect
does not work for whacky curves
"""
max_iter = 20
resolution = 0.01
iter = 1
lower = 0
upper = d
while iter < max_iter:
t = (upper - lower) / 2
if twee... |
def union(u, v):
"""Return the union of _u_ and _v_.
>>> union((1,2,3), (2,3,4))
[1, 2, 3, 4]
"""
w = list(u)
if w is u:
import copy
w = copy.copy(w)
for e in v:
if e not in w:
w.append(e)
return w |
def convert_to_nullable(input_val, cast_function):
"""For non-null input_val, apply cast_function and return result if successful; for null input_val, return None.
Args:
input_val (Any): The value to attempt to convert to either a None or the type specified by cast_function.
The recognized ... |
def c_path(path):
"""
Returns a string corresponding to the ``path`` to a struct element in C.
The ``path`` is the sequence of field names/array indices returned from
:py:func:`~reikna.cluda.dtypes.flatten_dtype`.
"""
return "".join(
(("." + elem) if isinstance(elem, str) else ("[" + st... |
def random_alphanumeric(length: int) -> str:
"""
Returns random str with the combination of alphabetic and numeric
:param length: char length
:return: [0-9a-zA-Z]
"""
import random
import string
letters = string.ascii_letters + string.digits
random_str = ''.join(random.c... |
def get_ligand_filetype(ligand_filename):
"""Returns the filetype of ligand."""
if ".mol2" in ligand_filename:
return ".mol2"
elif ".sdf" in ligand_filename:
return "sdf"
elif ".pdbqt" in ligand_filename:
return ".pdbqt"
elif ".pdb" in ligand_filename:
return ".pdb"
else:
raise ValueErro... |
def average_acceleration(v1 : float, v0 : float, t1 : float, t0 : float) -> float:
"""
[FUNC] average_acceleration:
Returns the average_acceleration
"""
return ((v1-v0)/(t1-t0)); |
def object_adder(a, b):
"""Adds two object together"""
if type(a) is not int or type(b) is not int:
raise TypeError("Object is not of type int")
return a + b |
def showcase_user(username: str):
""":class:`str`: Make a link that lets you showcase user.
Parameters
------------
username: :class:`str`
The user's username.
.. versionadded: 1.3.5
"""
return f"https://twitter.com/{username}" |
def get_in(obj, keys):
"""
>>> get_in({'a': {'b': 1}}, 'a.b')
1
"""
if isinstance(keys, str):
keys = keys.split('.')
for key in keys:
if not obj or key not in obj:
return None
obj = obj[key]
return obj |
def make_filter_fn(filter_dict):
"""Returns a lambda which, when given a Todoist task, will check
whether it has the same values for keys in `filter_dict`, returning
a bool
"""
if not filter_dict:
return None
def fn(task):
for k, v in filter_dict.items():
if task[k] ... |
def mark_line_for_separation(line):
"""
Tag stage directions, acts, and scenes.
"""
if line[0] == " ":
if line[-1] != ".":
return "Stage_dir" + line + "."
else:
return "Stage_dir" + line
elif "ACT " in line or "SCENE " in line:
return line + "."
re... |
def parse_approx_order(approx_order):
"""
Parse the uniform approximation order value (str or int).
"""
ao_msg = 'unsupported approximation order! (%s)'
force_bubble = False
discontinuous = False
try:
ao = int(approx_order)
except ValueError:
mode = approx_order[-1].lowe... |
def parse_vertex(text):
"""Parse text chunk specifying single vertex.
Possible formats:
vertex index
vertex index / texture index
vertex index / texture index / normal index
vertex index / / normal index
"""
v = 0
t = 0
n = 0
chunks = text.split("/")
v ... |
def normalize_ranges(ranges):
"""
This function compare several ranges and offset the relative start
to 0. If the ranges has a gap, for example, range1 finish to 50 and
range2 start at 65. The gap is removed.
"""
offset = sorted(ranges)[0][0]
ranges = [[n - offset for n in r] for r in ranges... |
def istuple(val):
"""
check if the entry is a tuple or is a string of tuple
Parameters
----------
val
an entry of any type
Returns
-------
bool
True if the input is either a tuple or a string of tuple, False otherwise
Notes
-----
please note that '(1)' is a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.