content stringlengths 42 6.51k |
|---|
def is_position_in_coding_feature(position, cds_features):
"""Checks whether the given position lies inside of a coding feature
in the given genome record.
"""
for feature in cds_features:
if (feature.location.start <= position and
position < feature.location.end):
re... |
def is_empty_alignment(alignment):
"""Returns True if alignment is empty.
Args:
alignment (str/Bio.Align.MultipleSequenceAlignment): A multiple sequence
alignment string in FASTA format or a multiple sequence alignment
object, either as a Bio.Align.MultipleSequenceAlignment or a... |
def get_indexes(start_index, chunk_size, nth):
"""
Creates indexes from a reference index, a chunk size an nth number
Args:
start_index (int): first position
chunk_size (int): Chunk size
nth (int): The nth number
Returns:
list: First and last position of indexes
... |
def currency_to_protocol(amount):
"""
Convert a string of 'currency units' to 'protocol units'. For instance
converts 19.1 bitcoin to 1910000000 satoshis.
Input is a float, output is an integer that is 1e8 times larger.
It is hard to do this conversion because multiplying
floats causes roundin... |
def parseIndex(index=None):
"""
Parse index query based on string
Parameters
----------
index:str
Examples
---------
"""
try:
if index is None:
value=slice(None,None,None)
else:
index=str(index)
if ":" in index:
start,end=index.split(":")
if ... |
def get_diagonal_points(start_x, start_y, end_x, end_y):
"""
Returns a list of tuples that contains diagonal points from one point to another
:param start_x:
:param start_y:
:param end_x:
:param end_y:
:return:
"""
points = []
y_inc = 1
if int(start_x) > int(end_x):
s... |
def __convert_size(size_in_bytes, unit):
"""
Converts the bytes to human readable size format.
Args:
size_in_bytes (int): The number of bytes to convert
unit (str): The unit to convert to.
"""
if unit == 'GB':
return '{:.2f} GB'.format(size_in_bytes / (1024 * 1024 * 1024))
elif unit =... |
def longest_repetition(lst):
"""
Takes as input a list, and returns the element in the list that has the
most consecutive repetitions. If there are multiple elements that have
the same number of longest repetitions, returns the one that appears
first. If the input list is empty, returns None.
""... |
def convert_list_to_dict(origin_list):
""" convert HAR data list to mapping
@param (list) origin_list
[
{"name": "v", "value": "1"},
{"name": "w", "value": "2"}
]
@return (dict)
{"v": "1", "w": "2"}
"""
return {
item["name"]: item["value"]
... |
def esc_seq(n, s):
"""Escape sequence. Call sys.stdout.write() to apply."""
return '\033]{};{}\007'.format(n, s) |
def format_sizeof(num, suffix='', divisor=1000):
"""
Code from tqdm
Formats a number (greater than unity) with SI Order of Magnitude
prefixes.
Parameters
----------
num : float
Number ( >= 1) to format.
suffix : str, optional
Post-postfix [default: ''].
divisor :... |
def corr_units(varlist):
"""
The unit correction is necessary as in the case when there are subscripts,
the units are not associated correctly with all the subscript instances
therefore the same unit needs to be passed down to other instances
unit_dict is not used anywhere else, but could be:
... |
def PathHasDriveLetter(path):
"""Check path for windows drive letter.
Use 1:2 to avoid raising on single character paths.
Args:
path: path string
Returns:
True if this path has a drive letter.
"""
return path[1:2] == ":" |
def get_attribute_value(owner_uri: str, attribute_name: str):
"""Get attribute value for given attribute name from the owner uri"""
if owner_uri is not None and '/' in owner_uri:
sliced_owner_uri = owner_uri[owner_uri.rindex('/'):len(owner_uri)]
splited_owner_uri = sliced_owner_uri.split('|')
... |
def solve_fast(k, lim):
"""A little faster version of 'solve', but with a high memory usage. This
version uses an array to store all the previous values, it uses the
value as the index and the previous index as the element. """
seq = [*k]
nums = [None] * (max(seq) + 1)
for i, elem in enumera... |
def convert_keys_to_string(dictionary):
"""
Recursively converts dictionary keys to strings.
Found at http://stackoverflow.com/a/7027514/104365
"""
if not isinstance(dictionary, dict):
return dictionary
return dict([(str(k), convert_keys_to_string(v))
for k, v in dictiona... |
def get_high_and_water_ways(ways):
"""
Extracts highways and waterways from all ways.
:param ways: All ways as a dict
:return: highways (list), waterways (list)
"""
highways = list()
waterways = list()
for way_id in ways:
way = ways[way_id]
if "highway" in way.tags:
... |
def format_website_string(website):
"""Returns a formatted website string to be used for siteinfo.
Args:
website (string): user-supplied.
Returns:
string: lower-case, prefixes removed.
"""
formatted = website.lower()
prefixes = ["https://", "http://", "www."]
for prefix in pr... |
def pe44(limit=1500):
"""
>>> pe44()
(5482660, 7042750, 1560090, 2166, 1019)
"""
pents = [i * (3 * i - 1) >> 1 for i in range(1, limit << 1)]
ps = set(pents)
for i in range(limit):
p1 = pents[i]
for j in range(i + 1, (limit << 1) - 1):
p2 = pents[j]
di... |
def parse_sk_m(line):
"""
Parse sk_m measurements.
This is a line having this format:
$ sk_m_print(0,send-1-0-1) idx= 4 tscdiff= 42
@return None, in case the lines is not an sk_m, a tuple (core, title, idx, tscdiff) otherwise
"""
if line.startswith('sk_m_print'):
(desc, _, idx, _,... |
def accepts(source):
""" Do we accept this source? """
if source["type"] == "git":
return True
# There are cases where we have a github repo, but don't wanna analyze the code, just issues
if source["type"] == "github" and source.get("issuesonly", False) == False:
return True
return F... |
def dict_attr(attr_dict: dict, attr_dict_key: str):
"""
:rtype: dict
"""
if attr_dict_key in attr_dict.keys():
return attr_dict[attr_dict_key]
return {} |
def is_instrinsic(input):
"""
Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single
key that is the name of the intrinsics.
:param input: Input value to check if it is an intrinsic
:return: True, if yes
"""
if input is not None and is... |
def _closure_service(target, type = "binary"):
""" Computes a target name, postfixed with a sentinel indicating
a request for a Closure-based gRPC client. """
return "%s-%s-%s" % (target, "grpc_js", type) |
def logBase2(n):
"""assumes that n is a postivie int
returns a float that approximates the log base 2 of n"""
import math
return math.log(n, 2) |
def order_annotations(annotation):
"""
Standardizes the annotations that are presented to users where more than one is applicable.
Parameters
----------
annotation : str
The annotation to be returned to the user in the command bar.
"""
single_annotations = ["Akk", "Dat", "Ge... |
def factorial(n):
"""
Calculate n!
Args:
n(int): factorial to be computed
Returns:
n!
"""
if n == 0:
return 1 # by definition of 0!
return n * factorial(n-1) |
def validate_package_weight_normal_code_type_annotation(weight: int) -> bool:
"""
:param weight: weight of mail package, that we need to validate
:return: if package weight > 200 - return False (we cannot deliver this package)
"""
if weight <= 0:
raise Exception("Weight of package cannot be ... |
def bisection(func, low, high, eps):
"""
Find the root on the interval [low, high] to the tolerance eps
( eps apples to both function value and separation of the bracketing values )
"""
# if bracket is backwards, correct this
if low > high:
low, high = high, low # standard way to swap ... |
def get_samples_panfamilies(families, sample2family2presence):
"""Get the sorted list of all the families present in the samples
Can be a subset of the pangenome's set of families"""
panfamilies = set()
for f in families:
for s in sample2family2presence:
if sample2family2presence[s][... |
def add(a, b):
"""This program adds two numbers and return result"""
result = a + b
return result |
def num_splits(s: list, d: int) -> int:
"""Return the number of ways in which s can be partitioned into two
sublists that have sums within d of each other.
>>> num_splits([1, 5, 4], 0) # splits to [1, 4] and [5]
1
>>> num_splits([6, 1, 3], 1) # no split possible
0
>>> num_splits([-2, 1, 3... |
def partial_clique_graph(i, set_cliques, minimum, num_cliques):
"""
Function that supports the creation of the clique graph, the second stage of CPM.
This function is detached from the main function since it is parallelised
(based on the amout of workers).
Parameters
----------
i : integer... |
def create_ref(path):
"""
Create a json definition reference to a specific path
"""
return '#/definitions/' + path |
def ordlist(s):
"""Turns a string into a list of the corresponding ascii values."""
return [ord(c) for c in s] |
def _is_trivial_paraphrase(exp1, exp2):
"""
Return True if:
- w1 and w2 differ only in gender and/or number
- w1 and w2 differ only in a heading preposition
:param exp1: tuple/list of strings, expression1
:param exp2: tuple/list of strings, expression2
:return: boolean
"""
d... |
def lchop(string, prefix):
"""Removes a prefix from string
:param string: String, possibly prefixed with prefix
:param prefix: Prefix to remove from string
:returns: string without the prefix
"""
if string.startswith(prefix):
return string[len(prefix):]
return string |
def _convert_FtoK(T):
""" convert Fahrenheit to Kelvin.
:param T: Temperature (F).
:return: Temperature (K).
"""
return (T - 32.0)*5.0/9.0 + 273.15 |
def get_feature_directory_name(settings_dict):
"""Get the directory name from the supplied parameters and features."""
dir_string = "%s_%d_%d_%d_%d" % (
settings_dict["feature"],
settings_dict["fft_sample_rate"],
settings_dict["stft_window_length"],
settings_dict["stft_hop_length... |
def decode_modm(limbs):
"""
Decodes scalar mod m from limbs with base 30
:param n:
:return:
"""
n = 0
c = 0
shift = 0
mask = (1 << 30) - 1
for i in range(9):
n += ((limbs[i] & mask) + c) << shift
c = limbs[i] >> 30
shift += 30
return n |
def fibonacci_sequence(size):
"""fibonacci
"""
sequence = []
for n in range(size):
if n == 0:
sequence.append(1)
elif n == 1:
sequence.append(1)
else:
sequence.append(sequence[-1] + sequence[-2])
return sequence |
def extract_state_from_event(state_key: str, event_data: dict):
"""
Extract information from the event data to make a new sensor state.
Use 'dot syntax' to point for nested attributes, like `service_data.entity_id`
"""
if state_key in event_data:
return event_data[state_key]
elif state_... |
def get_one_hot_index_from_ints(tonic, quality, num_qualities=3):
"""
Get the one-hot index of a chord with the given tonic and quality.
Parameters
==========
tonic : int
The tonic of the chord, where 0 is C. None represents a chord with no tonic.
quality : int
The ... |
def init_times(times, **kwargs):
"""Add attributes to a set of times."""
for t in times:
t.update(**kwargs)
return times |
def load_array_meta(loader, filename, index):
"""
Load the meta-data data associated with an array from the specified index
within a file.
"""
return loader(filename, index) |
def get_link(js):
""" @todo """
if 'url' in js:
return js['url']
if 'architecture' not in js:
return None
for bits in ['64bit', '32bit']:
if bits not in js['architecture']:
continue
if 'url' not in js['architecture'][bits]:
continue
return ... |
def Wrap(content, cols=76):
"""Wraps multipart mime content into 76 column lines for niceness."""
lines = []
while content:
lines.append(content[:cols])
content = content[cols:]
return '\r\n'.join(lines) |
def friendly_repr(obj, *attributes):
"""Render a human friendly representation of a database model instance."""
values = []
for name in attributes:
try:
value = getattr(obj, name, None)
if value is not None:
values.append("%s=%r" % (name, value))
excep... |
def unlist(collection):
"""Extracts element from @collection if len(collection) 1.
:returns: element in collection or None.
:raises: TypeError if len(collection) > 1
"""
if len(collection) > 1:
raise TypeError("Cannot unlist collection: {0}\n".format(collection) +
"C... |
def _change_from_camel_case(word):
"""Changes dictionary values from camelCase to camel_case.
This is done so that attributes of the object are more
python-like.
:param word: A string of a word to convert
:type word: string
:return: A string of the converted word from camelCase to camel_case
... |
def edit_string_for_tags(tags):
"""
Given list of ``Tag`` instances, creates a string representation of
the list suitable for editing by the user, such that submitting the
given string representation back without changing it will give the
same list of tags.
Tag names which contain commas will b... |
def to_cuda(*args):
"""Move tensors to GPU device.
"""
return [None if x is None else x.cuda() for x in args] |
def has_form_encoded_header(header_lines):
"""Return if list includes form encoded header"""
for line in header_lines:
if ":" in line:
(header, value) = line.split(":", 1)
if header.lower() == "content-type" \
and "x-www-form-urlencoded" in value:
... |
def fix_month(bib_str: str) -> str:
"""Fixes the string formatting in a bibtex entry"""
return (
bib_str.replace("{Jan}", "jan")
.replace("{jan}", "jan")
.replace("{Feb}", "feb")
.replace("{feb}", "feb")
.replace("{Mar}", "mar")
.replace("{mar}", "mar")
.r... |
def _any(iterable):
"""Same as built-in version of any() except it explicitly checks if an element "is not None"."""
for element in iterable:
if element is not None:
return True
return False |
def binary_search(arr, key):
"""Given a search key, this binary search function checks if a match found
in an array of integer.
Examples:
- binary_search([3, 1, 2], 2) => True
- binary_search([3, 1, 2], 0) => False
Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
Arg... |
def seq_fib(num=6):
"""Stores and reuses calculations to avoid redundancies and time build up.
Args:
num (int): Wanted number from the sequence.
Returns:
fib[num]: Gets the n'th number from storage values.
"""
fib = {}
for k in range(1, num+1):
if k <= 2:
f... |
def isLeapYear(year):
""" Returns True if the year is a Leap Year
else, returns False """
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
return False |
def calc_wait(da, speed):
"""
Given an angular delta and the speed (servo counts), calculate the how long
to wait for the servo to complete the movement
[Join Mode]
0 ~ 1,023(0x3FF) can be used, and the unit is about 0.111rpm.
If it is set to 0, it means the maximum rpm of the motor is used
... |
def base_slots(cls):
"""Return all member descriptors in C and its bases."""
slots = set()
for c in type.mro(cls):
slots.update(getattr(c, '__slots__', ()))
return slots |
def find_min_rotate(array):
"""
Finds the minimum element in a sorted array that has been rotated.
"""
low = 0
high = len(array) - 1
while low < high:
mid = (low + high) // 2
if array[mid] > array[high]:
low = mid + 1
else:
high = mid
return a... |
def parse_file_type(file_type, file_name, output=False, logger=None):
"""Parse the file_type from the file_name if necessary
:param file_type: The input file_type. If None, then parse from file_name's extension.
:param file_name: The filename to use for parsing if necessary.
:param output: Li... |
def divides(a, b):
"""
:param a: A nonzero integer.
:param b: An integer.
:returns: Returns a boolean value indicating whether a divides b.
"""
return b % a == 0 |
def valid_password(password):
"""
The password must be at least nine characters long. Also, it must include
characters from two of:
-alphabetical
-numerical
-punctuation/other
"""
punctuation = set("""!@#$%^&*()_+|~-=\`{}[]:";'<>?,./""")
alpha = False
num = False
punct = False
if l... |
def followers_and_retweets_of_tweet(tweet):
"""
Function that retrieves number of followers of account
that posted tweet and the number of times that tweet was
retweeted
Parameters
----------
tweet: dict
data for individual tweet
Returns
-------
followers: int... |
def prf(correct, pred_sum, gold_sum):
"""
Calculate precision, recall and f1 score
Parameters
----------
correct : int
number of correct predictions
pred_sum : int
number of predictions
gold_sum : int
number of gold answers
Returns
----... |
def ham_dist(bv1, bv2):
"""
returns the hamming distance between two bit vectors
represented as lists
"""
if len(bv1) != len(bv2):
raise Exception("fail: bitvectors of different length "+\
str(len(bv1))+", "+str(len(bv2)))
total = 0
for i, bit in enumerate(bv1... |
def coerce_result(result):
"""
Coerces return value to a tuple if it returned only a single value.
"""
if isinstance(result, tuple):
return result
else:
return (result,) |
def _split_columns(x):
"""Helper function to parse pair of indexes
"""
try:
a, b = map(int, x.split(","))
# columns from command line are numbered starting from 1
# but internally we start counting from 0
return a - 1, b - 1
except ValueError as ex:
message = """ ... |
def binary_transition(transitions, state, symbol):
"""Binary state machine transition computation. Computes next state.
:param transitions: Transition "matrix", in the form of:
{True: state_inverting_symbols, False: state_inverting_symbols}
:param state: Current state. True or False
:param symb... |
def create_phone_number(n):
"""
Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers
in the form of a phone number. The returned format must be correct in order to complete this challenge.
Don't forget the space after the closing parentheses!
... |
def findNubInDict(id, nubDict):
""" Return the named nub, or None if it does not exist. """
return nubDict.get(id, None) |
def inverse_word_map(word_map):
""" Create an inverse word mapping.
:param word_map: word mapping
"""
return {v: k for k, v in word_map.items()} |
def is_digit(str_value: str) -> bool:
"""Checks if a string represents a digit after replacing
thousand and decimal separators"""
return str_value.replace(".", "").replace(",", "").isdigit() |
def count_steps(path):
"""Count the number of replacement steps in a given path
:param path: the path through the CYK table
:return steps: the number of replacement steps
"""
# path is always a branching of the form
# (a, (b, c))
# standing for a => (b, c)
name, result = path
steps ... |
def calculate_label_counts(examples):
"""Assumes that the examples each have ONE label, and not a distribution over labels"""
label_counts = {}
for example in examples:
label = example.label
label_counts[label] = label_counts.get(label, 0) + 1
return label_counts |
def triangle(base, height):
"""Calculate the area of a triangle."""
return base * height / 2 |
def _create_accum_slots(optimizer, var_list, name):
"""Create accumulation slots."""
slots = []
for v in var_list:
s = optimizer._zeros_slot(v, "accum", name) # pylint: disable=protected-access
slots.append(s)
return slots |
def parseBoolValue(value):
"""
Utility function to parse booleans and none from strings
"""
if value == 'false':
return False
elif value == 'true':
return True
elif value == 'none':
return None
else:
return value |
def empty_columns(board):
"""Returns list of "" with length equal to length of expected column.
>>> empty_columns(['***21**', '412453*', '423145*', '*543215', '*35214*',\
'*41532*', '*2*1***'])
['', '', '', '', '', '', '']
"""
columns = []
while len(columns)!= len(board[0]):
columns.app... |
def product_calculator(*args: int) -> int:
"""
Calculates the product of the given inputs.
:param args: A set of input values
:return: The product of the given values
"""
value = 1
for i in args:
value *= i
return value |
def validate_non_humanreadable_buff(data: str, buff_min_size: int = 256, whitespace_ratio: float = 0.10) -> bool:
""" Checks if a buffer is not human readable using the porportion of whitespace
data: the buffer
buff_min_size: minimum buffer size for the test to be meaningful
whitespace_ratio: ratio of ... |
def z_region_pass(region, upper_limit=None, lower_limit=None):
"""return True if extended region [xmin, xmax, ymin, ymax, zmin, zmax] is
within upper and lower z limits
Args:
region (list): a long-region [xmin, xmax, ymin, ymax, zmin, zmax]
upper_limit (float): the z-max
lower_limit ... |
def limit(q, lim):
"""Non-MS SQL Server implementation of 'limit'"""
return "SELECT sq.* FROM ({}) sq LIMIT {}".format(q, lim) |
def addelems(list1, list2):
"""
Adds list1 and list2 element wise. Summands may contain None, which are ignored.
:type list1: list
:param list1: First summand
:type list2: list
:param list2: Second summand
:return: list
"""
# Make sure the lists are of the same length
assert len(... |
def can_move(index, state, zero_index):
"""Check whether the empty sign could be moved."""
if index < 0:
return state[zero_index + index] == 1 and zero_index + index > -1
return zero_index + index < len(state) and state[zero_index + index] == 2 |
def reduction(op, elements, accumulator):
""" Combines a list of elements into one using an accumulator. Returns the final state of the accumulator.
----------
op : Operation to apply to each element and the accumulator. Must be associative and distributive.
elements : List of elements.
accumulator ... |
def merge_blocks(ivs, dist=0):
""" Merge blocks
Args:
ivs (list): List of intervals. Each interval is represented by a tuple of
integers (start, end) where end > start.
dist (int): Distance between intervals to be merged. Setting dist=1 will merge
adjacent intervals
... |
def compile_per_chrom(hbar_list):
"""Return [{chr: upper: lower:}]"""
if hbar_list == []:
return []
mylist = []
comp = {"chr": None , "xranges":[], "upper":[], "lower":[]}
mylist.append(comp)
for i in hbar_list:
# same chromosome, add to lists
if mylist[-1]['chr'] is No... |
def get_recursively(search_dict, field):
"""Takes a dict with nested dicts, and searches all dicts for a key of the
field provided."""
fields_found = []
for key, value in search_dict.items():
if key == field:
fields_found.append(value)
elif isinstance(value, dict):
... |
def parse_method_path(method_path):
""" Returns (package, service, method) tuple from parsing method path """
# unpack method path based on "/{package}.{service}/{method}"
# first remove leading "/" as unnecessary
package_service, method_name = method_path.lstrip("/").rsplit("/", 1)
# {package} is ... |
def dot(x, y):
"""
Dot product as sum of list comprehension doing element-wise multiplication
"""
return (sum(x_i * y_i for x_i, y_i in zip(x, y))) |
def get_sbo_int( miriam_urns):
""" takes a list of miriam encoded urn, e.g. ['urn:miriam:GO:0016579', 'urn:miriam:SBO:0000330']
and returns the integers [330] """
return [ int( i[15:]) for i in miriam_urns if i.startswith( "urn:miriam:SBO:")] |
def count_punkt(list_of_lists_of_tokens, punkt_list=[]):
"""
Return count of "meaningful" punctuation symbols in each text
Parameters
----------
- list_of_lists_of_tokens : dataframe column whose cells contain lists of words/tokens (one list for each sentence making up the cell text)
- pun... |
def replace(key: str, value: str, line: str) -> str:
""" Replaces a key with a value in a line if it is not in a string or a comment and is a whole
word.
Complexity is pretty bad, so might take a while if the line is vvveeeerrrrryyyyyy long.
"""
i = 0
in_string = False
in_comment = Fals... |
def color_blend(a, b):
"""Performs a Screen blend on RGB color tuples, a and b"""
return (255 - (((255 - a[0]) * (255 - b[0])) >> 8), 255 - (((255 - a[1]) * (255 - b[1])) >> 8), 255 - (((255 - a[2]) * (255 - b[2])) >> 8)) |
def starts2dshape(starts):
"""
Given starts of tiles, deduce the shape of the decomposition from them.
Args:
starts (list of ints)
Return:
tuple: shape of the decomposition
"""
ncols = 1
for start in starts[1:]:
if start[1] == 0:
break
ncols += 1... |
def ease_in_out_cubic(n):
"""
:param float n: 0-1
:return: Tweened value
"""
n *= 2
if n < 1:
return 0.5 * n**3
else:
n -= 2
return 0.5 * (n**3 + 2) |
def _str2bool(s):
"""Convert string to boolean."""
return s.lower() in ("true", "t", "yes", "y", "1") |
def find_number_of_digits(number):
"""
it takes number as input, then finds number_of_digits.
"""
number_of_digits = 0
while (number > 0):
number_of_digits+=1
number //= 10
return number_of_digits |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.