content stringlengths 42 6.51k |
|---|
def is_not_blank(in_string):
"""Test if a string is not None NOR empty NOR blank."""
return bool(in_string and in_string.strip()) |
def byte_to_gigabyte(byte):
"""
Convert byte value to gigabyte
"""
return byte / (1024.0 ** 3) |
def set_bits(n, start, end, value):
"""Set bits [<start>:<end>] of <n> to <value> and return <n>"""
mask = ( 1 << end ) - ( 1 << start )
return (int(n) & ~mask) | (int(value) << start) & mask |
def Iq(q, peak_pos, peak_hwhm):
"""
Return I(q)
"""
inten = (1/(1+((q-peak_pos)/peak_hwhm)**2))
return inten |
def generate_combined_lulc(in_lucode, transition_code, activity_id, out_lucode):
"""Create a consistent lucode id based on the in, transition, and out
in_lucode - an integer < 999
transition_code - an integer < 9
activity_id - an integer < 99
out_lucode - an integer < 999
r... |
def contar_elementos(lista: list, elemento) -> int:
"""Cuenta la cantidad de letras especificas en un elemento
Argumentos:
lista (list) -- ...
elemento -- ...
"""
cuenta = 0
for e in lista:
if e == elemento:
cuenta += 1
return cuenta |
def into_keywords_format(keywords: dict) -> list:
"""Convert a dictionary of keyword, counter pairs into a list of dicts.
Args:
keywords: A dictionary that contains a counter for every keyword.
Returns:
The keywords in the format specified in wrapper/output_format.py.
"""
keywords_... |
def get_connection_retry_time(time: int) -> int:
"""Returns time to wait for connection retry
Args:
time (int): current retry wait time
Returns:
int: next retry wait time
"""
return time if (time == 16) else time * 2 |
def format_package_data(package_data):
"""Return formatted package"""
fmtd = {
'package': '{type} {name}',
'archive': '{type} {hash} [{name}]',
}
return fmtd[package_data['type']].format(**package_data) |
def get_list_of_list(list_of_thresholds):
"""
This function take the list of the argument thresholds, extract the value and create a list of list
"""
extract_thresholds = [float(list_of_thresholds[i]) for i in range(0,len(list_of_thresholds))]
n = 2
def chunks(l, n):
# For item i in ... |
def ack(m, n):
"""Computes the Ackermann function A(m,n).
Args:
m, n: non-negative integers.
"""
if m == 0:
return n + 1
if n == 0:
return ack(m - 1, 1)
return ack(m - 1, ack(m, n - 1)) |
def ensure_list(list_or_scalar):
"""Convert the input to a list if it is not."""
if isinstance(list_or_scalar, list):
return list_or_scalar
return [list_or_scalar] |
def union(a, b):
"""
returns the sum of both lists without duplicates
"""
if a is None:
return b
if b is None:
return a
return set(a | b) |
def y_is_in_circle(x, y):
"""Test if x,y coordinate lives within the radius of the unit circle"""
return x * x + y * y <= 1.0 |
def getMatching(token, toQuery):
"""use the token to search a list of strings, return all matching token
Args:
token (string): "l0"
toQuery (list): of strings to check
Returns:
list: of matchings strings
"""
matching = [q for q in toQuery
if token.lower() in... |
def _compile_unit(i):
"""Append gas to unit and update CO2e for pint/iam-unit compatibility"""
if " equivalent" in i["unit"]:
return i["unit"].replace("CO2 equivalent", "CO2e")
if i["unit"] in ["kt", "t"]:
return " ".join([i["unit"], i["gas"]])
else:
return i["unit"] |
def lists_overlap(sub, main):
"""Check whether lists overlap."""
for i in sub:
if i in main:
return True
return False |
def toDD(n):
"""Takes an integer and returns a string of length 2 corresponding to it"""
if n // 10 > 0:
return str(n)
else:
return "0" + str(n) |
def partition_list(items, split_on):
"""
Partition a list of items.
Works similarly to str.partition
Args:
items:
split_on callable:
Should return a boolean. Each item will be passed to
this callable in succession, and partitions will be
created any ... |
def is_between_strict(lo, val, hi) -> bool:
"""Shorthand for `(lo < val < hi) or (lo > val > hi)`."""
return (lo < val < hi) or (lo > val > hi) |
def format_arguments(arguments):
"""Returns numerical arguments as int type, or None if not set."""
formated_arguments = []
for argument in arguments:
if argument:
argument = int(argument)
formated_arguments.append(argument)
return formated_arguments |
def basic_feature(basic_geometry):
"""
Returns
-------
dict: GeoJSON object.
Coordinates are in grid coordinates (Affine.identity()).
"""
return {
'geometry': basic_geometry,
'properties': {
'val': 15
},
'type': 'Feature'
} |
def slice_arg(s):
"""
Parse a string that describes a slice with start and end.
>>> slice_arg('2:-3')
slice(2, -3, None)
>> slice_arg(':-3')
slice(None, -3, None)
>> slice_arg('2:')
slice(2, None, None)
"""
start, end = s.split(':')
start = None if start == '' else int(st... |
def filter_out_unicode(x):
"""
Pass in a list of (authors, hashtags) and return a list of hashtags that are not unicode
"""
hashtags = []
for hashtag in x[1]:
try:
hashtags.append(str(hashtag))
except UnicodeEncodeError:
pass
return (x[0], hashtags) |
def indexOfSmallestInt(listOfInts):
"""
return index of smallest element of non-empty list of ints, or False otherwise
That is, return False if parameter is an empty list, or not a list
parameter is not a list consisting only of ints
By "smallest", we mean a value that is no larger than any other
... |
def kl_divergence(log_a, log_b):
"""Kullback-Leibler divergence
- Source: https://www.tensorflow.org/api_docs/python/tf/keras/losses/KLD
"""
return log_a * (log_a - log_b) |
def cleanup_text(text: str):
"""
strips whitespace
:param text:
:return:
"""
if not text:
return text
text = text.strip()
return text |
def verify_complexity(complexity_data):
""" return True if complexity structure is valid, False otherwise
"""
if complexity_data['average'] is None:
return False
if complexity_data['highest']['name'] is None:
return False
return True |
def _kernel_seq(inputs, estimator):
"""
Wrapper around a function that computes anything on two sequences and returns a dict
While it is written as a general purpose kernel for anything, here it is used for
causal discovery and estimation from CCM based methods.
The function unpacks inputs into an... |
def match_mygene(text):
"""
Returns true if text matches NCBI protein sequences
"""
pieces = text.split(":")
cond = len(pieces) == 2
return cond |
def clean_name(name):
""" Cleans the name by removing spaces and adding .ttf to the end """
EXTENSION = '.ttf'
return name.replace(' ', '') + EXTENSION |
def user_name_for(name):
""" Returns a "user-friendly" version of a string, with the first letter
capitalized and with underscore characters replaced by spaces. For example,
``user_name_for('user_name_for')`` returns ``'User name for'``.
"""
name = name.replace("_", " ")
result = ""
last_low... |
def make_set(start_coordinate, length):
"""Compute the set the coordinate values a rectangles takes on an axis."""
end_coordinate = start_coordinate + length
return set(range(start_coordinate, end_coordinate + 1)) |
def xor(*args):
"""
Implements logical xor function for arbitrary number of inputs.
Parameters
----------
args : bool-likes
All the boolean (or boolean-like) objects to be checked for xor
satisfaction.
Returns
-------
output : bool
True if and only if one and on... |
def insert_spaces_back(text, indices):
"""
Given text and a list of indices, insert spaces at those indices
Example: insert_spaces_back("HELLOWORLD", [0, 4])
@param text is the text you are inserting spaces into
@param indices is the integer list of indices of spaces
@returns the formatted stri... |
def scrap(consensus, end_of_field):
"""
Consume lines upon matching a criterion.
Returns (consensus-without-first-line, first-line)
if end_of_field(first-line) returns True,
else returns (consensus-with-first-line, None)
:param bytes consensus: input which first lin... |
def strip_specific_magics(source, magic):
"""
Given the source of a cell, filter out specific cell and line magics.
"""
filtered=[]
for line in source.splitlines():
if line.startswith(f'%{magic}'):
filtered.append(line.lstrip(f'%{magic}').strip(' '))
if line.startswith(f'... |
def toflt(lst):
"""Makes all values of a list into floats"""
return [float(i) for i in list(lst)] |
def format_data_types(s):
"""
apply the correct data type to each value in the list created from a comma
separated sting "s"
x1: PDB ID (string)
x2: Macro molecule overlaps (int)
x3: Symmetry overlaps (int)
x4: All overlaps (int)
x5: Macro molecule overlaps per 1000 atoms (float)
x6: Symmetry overlap... |
def bit_indices(v):
"""Return list of indices where bits are set, 0 being the index of the least significant bit.
>>> bit_indices(0b101)
[0, 2]
"""
return [i for i, b in enumerate(bin(v)[::-1]) if b == "1"] |
def numbers_to_string(numbers):
"""
Convert a list of numbers to a string
:param numbers: Message as numbers
:return: Message as string
"""
val = ''.join(chr(n) for n in numbers)
return val |
def is_divisible(i, args):
"""Returns True if i is divisible by any element of args"""
return any(i % a == 0 for a in args) |
def triangles(creation_sequence):
"""
Compute number of triangles in the threshold graph with the
given creation sequence.
"""
# shortcut algorithm that doesn't require computing number
# of triangles at each node.
cs = creation_sequence # alias
dr = cs.count("d") # number of d... |
def convert_to_fortran_string(string):
"""
converts some parameter strings to the format for the inpgen
:param string: some string
:returns: string in right format (extra "")
"""
new_string = '"' + string + '"'
return new_string |
def _fix_absolute_import_name(absolute_import_name: str) -> str:
"""Replaces all the forward slashes and colons in an absolute import name
with underscores. This is for conforming to restrictions of Cloud Scheduler
job names."""
return absolute_import_name.replace('/', '_').replace(':', '_') |
def get_partition(string_):
"""
Return the partition portion of a device name (mount style, or udisksctl style).
:param string_:
:return:
"""
if "block_devices/" in string_:
return string_[len("block_devices/"):]
elif "/dev/" in string_:
return string_[len("/dev/"):]
els... |
def search_list_for_str(lst, search_string, starting_item, down, case_insensitive):
"""returns index into list representing string found, or None if not found"""
search_string = search_string.lower() if case_insensitive else search_string
search_slice_end = len(lst) if down else 0
search_list = lst[star... |
def pie_percent(n: int) -> int:
"""Precondition: n > 0
Assuming there are n people who want to eat a pie, return the percentage
of the pie that each person gets to eat.
>>> pie_percent(5)
20
>>> pie_percent(2)
50
>>> pie_percent(1)
100
"""
return int(100 / n) |
def few_enough_underscores(current: str, match: str) -> bool:
"""Returns whether match should be shown based on current
if current is _, True if match starts with 0 or 1 underscore
if current is __, True regardless of match
otherwise True if match does not start with any underscore
"""
if curre... |
def get_internal_ip_from_get_node(node_info):
"""
Retrieves the InternalIp returned by kubectl get no -o json
"""
for status_addresses in node_info['status']['addresses']:
if status_addresses["type"] == "InternalIP":
return status_addresses["address"] |
def convert_variable(datatype, variable):
"""
Convert variable to number (float/int)
Used for dataset metadata and for query string
:param datatype: type to convert to
:param variable: value of variable
:return: converted variable
:raises: ValueError
"""
try:
if variable and ... |
def binarize(x, threshold):
"""
Binarize the output of a sigmoid to be either +1 or -1
if output is gte threshold.
"""
return 1. if x >= threshold else -1. |
def can_skip(entry, skip) -> bool:
"""Return True if at least one variable matches"""
ret = False
for val in skip:
if val["name"] in entry and entry[val["name"]] == val["value"]:
ret = True
break
if val["value"] == "" and val["name"] not in entry:
ret = T... |
def calcContactFrac(n, **kwargs):
"""Return the proportion of contact for a n-residue protein.
This proportion is utilized in the DICOV as the prior probability of 3D
contact, P(+), by a regression analysis of a training set of 162 structurally
known protein sequences.
[MW15] Mao W, Kaya C, Dutta A... |
def filter_text(text, filters):
"""Run `text` through a series of filters.
`filters` is a list of functions. Each takes a string and returns a
string. Each is run in turn.
Returns: the final string that results after all of the filters have
run.
"""
clean_text = text.rstrip()
ending ... |
def _add_entry_attr(
ctx,
arguments,
argument_name,
universal_entry_value = None):
"""Using a priority scheme, adds the entry point to the 'arguments'.
The entry point value can come from three location:
local - argument list (highest priority)
global - the rule'... |
def dot(a: complex, b: complex) -> complex:
"""Inner product of two vectors.
Args:
a (complex): First vector.
b (complex): Second vector.
Returns:
complex: Inner product: a.x * b.x + a.y * b.y
"""
return (a.conjugate() * b).real |
def parse_api_error(response):
"""
Parse the error-message from the API Response.
Assumes, that a check if there is an error present was done beforehand.
:param response: Dict of the request response ([imdata][0][....])
:type response: ``dict``
:returns: Parsed Error-Text
:rtype: ``str``
... |
def translate_underscore(string, lower=False):
"""
Replaces the underscore HTML idiom <sub>—</sub> with the literal
underscore character _.
"""
if lower:
string = string.lower()
return string.replace('<sub>—</sub>','_').replace('<sub>-</sub>','_').replace(u'<sub>\u2014</sub... |
def human_time(milliseconds):
"""Take a timsetamp in milliseconds and convert it into the familiar
minutes:seconds format.
Args:
milliseconds: time expressed in milliseconds
Returns:
str, time in the minutes:seconds format
For example:
"""
milliseconds = int(milliseconds)
... |
def local_rig_path(msg):
"""Gets local path of the rig.
Args:
msg (dict[str, str]): Message received from RabbitMQ publisher.
Returns:
str: Path to local rig.
"""
return msg["rig"] |
def contains_ingredients(ing, check_ing):
"""
IMPORTANT: You should NOT use loops or list comprehensions for this question.
Instead, use lambda functions, map, and/or filter.
Take a 2D list of ingredients you have and a list of pancake ingredients.
Return a 2D list where each list only contai... |
def _add_missing_parameters(flattened_params_dict):
"""Add the standard etl parameters if they are missing."""
standard_params = ['ferc1_years',
'eia923_years',
'eia860_years',
'epacems_years',
'epacems_states']
for ... |
def select_by_year(year, D):
"""Select year from specification given in dictionary or list of ranges.
Examples:
>>> spec = {(..., 1990): 'foo',
... 1991: 'bar',
... (1992, 2000): 'foobar',
... (2001, ...): 'blah'}
>>> select_by_year(1990, sp... |
def regla_trapecio_iterativa(f, i, r_im1, lim):
""" Funcion para ejecutar la regla del trapecio.
Esta funcion trata de ejecutar la regla del trapecio mediante
un acercamiento iterativo. Regresara el valor calculado, con
la condicion de termino i == 0 donde no se llamara a si misma
de nuevo.
... |
def factorial(num):
"""Finds the factorial of the input integer.
:arg num: an integer
"""
#If the number provided is zero then the factorial is 1
if num == 0:
fact = 1
#Otherwise set fact to 1 and begin finding the factorial r is
#used to find each num-n for n=0 to n=num each v... |
def flatten_dict(d):
"""Flatten a dictionary where values may be other dictionaries
The dictionary returned will have keys created by joining higher- to lower-level keys with dots. e.g. if the original dict d is
{'a': {'x':3, 'y':4}, 'b':{'z':5}, 'c':{} }
then the dict returned will be
{'a.x':3, 'a... |
def reverse(moves: list) -> list:
"""Return list of reversed moves."""
reverse = []
for move in moves[::-1]:
if move.endswith("'"):
reverse.append(move[:-1])
elif move.endswith('2'):
reverse.append(move)
else:
reverse.append(move + "'")
... |
def get(self, key, default=None):
"""
return ``default`` if ``key`` is not in self, else the value associated with ``key``
"""
try:
return self[key]
except KeyError:
return default |
def quoteWindows(args):
"""
Given a list of command line arguments, quote them so they can be can be
printed in Windows CLI
"""
def q(x):
if " " in x:
return '"' + x + '"'
else:
return x
return [q(x) for x in args] |
def lchop(s, sub):
"""Chop ``sub`` off the front of ``s`` if present.
>>> lchop("##This is a comment.##", "##")
'This is a comment.##'
The difference between ``lchop`` and ``s.lstrip`` is that ``lchop`` strips
only the exact prefix, while ``s.lstrip`` treats the argument as a set of
leading ch... |
def interpret_config_value(value_str):
""" Determine the data type from the input string and convert.
Conversions:
'True', 'Yes' --> True
'False', 'No' --> False
Starting and ending with ' or " --> string
If can be converted to int, float or complex --> converted numeric valu... |
def split_up_threadwork(total_threads, thread_number, num_iterations):
"""
Splits up a specified number of iterations into approximately equal workloads for multiple threads to work on.
:param total_threads:
:param thread_number:
:param num_iterations:
:return: the iteration numbers that the spe... |
def status_comparison(past, present):
"""status compares with past and present
this function calls if valid cache exists
Args:
past (int): past analyze status (should be 3xx)
present (int): present analyze status
Returns:
cacheable (boolean): cache is able to make or not
... |
def str2bool(v):
"""
argparse does not support True or False in python
"""
return v.lower() in ("true", "t", "1") |
def _inflate_dotted(input_dict):
"""Convert flat dict with dotted key notation into nested dict.
Given a flat dict with dotted keys for nested items, e.g.
>>> input_dict = {'spam.eggs': 23, 'answer': 42}
create a nested dict
>>> output_dict = _inflate_dotted(input_dict)
>>> output_... |
def pretty_frame_name(frame_name):
"""omit some stdc++ stacks"""
pretty_names = (
('std::__invoke_impl', ''),
('std::__invoke', ''),
('std::_Bind', ''),
('Runnable::operator()', ''),
('std::thread::_Invoker', ''),
('std::thread::_State_impl', 'std::thread'),
('std::this_thread::sleep_for... |
def get_unique_tuples(x):
"""Get unique 2-tuples, ignoring order, from the list `x`."""
unique_tuples = \
list(frozenset([tuple(sorted((o1, o2))) for o1 in x
for o2 in x if o1 is not o2]))
return unique_tuples |
def lambda_handler(event, context):
"""Handle the lambda event."""
return {
"statusCode": 200,
"body": "Thank you for using my API",
"headers": {
'Content-Type': 'text/html',
}
} |
def in_order(tree):
"""
Function to which performs inorder for a tree iteratively.
Parameters:
tree (BinTreeNode) ; the tree for which inorder is to be performed.
Returns:
sortedArr (list); list of all elements in ascending order.
"""
sortedArr = []
current... |
def compute_q10_correction(q10, T1, T2):
"""Compute the Q10 temperature coefficient.
As explained in [1]_, the time course of voltage clamp recordings are
strongly affected by temperature: the rates of activation and inactivation
increase with increasing temperature. The :math:`Q_{10}` temperature
... |
def get_rate(relSeas_peak, relSeas_edge, period):
""" Calculate onset/decline rate of event
"""
return (relSeas_peak - relSeas_edge) / period |
def banr(registers, opcodes):
"""banr (bitwise AND register) stores into register C the
result of the bitwise AND of register A and register B."""
test_result = registers[opcodes[1]] & registers[opcodes[2]]
return test_result |
def delete_cookie(cookieName: str, url: str) -> dict:
"""Deletes browser cookie with given name, domain and path.
Parameters
----------
cookieName: str
Name of the cookie to remove.
url: str
URL to match cooke domain and path.
**Experimental**
"""
return {
... |
def split_data_to_chunks(data: list, max_chunk_size: int, overlapping_size: int):
"""
Because GP can take very long to finish, we split data into smaller chunks and train/predict these chunks separately
:param data:
:param max_chunk_size:
:param overlapping_size:
:return: list of split data
... |
def left_part_of(txt, sub_txt, n=1):
"""
Return the left part before the nth of sub_txt appeared in txt.
:param txt: text
:param sub_txt: separate text
:param n: the nth of sub_txt(default:1)
"""
parts = txt.split(sub_txt)
return sub_txt.join(parts[:n]) |
def _percent_completion_for_module(module_data: dict) -> int:
"""Produce a rough, integer-rounded completion percentage for the
given module."""
try:
pc = module_data['completion_count'] / module_data['total_pages'] * 100
return round(pc)
except (KeyError, ZeroDivisionError):
pa... |
def get_bq_name(mongo_field):
"""Given a mongo field name, make one bigquery is happy with"""
return ''.join([ch for ch in mongo_field if ch.isalnum() or ch == '_']) |
def convertBytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def get_reviewers_ids(reviews_list):
""" Extracts reviewer names from all reviews """
reviewers_ids=[review['reviewer'] for review in reviews_list if review['reviewer'] is not None]
return reviewers_ids |
def L_adiab(t, t_ref, L_ref, gamma):
"""
Returns the adiabatic (Sedov-Taylor) evolution of the SNR radio spectral luminosity [erg * s^-1 * Hz^-1] as a function of time after explosion [years] and frequency [GHz]. NOTE: frequency dependence prefactor, usually (nu/nu_pivot)^-alpha, is factorized out.
Paramet... |
def est_majeure(p):
"""Personne -> bool
renvoie True si la personne est majeure, ou False sinon."""
nom, pre, age, mar = p
return age >= 18 |
def get_file_ext(filename):
""" Get extension of a file """
return filename.rsplit('.', 1)[1] |
def time_of_day(hour, minute, second):
"""Return the time of day data structure."""
return [hour, minute, second] |
def _fuse(mol1, mol2, w=1):
"""
Fuse 2 dicts representing molecules. Return a new dict.
This fusion does not follow the laws of physics.
"""
return {atom: (mol1.get(atom, 0) + mol2.get(atom, 0)) * w for atom in set(mol1) | set(mol2)} |
def isnumber(obj):
"""
Test if the argument is a number (complex, float or integer).
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float, complex))
) |
def flatt_on_level(it, d=-1, level=None):
"""
>>> list(flatt_on_level([[[['a']]]], level=3))
[['a']]
"""
if d == -1:
return list(flatt_on_level(it, d=d + 1, level=level))
if d == level:
return (i for i in [it])
res = []
for x in it:
res.extend( flatt_on_level(x... |
def bori(registers, opcodes):
"""bori (bitwise OR immediate) stores into register C the
result of the bitwise OR of register A and value B."""
test_result = registers[opcodes[1]] | opcodes[2]
return test_result |
def parse_input(text):
"""Meh
>>> parse_input(EXAMPLE)
({'class': [(0, 1), (4, 19)], 'row': [(0, 5), (8, 19)], 'seat': [(0, 13), (16, 19)]}, [11, 12, 13], [[3, 9, 18], [15, 1, 5], [5, 14, 9]])
"""
rules = {}
myticket = []
nearbytickets = []
mode = "rules"
for line in text.strip().spl... |
def simple_tokenize(sent):
""" Tokenize but add spaces around the commmas."""
comma_sep_parts = [p.strip() for p in sent.split(",")]
return " , ".join(comma_sep_parts).split(" ") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.