content stringlengths 42 6.51k |
|---|
def splitFilename(fn):
"""Split filename into base and extension (base+ext = filename)."""
if '.' in fn:
base, ext = fn.rsplit('.', 1)
else:
ext = ''
base = fn
return base, ext |
def _get_parent_scope(scope):
"""Removes the final leaf from a scope (`a/b/c/` -> `a/b/`)."""
parts = scope.split('/')
return '/'.join(parts[:-2] + parts[-1:]) |
def combine_sigma(sig1, sig2):
""" Combine the sigma values of two species.
:param sig1: sigma of species 1
:type sig1: float
:param sig2: sigma of species 2
:type sig2: float
:return: sig_comb
:rtpye: float
"""
if sig1 is not None and sig2 is not None:
... |
def floatToFixed(value, precisionBits):
"""Converts a float to a fixed-point number given the number of
precisionBits. Ie. int(round(value * (1<<precisionBits))).
>>> floatToFixed(0.8, 14)
13107
>>> floatToFixed(1.0, 14)
16384
>>> floatToFixed(1, 14)
16384
>>> floatToFixed(0, 14)
0
"""
return int(round(v... |
def isInPar(db, chrom, start, end):
""" return None if not in PAR or "1" or "2" if genome is hg19 or hg38 and chrom:start-end is in a PAR1/2 region """
if db not in ("hg19", "hg38"):
return None
if not chrom in ("chrX", "chrY"):
return None
# all coordinates are from https://en.wikipedi... |
def parse_redirect_params(redirect_str):
"""
Parse a redirect string into it's url reverse key and optional kwargs
"""
if not redirect_str:
return None, None
redirect_key = redirect_str
redirect_kwargs = {}
redirect_key_parts = redirect_str.split("|")
if len(redirect_key_parts) =... |
def helper(n, max_n):
"""
:param n: (int) number n for pick largest digit
:param max_n: (int) largest digit
:return: (int) largest digit
"""
# Base Case
if n == 0: # return largest digit
return max_n
# Recursive Case
else:
remainder = n % 10 # pick digit
if remainder > max_n:
return helper(n//1... |
def win_or_block(board, win_rows, test_mark, move_mark):
"""
Check for both a possible winning move or a possible
blocking move that the machine should make & makes
that move. Differentiate these moves with the space
marking characters used for test_mark and move_mark.
To check for a winning mov... |
def rot13(string):
"""
Rot13 for only A-Z and a-z characters
"""
try:
return ''.join(
[chr(ord(n) + (13 if 'Z' < n < 'n' or n < 'N' else -13)) if ('a' <= n <= 'z' or 'A' <= n <= 'Z') else n for
n in
string])
except TypeError:
return None |
def binary_search(a, value):
"""
Searches a value in a (sorted) list. Return the index if found, otherwise
returns <None>.
"""
start = 0
end = len(a) - 1
while (start <= end):
i = (start + end) // 2 # Middle point
# If found the value
if (a[i] == value):
... |
def create_result(m, d, y):
""" Creates result """
result = ''
if m < 10:
result += '0' + str(m)
else:
result += str(m)
result += '/'
if d < 10:
result += '0' + str(d)
else:
result += str(d)
result += '/' + str(y)
return result |
def deduce(control, length, arr):
"""Return the only number left."""
matches = list(
filter(
lambda x: len(x) == length and x not in arr,
control))
if len(matches) != 1:
raise ValueError('Something went wrong. No deduction possible.')
return matches[0] |
def test_1(input):
"""
>>> test_1("hijklmmn")
True
>>> test_1("abcdffaa")
True
>>> test_1("")
False
>>> test_1("abdfasdf")
False
"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
for i in range(len(input)-3):
if input[i:i+3] in alphabet:
return True
ret... |
def cents_to_string(cents):
"""
Convert an integer number of cents into a string representing a dollar
value.
"""
return '%d.%02d' % divmod(cents, 100) |
def listToStr(list, seperator=" "):
""" Return a string consists of elements in list seperated by
seperator.
"""
return seperator.join(map(str,list)) |
def pathfinder_auxiliary(row, col, M):
"""
Find the maximum path from the longest path's location
@param row The row index in the matrix of where to find the longest path
@param col The column index in the matrix of where to find the longest path to
@param M The M... |
def needs_write_barrier(obj):
""" We need to emit write barrier if the right hand of assignment
is in nursery, used by the JIT for handling set*_gc(Const)
"""
if not obj:
return False
# XXX returning can_move() here might acidentally work for the use
# cases (see issue #2212), but this i... |
def sizeFormat(sizeInBytes):
"""
Format a number of bytes (int) into the right unit for human readable
display.
"""
size = float(sizeInBytes)
if sizeInBytes < 1024:
return "%.0fB" % (size)
if sizeInBytes < 1024 ** 2:
return "%.3fKb" % (size / 1024)
if sizeInBytes < 1024 *... |
def below(prec, other_prec):
"""Whether `prec` is entirely below `other_prec`."""
return prec[1] < other_prec[0] |
def escape(string):
"""Escape strings to be SQL safe"""
if '"' in string:
raise Exception("Can't escape identifier {} because it contains a backtick"
.format(string))
return '"{}"'.format(string) |
def fibonacci(n):
"""
FIBONACCI SEQUENCE
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Info about its calculation:
https://stackoverflow.com/questions/18172257/efficient-calculation-of-fibonacci-series
Calculate them using recursive function
This is a primitive recursive solution
"""
if n <= ... |
def f1_score(precision, recall):
"""
Compute f1 score.
"""
if precision or recall:
return 2 * precision * recall / (precision + recall)
return 0 |
def create_biomarker_schema(schema: dict) -> dict:
"""
Factory method for creating a schema object.
Arguments:
schema {dict} -- Cerberus schema dictionary.
Returns:
dict -- EVE endpoint definition.
"""
base_dict = {
"public_methods": [],
"resource_methods": ["GE... |
def not_none(input_value, replacement_value=""):
""" If the given input value is None, replace it with something else """
if input_value is None:
return replacement_value
return input_value |
def flatten_list(l):
"""
Flatten a list recursively without for loops or additional modules
Parameters
---------
l : list
List to flatten
Example Usage:
.. code-block:: python
from autoprotocol_utilities.misc_helpers import flatten_list
temp_flattened_... |
def sci_to_float(s):
"""
Converts a string of the form 'aEb' into an int given by a*10^b
"""
s = s.replace("e", "E")
if 'E' in s:
s = s.split('E')
return float(s[0]) * 10**float(s[1])
return s |
def count_yes( answers, part2=False ):
"""
For Part 1:
-----------
This function returns the count of questions to which atleast one
person in the group answered yes.
For Part 2:
-----------
This function returns the count of questions to which every
person in the group answered... |
def midpoints(vec):
"""
:param vec: list of N coordinates
:return: list of N-1 points that represent the midpoint between all pairwise N coordinates
"""
return [vec[i] + abs(vec[i+1] - vec[i]) / 2.0 for i in range(len(vec)-1)] |
def get_url_for_exhibition(after, before, apikey):
"""
This function writes a url(a string) for Harvard Art Museums API to get a dataset with all exhibitions information, held in the selected years.
Parameters
----------
after: str
A string of a starting year of a period when exhibition... |
def find_interval(value, intervals):
"""
Find the interval in which value exists in.
Returns the index where the interval interval_ends.
"""
for index, interval in enumerate(intervals):
if interval[0] <= value <= interval[1]:
return index
return -1 |
def dB_function(dB):
""" Convert dB into linear units """
linear = 10**(dB/10.)
return linear |
def factorial(n):
"""
Given an integer value,
return its factorial without using resursive approach
"""
facto = 1 # Assignment Takes constant time: O(1)
while n > 1: # This loop will run n times: O(n)> Because the loop has 2 lines to execute, it will be O(2n)
facto *= n # Takes constant time: O(1)
... |
def calculation(m, d, n):
"""
Calculates m**d mod(n) more efficiently
"""
value = 1
for _ in range(d):
value = (value * m) % n
return value |
def write_output(best_solution):
"""
Parses best_solution's path and returns desired strings
"""
output_data = str(best_solution[1]) + ' ' + str(1) + '\n'
output_data += ' '.join([i[1] for i in best_solution[0] if int(i[1]) != -1])
return output_data |
def getCollectionForId(obj_id):
""" return groups/datasets/datatypes based on id """
if not isinstance(obj_id, str):
raise ValueError("invalid object id")
collection = None
if obj_id.startswith("g-"):
collection = "groups"
elif obj_id.startswith("d-"):
collection = "datasets"... |
def fahrenheit(value: float, target_unit: str) -> float:
"""
Utility function for Fahrenheit conversion in Celsius or in Kelvin
:param value: temperature
:param target_unit: Celsius, Kelvin or Fahrenheit
:return: value converted in the right scale
"""
if target_unit == "C":
# Conver... |
def Main(a, b):
"""
:param a:
:param b:
:return:
"""
j = a & b
q = j | b
m = a ^ q
return m |
def _to_module_name(fn):
# type: (str) -> str
"""
Try to guess imported name from file descriptor path
"""
fn = fn.replace('/', '_dot_')
fn = fn[:-len('.proto')] # strip suffix
fn += '__pb2' # XXX: might only be one underscore?
return fn |
def hyperheader2dic(head):
"""
Convert a hypercomplex block header into a Python dictionary.
"""
dic = dict()
dic["s_spare1"] = head[0]
dic["status"] = head[1]
dic["s_spare2"] = head[2]
dic["s_spare3"] = head[3]
dic["l_spare1"] = head[4]
dic["lpval1"] = head[5]
dic["rpval1"] ... |
def apache_client_convert(client_dn, client_ca=None):
"""
Convert Apache style client certs.
Convert from the Apache comma delimited style to the
more usual slash delimited style.
Args:
client_dn (str): The client DN
client_ca (str): [Optional] The client CA
Returns:
t... |
def get_lr(lr, epoch, steps, factor):
"""Get learning rate based on schedule."""
for s in steps:
if epoch >= s:
lr *= factor
return lr |
def interpret_word_seg_results(char_seq, label_seq):
"""Transform model output into user-friendly contents.
Example: In CWS, convert <BMES> labeling into segmented text.
:param char_seq: list of string,
:param label_seq: list of string, the same length as char_seq
Each entry is one of ('B',... |
def is_droppedaxis(slicer):
"""Return True if the index represents a dropped axis"""
return isinstance(slicer, int) |
def convert_chars_to_unicode(lst):
"""
Given a list of characters, convert any unicode variables to its unicode repr
Input: List of characters
Output: List of characters, with the ones specified as variable names replaced
with the actual unicode representation
"""
output ... |
def vue(item):
"""Filter out vue templates.
For example: {{ "message.text" | vue }} will be transformed to just {{ "message.text" }} in HTML
Parameters:
item (str): The text to filter.
Returns:
item (str): Text that jinja2 will render properly.
"""
return f"{{{{ {item} }}}}" |
def IntToRGB(intValue):
""" Convert an FL Studio Color Value (Int) to RGB """
blue = intValue & 255
green = (intValue >> 8) & 255
red = (intValue >> 16) & 255
return (red, green, blue) |
def arg_valid_val(args_array, opt_valid_val):
"""Function: arg_valid_val
Description: Validates data for options based on a dictionary list.
Arguments:
(input) args_array -> Array of command line options and values.
(input) opt_valid_val -> Dictionary of options & their valid values
... |
def get_term_class(go, alias, is_a):
"""Find the class (P, C or F) of the given GO term."""
x = alias.get(go, go)
while x:
if x in ["GO:0008150", "obsolete_biological_process"]:
return "P"
elif x in ["GO:0005575", "obsolete_cellular_component"]:
return "C"
eli... |
def get_family_name_from(seq_name_and_family):
"""Get family accession from concatenated sequence name and family string.
Args:
seq_name_and_family: string. Of the form `sequence_name`_`family_accession`,
like OLF1_CHICK/41-290_PF00001.20. Assumes the family does not have an
underscore.
Returns:... |
def _try_rsplit(text, delim):
"""Helper method for splitting Email Received headers.
Attempts to rsplit ``text`` with ``delim`` with at most one split.
returns a tuple of (remaining_text, last_component) if the split was
successful; otherwise, returns (text, None)
"""
if delim in text:
... |
def _animal_id_suffixed(prev_id: float, num: int, addition_base=0.5) -> float:
"""adds a decimal number to make a new animal_id distinct from prev_id"""
if num == 0:
return prev_id
else:
return prev_id + addition_base ** num |
def too_large(e):
""" Check if file size is too large """
return "File is too large", 413 |
def convert_to_value(item, target_values, value, matching=True):
"""Convert target strings to NaN.
Converts target strings listed in target_values to value so they can be
processed within a DataFrame, such as for removing specific rows. If
matching=False, strings that do not those listed in values ... |
def delete(old_string, starting_index, ending_index):
""" Removes portion from old_string from starting_index to ending_index"""
# in log, index starts at 1
starting_index -= 1
return old_string[:starting_index] + old_string[ending_index:] |
def add_suffix_to_fp(file_path, suffix, path_separator='/'):
"""
Add a suffix to a file name (not a new file type; e.g. 'file' becomes 'file_name').
Return new filepath.
"""
new_file_path = ''
new_file_path = file_path.split(path_separator)
file_name = new_file_path[-1].split('.')
f... |
def backward_substitution(matrix_u, matrix_y):
""" Backward substitution method for solution of linear systems.
Solves the equation :math:`Ux = y` using backward substitution method
where :math:`U` is a upper triangular matrix and :math:`y` is a column matrix.
:param matrix_u: U, upper triangular matr... |
def isGoodRun(goodRunList, run):
"""
_isGoodRun_
Tell if this is a good run
"""
if goodRunList is None or goodRunList == {}:
return True
if str(run) in goodRunList.keys():
# @e can find a run
return True
return False |
def extract_md_header(file):
"""Extract the header from the input markdown file.
Paramters
---------
file : generator
A generator that generates lines.
Returns
-------
string | None
The extracted header content or `None`.
"""
first_line = True
header_content = "... |
def num_to_text(num):
# Make sure we have an integer
"""
Given a number, write out the English representation of it.
:param num:
:return:
>>> num_to_text(3)
'three'
>>> num_to_text(14)
'fourteen'
>>> num_to_text(24)
'twenty four'
>>> num_to_text(31)
'thirty one'
... |
def _create_issue_result_json(issue_id, summary, key, **kwargs):
"""Returns a minimal json object for an issue."""
return {
"id": "%s" % issue_id,
"summary": summary,
"key": key,
"self": kwargs.get("self", "http://example.com/%s" % issue_id),
} |
def covert_if_not_ascii(value):
"""converts a value if it is not a ascii supported str"""
try:
value.encode("ascii")
return value
except (AttributeError, UnicodeEncodeError):
return str(value) |
def image_search(inlist, filename, debug=False):
"""
Args:
inlist: List of filepaths
filename: Suffix to match to
debug: Extra info required?
Returns: Single filepath
"""
if debug:
print(inlist)
print(filename)
im = [i for i in inlist if i.split("/")[-1... |
def identify_slack_event(event):
"""Identify the Slack event type given an event object.
Parameters
----------
event : `dict`
The Slack event object.
Returns
-------
slack_event_type : `str`
The name of the slack event, one of https://api.slack.com/events.
"""
prima... |
def pip_has_version(package):
"""
For pip install strings: Checks if there is a part that mentions the version
"""
for c in ["<", "=", ">"]:
if c in package:
return True
return False |
def setup_config(config):
"""
Make config arguments the proper type!
"""
config['num_req_to_send'] = int(config['num_req_to_send'])
return config |
def full_adder(a,b,c=0):
"""Single bit addition with carry"""
s = (a+b+c)%2
cout = a*b + (c*(a+b)%2)
return s,cout |
def parse_hex_color(value):
"""
Convert a CSS color in hexadecimal notation into its R, G, B components.
:param value: A CSS color in hexadecimal notation (a string like '#000000').
:return: A tuple with three integers (with values between 0 and 255)
corresponding to the R, G and B compone... |
def fix_opcode_names(opmap):
"""
Python stupidly named some OPCODES with a + which prevents using opcode name
directly as an attribute, e.g. SLICE+3. So we turn that into SLICE_3 so we
can then use opcode_23.SLICE_3. Later Python's fix this.
"""
return dict([(k.replace('+', '_'), v)
... |
def get_output(filename: str) -> str:
"""Gets the relative file path for the provided output file."""
return "./output/" + filename |
def infer_app_url(headers: dict, register_path: str) -> str:
"""
ref: github.com/aws/chalice#485
:return: The Chalice Application URL
"""
host: str = headers["host"]
scheme: str = headers.get("x-forwarded-proto", "http")
app_url: str = f"{scheme}://{host}{register_path}"
return app_url |
def stacks_dna_dna(inseq, temp=37):
"""Calculate thermodynamic values for DNA/DNA hybridization.
Input Arguments:
inseq -- the input DNA sequence of the DNA/DNA hybrid (5'->3')
temp -- in celcius for Gibbs free energy calc (default 37degC)
salt -- salt concentration in units of mol/L (defau... |
def get_tn(num_bases, tp, fp, fn):
"""
This functions returns the number of true negatives.
:param num_bases: Number of bases
:type num_bases: int
:param tp: Number of true positives
:type tp: int
:param fp: Number of false positives
:type fp: int
:param fn: Number of false negative... |
def remove_file(filename, recursive=False, force=False):
"""Removes a file or directory."""
import os
try:
mode = os.stat(filename)[0]
if mode & 0x4000 != 0:
# directory
if recursive:
for file in os.listdir(filename):
success = remo... |
def curry(tup_fn, x, y):
"""``curry :: ((a, b) -> c) -> a -> b -> c``
Converts an uncurried function to a curried function.
"""
return tup_fn((x, y)) |
def implode(list):
"""
Takes list and returns standardized version of it.
:param list: list
:return: standardized list
"""
return ', '.join([str(i) for i in list]) |
def popup(message, title):
"""
Function that returns UR script for popup
Args:
message: float. tooltip offset in mm
title: float. tooltip offset in mm
Returns:
script: UR script
"""
script = 'popup("%s","%s") \n' %(message,title)
return script |
def normalize_job_id(job_id):
"""Convert the job id into job_id, array_id."""
return str(int(job_id)), None |
def gather_word_info(hot_posts, wordlist,
posts_len=None,
counter=0,
words_info=None):
"""does the recursion to grab word info from wordlist and posts
"""
if hot_posts is None:
return
# generate defaults
if posts_len is None:
... |
def check_form(media: dict, form: list, allow_null=[]):
""" Obsolete function """
if media == None:
return False
media_list = list(media)
for i in form:
if None in media_list or i not in media_list:
return False
for x in media:
if media.get(x) == None ... |
def funtion_0(x, a):
"""
"""
if x < a:
return 0.0
return 1.0 |
def convert_truelike_to_bool(input_item, convert_float=False, convert_nontrue=True):
"""Converts true-like values ("true", 1, True", "WAHR", etc) to python boolean True.
Parameters
----------
input_item : string or int
Item to be converted to bool (e.g. "true", 1, "WAHR" or the equivalent in se... |
def is_empty_row(row):
"""Returns True if all cells in a row evaluate to False
>>> is_empty_row(['', False, ''])
True
>>> is_empty_row(['', 'a', ''])
False
"""
return not any(row) |
def prefer_lnc_over_anti(rna_type, _):
"""
This will remove antisense_RNA to use lncRNA if we have both. This is
because the term antisense_RNA usually but not always means
antisense_lnc_RNA. Until we switch to SO terms which can express this we
will switch.
"""
if rna_type == set(["antisen... |
def upper_first(s):
""" uppercase first letter """
s = str(s)
return s[0].upper() + s[1:] |
def divide(a, b):
""" Return result of dividing a by b """
print("=" * 20)
print("a: ", a, "/ b: ", b)
try:
return a/b
except (ZeroDivisionError, TypeError):
print("Something went wrong!")
raise |
def __vertical_error_filters(
vertical_error: int
) -> tuple:
"""Make filters that correct for a vertical error between the cameras"""
if vertical_error > 0:
# Right video is too low
ve_left = 'crop=iw:ih-{}:0:{},'.format(vertical_error, vertical_error)
ve_right = 'crop=iw:ih-{}:... |
def split_system_subsystem(system_name):
"""Separate system_name and subsystem_name str from the input
Ex: system_name=NE1[cli,dip,if1] will be separate into
system_name=NE1
subsystem_name str = 'cli, dip, if1'"""
new_system_name = system_name.split('[')
system_name = new_system... |
def unquoted(term):
"""unquoted - unquotes string
Args:
term: string
Returns:
term: without quotes
"""
if term[0] in ["'", '"'] and term[-1] in ["'", '"']:
return term[1:-1]
else:
return term |
def self_ensemble_hyperparams(lr=1e-3, unsupervised_weight=3.0, wd=5e-5, scheduler=False):
"""
Return a dictionary of hyperparameters for the Self-Ensemble algorithm.
Default parameters are the best ones as found through a hyperparameter search.
Arguments:
----------
lr: float
Learning ... |
def parse(s:str):
"""Get the next space separated word from a string. Return (word,remainder)"""
s=s.strip()
i=s.find(" ")
if i<0:
i=len(s)
result=s[0:i].strip()
remain=s[i+1:].strip()
return (result,remain) |
def all(iterable):
"""
Return True if all elements are set to True. This
function does not support predicates explicitly,
but this behavior can be simulated easily using
list comprehension.
>>> from sympy import all
>>> all( [True, True, True] )
True
>>> all( [True, False, True] )
... |
def _get_inner_type(typestr):
""" Given a str like 'org.apache...ReversedType(LongType)',
return just 'LongType' """
first_paren = typestr.find('(')
return typestr[first_paren + 1 : -1] |
def square_helper(start, finish, expand1, expand2, size_limit):
"""
This function can expand one axis of the size of the bounding box.
Parameters:
start (int): the coordinate of the start point.
finish (int): the coordinate of the finish point.
expand1 (int): the n... |
def remove_soft_hyphens(line):
"""Removes any soft hyphens or middle dots"""
line = line.replace(u'\u00AC', '') # not sign (Word's soft hyphen)
line = line.replace(u'\u00AD', '') # soft hyphen
line = line.replace(u'\u00B7', '') # middle dot
return line |
def prime_factors(n):
"""
Compute the prime factors of the given number
:param n: Number you want to compute the prime factors (intger)
:return: Prime factors of the given number (list of integer)
"""
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:... |
def isSBMLModel(obj):
"""
Tests if object is a libsbml model
"""
cls_stg = str(type(obj))
if ('Model' in cls_stg) and ('lib' in cls_stg):
return True
else:
return False |
def list_to_set24(l):
"""Convert a bit vector to an integer"""
res = 0
for x in l: res ^= 1 << x
return res & 0xffffff |
def _flatten_index(i, alpha, num_symbols):
"""
Map position and symbol to index in
the covariance matrix.
Parameters
----------
i : int, np.array of int
The alignment column(s).
alpha : int, np.array of int
The symbol(s).
num_symbols : int
The number of symbols o... |
def getValuesInInterval(dataTupleList, start, stop):
"""
Gets the values that exist within an interval
The function assumes that the data is formated as
[(t1, v1a, v1b, ...), (t2, v2a, v2b, ...)]
"""
intervalDataList = []
for dataTuple in dataTupleList:
time = dataTuple[0]
... |
def _transpose(x):
"""The transpose of a matrix
:param x: an NxM matrix, e.g. a list of lists
:returns: a list of lists with the rows and columns reversed
"""
return [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.