content stringlengths 42 6.51k |
|---|
def hamming_distance(pattern1, pattern2):
"""Return the hamming distance between 2 patterns."""
if len(pattern1) == len(pattern2):
return sum([
pattern1[index] != pattern2[index]
for index in range(len(pattern1))
])
raise Exception('Length of both reads do not match') |
def find_max_min(list_numbers):
"""
takes a list_numbers and returns min and max values
as list i.e [min, max]
"""
if not isinstance(list_numbers, list):
raise TypeError("expected list_numbers to be a list")
list_length = len(list_numbers)
# remove duplicates values and sor... |
def add_alpha(colors):
"""
Add the default alpha value 1 to every color in a list or dictionary of colors
Parameters
----------
colors: list or dictionary
Returns
-------
list or dictionary of colors with alpha channel value
"""
if colors is type(dict):
alpha = []
... |
def rm_twin_pairs(all_pairs, twin_pairs):
"""Given all possible subject pairs, remove twins leaving only unrelated pairs.
Parameters
----------
all_pairs : list of tuple of (int, int)
All possible subject ID pairs.
twin_pairs : list of tuple of (int, int)
Twin ID pairs.
Returns... |
def find_reverse_number(number: int = 36) -> int:
"""
Reverses the given number. Does not work with number that end in zero.
>>> find_reverse_number(36)
63
>>> find_reverse_number(409)
904
"""
reverse = 0
while number > 0:
temp = number % 10
reverse = reverse * 10 + ... |
def is_pair_sum(pl: list, target: int) -> bool:
"""Returns True iff target can be made by summing 2 different integers in pl."""
for i in range(len(pl)):
for j in range(len(pl)):
if i != j:
if pl[i] + pl[j] == target:
return True
return False |
def irc_prefix(var):
"""
Prefix a string with the irc_
:param var: Variable to prefix
:return: Prefixed variable
"""
if isinstance(var, str):
return 'irc_%s' % var.lower() |
def easyHash(s):
"""
MDSD used the following hash algorithm to cal a first part of partition key
"""
strHash = 0
multiplier = 37
for c in s:
strHash = strHash * multiplier + ord(c)
#Only keep the last 64bit, since the mod base is 100
strHash = strHash % (1<<64)
retur... |
def represents_int(s, acceptRoundedFloats=False):
"""
This function return True if the given param (string or float) represents a int
:Example:
>>> represents_int(1)
True
>>> represents_int("1")
True
>>> represents_int("a")
False
>>> represent... |
def get_age_filter(age_value):
"""
When age_value = 6 it means first range is chosen 0-6 months.
For that range we want to include 0 and 6 in results.
"""
if age_value == '6':
return {'age_tranche__in': ['0', '6']}
else:
return {'age_tranche': age_value} |
def domains_match(base, probe):
"""
domains_match(base, probe) -> bool
Return whether probe should "match" base if both are interpreted
as domain names. Implements RFC6265, Section 5.1.3.
"""
if probe == base:
# Equal domains always match.
return True
prefix = probe[:-len(ba... |
def color_array_by_value(value, palette, denom, mask_zeros):
"""
Figure out the appropriate RGB or RGBA color for the given numerical
value based on the palette, denom, and whether zeros should be masked.
"""
if value == -1: # sentinel value
return -1
if value == 0 and mask_zeros: # T... |
def colors(i):
"""Return a pyplot default color
"""
return f'C{i}' |
def has_module(name):
"""
Check to see if a module is installed by name without
actually importing the module.
Parameters
------------
name : str
The name of the module to check
Returns
------------
installed : bool
True if module is installed
"""
# this should ... |
def get_event_time(event):
"""
Get the merger time for known GW events.
See https://www.gw-openscience.org/catalog/GWTC-1-confident/html/
Last update https://arxiv.org/abs/1811.12907:
GW150914
GW151012
GW151226
GW170104
GW170608
GW170729
GW170809
... |
def MapNestedList(data, func):
"""Map a nested dictionary with specified func
@example:
>>> a = [ 1 , [ 2 , 3 ], 4 ]
>>> MapNestedList(a, str)
['1', ['2', '3'], '4']
"""
if not isinstance(data, list):
return func(data)
return [MapNestedList(e, func) for e in data] |
def error(row, message, record=None, **kwargs):
""" Failed import of the record ``record`` at line ``row``, with the error
message ``message``
:param str message:
:param dict record:
"""
return (
-1, dict(record or {}, **kwargs),
"Line %d : %s" % (row, message),
'') |
def GL2PL(gl):
""" Converts Genotype likelyhoods to phred scaled (PL) genotype likelyhoods. """
return -int(gl * 10) |
def get_pieces(struct, splits):
"""Breaks up the structure at fixed positions, returns the pieces.
struct: structure string in sprinzl format
splits: list or tuple of positions to split on
This is a helper function for the sprinzl_to_vienna function.
struct = '...===...===.'
splits = ... |
def get_description(contents):
"""
Gets the description of an ZTAP note.
Type will be prefixed to the first line of the comment/log.
"""
note = contents.get("contents")
if not note:
return ""
first_line = note.split("\n")[0]
typ = contents.get("type")
if typ == "comment":
... |
def remove(s, i):
"""
Returns the string s with the character at index i removed.
Examples:
>>> s = '12304'
>>> remove(s, 3)
'1234'
>>> s = '0123'
>>> remove(s, 0)
'123'
>>> s = '0123'
>>> remove(s, 3)
'012'
>>> s = '0123'
>>> remove(s, -1)
'0123'
>>... |
def is_too_similar_for_axes(word1, word2):
""" Checks if the words contain each other """
return word1 in word2 or word2 in word1 |
def is_same_target(bam_file_name, label_data_df):
"""
:param bam_file_name:
:param label_data_df:
:return:
"""
return bam_file_name.rsplit('/',1)[1].split('_')[0] == label_data_df.rsplit('/',1)[1].split('_')[0] |
def flatten(l, r=1):
"""Flatten a nested list/tuple r times."""
return l if r == 0 else flatten([e for s in l for e in s], r-1) |
def sort_bills(found_bills) -> list:
"""Sort found Bills by their Bill Ids."""
return sorted(found_bills.items(), key=lambda x: int(x[0].split(" ")[1])) |
def split(line):
"""Input string as described in module docstring, return 2 sets of ints."""
set1 = {int(x) for x in (line.split(';')[0]).split(',')}
set2 = {int(x) for x in (line.split(';')[1]).split(',')}
return set1, set2 |
def format_html(html):
"""
Helper function that formats HTML in order for easier comparison
:param html: raw HTML text to be formatted
:return: Cleaned HTML with no newlines or spaces
"""
return html.replace('\n', '').replace(' ', '') |
def text2array_unicode(string: str) -> list:
"""
Return an array of char ascii codes for each character in string
"""
array_unicode = []
for letter in string:
array_unicode.append(ord(letter))
return array_unicode |
def _flat(commands):
"""Flatten commands while preserving order"""
commands = [cmd for cmd in commands if cmd is not None]
flattened = []
for command in commands:
if isinstance(command, str):
flattened.append(command)
elif isinstance(command, list):
flattened.exte... |
def iou(bbox1, bbox2):
"""
Calculates the intersection-over-union of two bounding boxes.
Args:
bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2.
bbox2 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2.
Returns:
int: intersection-over-onion... |
def mapDict(dictionary, func):
"""
Applies a function to the values of a dictionary.
:param dictionary: The dictionary for which a function should be applied on the values of its tuples. \t
:type dictionary: Dict<mixed, mixed> \n
:param func: The function to be applied on the value of a tuple. \t
... |
def get_order(perm, index):
"""Returns the exact order (length) of the cycle that contains a given index.
"""
order = 1
curr = index
while index != perm[curr]:
order += 1
curr = perm[curr]
return order |
def handle_2_columns(datalist, return_list = False):
"""This function has the intent of changing:
('A8', '2') => ('A8', '', '2')
('A8', '', '2') => ('A8', '', '2')
[('E2', '5')] => [('E2', '', '5')]
[('G1', '', '5')] => [('G1', '', '5')]
with the purpose of handling 2 column csv part file inputs... |
def wrap_plan(*lines: str) -> str:
""" Wrap in pgtap plan functions, assumes each line is a test """
# You can't run a pgTap query without a plan unless it's a
# runtests() call to db test functions
return "\n".join(
[
"BEGIN;",
"SELECT plan(%s);" % len(lines),
... |
def getattrs(value, attrs):
"""Helper function that extracts a list of attributes from
`value` object in a `dict`/mapping of (attr, value[attr]).
Args:
value (object):
Any Python object upon which `getattr` can act.
attrs (iterable):
Any iterable containing attribut... |
def get_one_level_lower_path(relative_path):
"""
@param relative_path:
@type relative_path:
@return:
@rtype:
"""
relative_path_elements = relative_path.split('/')
del relative_path_elements[len(relative_path_elements) - 1]
return '/'.join(relative_path_elements) |
def is_valid_hour(hour):
"""
Check if hour value is valid
:param hour: int|string
:return: boolean
"""
return (hour == '*') or (23 >= hour >= 0) |
def generate_payload(size:int=0):
"""
Generates a payload of random bytes of the given amount
:param size: number of generated bytes
:return: the generated payload
"""
payload = bytes(size)
return payload |
def merge_fields(*fields):
"""Used in audiorename/args.py"""
arguments = locals()
out = {}
for fields in arguments['fields']:
out.update(fields)
return out |
def histogram(ratings, min_rating=None, max_rating=None):
"""
Returns the counts of each type of rating that a rater made
"""
if min_rating is None:
min_rating = min(ratings)
if max_rating is None:
max_rating = max(ratings)
num_ratings = int(max_rating - min_rating + 1)
hist_... |
def padding_row(row, mcols):
"""
:param rows: A list of row data :: [[]]
>>> padding_row(['a', 1], 3)
['a', 1, '']
>>> padding_row([], 2)
['', '']
"""
return row + [''] * (mcols - len(row)) |
def process_keywords(keywords):
"""Add plan records and other references as references
"""
keys = keywords.split(",")
return keys |
def _sane_version_list(version):
"""Ensure the major and minor are int.
Parameters
----------
version : list
Version components
Returns
-------
version : list
List of components where first two components has been sanitised
"""
v0 = str(version[0])
if v0:
... |
def geocode_with_exception(loc, geocode):
"""
Find location. If no location can be found, return None.
"""
try:
return geocode(loc)
except Exception:
return None |
def isValidRAIDLevel(raids):
""" Evaluate the RAID level to int type, and check if
exists in valid RAID Levels. Return True if OK, else return
an error message.
"""
validRAIDLevels = [0,1,5,6,10,50,60]
if len(raids) <= 0:
return True
else:
if int(raids[0]['level']) in validRA... |
def _mzmlListAttribToTuple(oldList):
"""Turns the param entries of elements in a list elements into tuples, used
in :func:`MzmlScan._fromJSON()` and :func:`MzmlPrecursor._fromJSON()`.
.. note:: only intended for a list of elements that contain params. For
example the mzML element ``selectedIonList`... |
def pivotize(matrix):
""" Creates the pivoting matrix """
size = len(matrix)
# determine identity matrix P (n x n)
P = [[float(i == j) for i in range(size)] for j in range(size)]
r = 0
for j in range(size):
# find row with max element
row = max(range(j, size), key=lambda i: abs(m... |
def get_style(param_or_header):
"""Checks parameter/header style for simpler scenarios"""
if "style" in param_or_header:
return param_or_header["style"]
# if "in" not defined then it's a Header
location = param_or_header.getkey("in", "header")
# determine default
return "simple" if loc... |
def create_tag_label(prefix,obj_name):
""" Given an object and prefix, create a tag label that combines the prefix
and Rhino object name. Return label as a string"""
lable = prefix + "_"+ obj_name
return lable |
def avg(nums):
"""Returns the average (arithmetic mean) of a list of numbers"""
return float(sum(nums)) / len(nums) |
def has_outputfile(records: dict) -> list:
""" Convenience function for finding output files in a dictionary of records"""
keys, has_outputs = [], []
# check to see which records have outputfiles
for key, record in records.items():
keys.append(key)
has_outputs.append(record['output'] is ... |
def is_int(string):
"""
Return true if string is an integer.
"""
try:
int(string)
return True
except ValueError:
return False |
def index_tw_refs_by_verse(tw_refs):
""" Returns a dictionary of books -> chapters -> verses, where each
verse is a list of rows for that verse. """
tw_refs_by_verse = {}
for tw_ref in tw_refs:
book = tw_ref["Book"]
chapter = tw_ref["Chapter"]
verse = tw_ref["Verse"]
... |
def expect_list(obj):
""" Returns the given object within a list if it is not already """
return obj if isinstance(obj, list) else [obj] |
def normalize_rtsp(rtsp: str) -> str:
"""normalize_rtsp.
RTSP://xxx => rtsp://
Args:
rtsp (str): rtsp
Returns:
str: normalized_rtsp
"""
normalized_rtsp = rtsp
if isinstance(rtsp, str) and rtsp.lower().find("rtsp") == 0:
normalized_rtsp = "rtsp" + rtsp[4:]
retur... |
def search_key_for_action(action):
""" Name and description are search keys. """
elements = []
elements.append(action['name'])
elements.append(action['description'])
return u' '.join(elements) |
def to_pascal_case(string: str, separator: str = ' ') -> str:
"""Converts `some standard name` to SomeStandardName,
splitting the input string by a given separator"""
return "".join(word.capitalize() for word in string.split(separator)) |
def scale_cv_figsize(im_shape, scale, max_figsize):
"""
Scales image size for clearer display in OpenCV.
Parameters
----------
im_shape : 2-tuple of ints
(number of rows, number of columns) in image to be scaled
scale : float
Positive factor to scale image size
max_figsi... |
def iterable(y):
"""
Check whether or not an object can be iterated over.
Parameters
----------
y : object
Input object.
Returns
-------
b : bool
Return ``True`` if the object has an iterator method or is a
sequence and ``False`` otherwise.
Examples
--------... |
def get_ones_complement_bit_string(value):
"""Returns the ones complement bit string of a value."""
if value == 0:
return ''
negative = False
if value < 0:
negative = True
value *= -1
bit_string = bin(value)[2:] # Chop off the '0b' bin returns
if negative:
bit_li... |
def get_overlap(x0, xd, y0, yd):
"""Return the min edge and width of overlap.
Parameters
----------
x0, y0 : float
The min values of the ranges
xd, yd : float
The widths of the ranges
Returns
-------
lo : float
The min value of the overlap region
width : flo... |
def permutations(lst):
"""
Finds all permutations of a set
"""
# If lst is empty then there are no permutations
if len(lst) == 0:
return []
# If there is only one element in lst then, only one permuatation is possible
if len(lst) == 1:
return [lst]
# Find th... |
def normalize_azimuth(azimuth, zero_center=False):
"""Normalize an azimuth in degrees so it falls between 0 and 360.
If ``zero_center=True``, azimuth will be normalized
between -180 and 180.
"""
if (azimuth > 360 or azimuth < 0):
azimuth %= 360
if zero_center:
if azimuth > 1... |
def get_activity_status_text(activity_status):
"""
Given the activity status boolean, return a human
readable text version
"""
if activity_status is True:
activity_status_text = "Success!"
else:
activity_status_text = "FAILED."
return activity_status_text |
def oruser(name):
"""Return name if is not empty or user name
"""
if name:
return name
import getpass
return getpass.getuser() |
def _has_surrogates(s):
"""Return True if s contains surrogate-escaped binary data."""
# This check is based on the fact that unless there are surrogates, utf8
# (Python's default encoding) can encode any string. This is the fastest
# way to check for surrogates, see issue 11454 for timings.
try:
... |
def _ncells_after_subdiv(ms_inf, divisor):
"""Calculates total number of vtu cells in partition after subdivision
:param ms_inf: Mesh/solninformation. ('ele_type', [npts, nele, ndims])
:type ms_inf: tuple: (str, list)
:rtype: integer
"""
# Catch all for cases where cell subdivision is not perf... |
def bl2ij(bl):
"""
Convert baseline number to antenna numbers.
Parameters
----------
bl : int
baseline number
Returns
-------
int
first antenna number
int
second antenna number
"""
bl = int(bl)
if bl > 65536:
bl -= 65536
mant = 2... |
def As_Dollars_Pad(Number):
"""Format Dollars amounts to strings & Pad Right 10 Spaces"""
Number_Display = f"${Number:,.2f}"
Number_Display = f"{Number_Display:>10}"
return Number_Display |
def rem_not_expanded_dims(idx_advanced, expand_true, tensor_index_ndim, rem_ndim, not_expanded_dim):
"""Adds remaining dimensions not indexed to not_expanded_dim"""
if idx_advanced != -1:
if expand_true:
# tensor indices generate only one dimension with size 1
tensor_dims = (Fals... |
def modelseeddb_parse_equation(equation, delimiter=' '):
"""
This function is a copy of ModelSEEDDatabase Biochem_Helper.py:parseEquation
https://github.com/ModelSEED/ModelSEEDDatabase/Scripts/Biochem_Helper.py
"""
# Build search strings using specified delimiter.
bidirectional = delimiter + '<=... |
def concatenate_rounds(rounds_1, rounds_2):
"""
:param rounds_1: list - first rounds played.
:param rounds_2: list - second set of rounds played.
:return: list - all rounds played.
"""
rounds = rounds_1[:]
for go_round in rounds_2:
rounds.append(go_round)
return rounds |
def unique (inn):
""" Removes duplicate entries from an array of strings
Returns an array of strings, also removes null and blank strings
as well as leading or trailing blanks
inn = list of strings with possible redundancies
"""
# Make local working copy and blank redundant entries
lin... |
def is_number(s):
"""Checks if a string is a number or not."""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass |
def juxtapose(left, right):
"""
Takes two texts/strings with several lines, and creates a new string, where both original texts are displayed
side by side. This is, however, just a helper function for the purpose of illustration, and not necessarily
a generally useable function.
"""
if type(lef... |
def get_class(x):
"""
x: index
"""
# Example
distribution = [0, 2000, 4000, 6000, 8000, 10000]
x_class = 0
for i in range(len(distribution)):
if x > distribution[i]:
x_class += 1
return x_class |
def list_of_primes(limit):
"""
Get a list of primes up to limit
:param limit: maximum number to get primes
:return: the list of primes up to limit
"""
primes = []
for i in range(2, limit + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
i... |
def parse_image_size(image_size):
"""Parse "100x100" like string into a tuple."""
return tuple(map(int, image_size.split("x"))) |
def _get_split_idx(N, blocksize, pad=0):
"""
Returns a list of indexes dividing an array into blocks of size blocksize
with optional padding. Padding takes into account that the resultant block
must fit within the original array.
Parameters
----------
N : Nonnegative integer
Total ... |
def to_camel_case(snake_str):
"""Format string to camel case."""
title_str = snake_str.title().replace("_", "")
return title_str[0].lower() + title_str[1:] |
def path_join(*args):
"""Should work for windows and linux
:rtype: str
"""
return "/".join([str(x) for x in args]) |
def custom_token_implementation(user_id):
""" Custom JWT implementation """
return 'CUSTOM TOKEN FOR [{}]'.format(user_id) |
def mortal_fib(n, m):
"""rabbbits[0] = newborn, rabbits[-1] = almost dead"""
rabbits = [0] * m
rabbits[0] = 1
for i in range(n - 1):
tmp, total = rabbits[0], 0
for j in range(1, m):
total += rabbits[j]
rabbits[j], tmp = tmp, rabbits[j]
rabbits[0] = total
... |
def extract_lines(all_dialog, speaker):
"""Get only one speaker's lines from the extracted dialog."""
return [line for line_speaker, line in all_dialog if line_speaker == speaker] |
def get_pattern(full, sub1, sub2, sub3):
"""
>>> get_pattern("aeyceayaeyyecaeyaeyyecceayyecceay", "aey", "ceay", "yec")
[65, 44, 66, 44, 65, 44, 67, 44, 65, 44, 65, 44, 67, 44, 66, 44, 67, 44, 66, 10]
"""
result = []
position = 0
while position < len(full):
r1 = full.find(sub1, posit... |
def keys_to_camel_case(value):
"""
Transform keys from snake to camel case (does nothing if no snakes are found)
:param value: value to transform
:return: transformed value
"""
def str_to_camel_case(snake_str):
components = snake_str.split("_")
return components[0] + "".join(x.t... |
def _pad(s: str, length: int) -> str:
"""
Pads *s* to length *length*.
"""
missing = length - len(s)
return s + " " * (missing if missing > 0 else 0) |
def _remove_batch_rule(rules):
"""Removes the batch rule and returns the rest."""
return [(k, v) for (k, v) in rules if k != "batch"] |
def prob2label(prod):
"""Transforms Probability to 0/1 Labels
Args:
prod: Probability of prediction (confidence)
Returns:
int: 0/1 Labels
"""
return (prod > 0.5) |
def get_link(link):
"""Returns an image link"""
if not link.get('url'):
return ""
elif link.get('img'):
return ('<a href="{0}" target="_blank" title="{1}" class="btn-custom">'
'<img width="25" height="25" src="{2}">'
'</a>'.format(link['url'], link['title'], l... |
def formatSearchQuery(query):
"""It formats the search string into a string that can be sent as a url paramenter."""
return query.replace(" ", "+") |
def parse_to_dicts(lines, containers):
"""
Parses a list of lines into tuples places in the given containers.
The lists of lines has the following format
token1: tval1
key1: val11
key2: val12
token1: tval2
key1: val21
key2: val22
:param lines:
:param containers: a dictio... |
def writeHeaderLine(header, filled=False):
"""Used to write a line in the header for the errors.log file.
Args:
header (string): Text to write in one line of the header.
Returns:
(string): Formatted header line string.
"""
headerLen = 80
maxLen = headerLen - 2; # -2 fo... |
def binary_search(sorted_a: list, x, epsilon=0.0000001) -> int:
"""Returns the index of x in a sorted array a or -1"""
a = sorted_a
def b_search(l: int, r: int) -> int:
if l > r:
return -1
m = (l + r) // 2
if abs(a[m] - x) < epsilon:
return m
elif x <... |
def jsonrpc_error(id, code, message, data=None):
"""Create JSON-RPC error response"""
return {
'jsonrpc': '2.0',
'error': {
'code': code,
'message': message,
'data': data,
},
'id': id,
} |
def rom_to_int(string):
"""
Converts roman numeral to integer ( only up 50)
(case sensitive)
:param string: a roman numeral in lower case
"""
table = [['l', 50], ['xl', 40], ['x', 10], ['ix', 9], ['v', 5], ['iv', 4], ['i', 1]]
returnint = 0
for pair in table:
continu... |
def _format_value(value):
"""
Hyperparameter can have many types, sometimes they can even be lists.
If one of the value is a float, it has to be compact.
"""
if isinstance(value, str):
return value
try:
return f"[{','.join(_format_value(x) for x in value)}]"
except TypeErro... |
def filter_hessian_data(hessian_data):
""" Filter contents of the hessian data, pick the entry with lowest energy """
res = {}
lowest_energy = {}
print("Start filtering hessian data by picking the entry with lowest energy")
for entry_name, data in hessian_data.items():
mol_name = entry_name.... |
def random(v1=None, v2=None):
"""Returns a random value.
This function does a lot of things depending on the parameters:
- If one or more floats is given, the random value will be a float.
- If all values are ints, the random value will be an integer.
- If one value is given, random return... |
def _dotUnquoter(line):
"""
Remove a byte-stuffed termination character at the beginning of a line if
present.
When the termination character (C{'.'}) appears at the beginning of a line,
the server byte-stuffs it by adding another termination character to
avoid confusion with the terminating se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.