content stringlengths 42 6.51k |
|---|
def flatten_list(lst):
"""
this is the fastest
"""
out = []
for sublist in lst:
out.extend(sublist)
return out |
def join_sequence_of_dicts(seq):
"""
Joins a sequence of dicts into a single dict
Parameters
----------
seq: sequence
Sequence of dicts to join
Returns
-------
dict
Raises
------
RuntimeError if a duplicate key is encountered.
"""
r = {}
for d in seq:
... |
def _is_variable_argument(argument_name):
"""Return True if the argument is a runtime variable, and False otherwise."""
return argument_name.startswith('$') |
def rem_file_ext(filename):
"""Returns the filename without extension."""
pos = filename.rfind('.')
if pos > -1:
return filename[:pos]
else:
return filename |
def tarjan_scc(graph):
"""
Tarjan's partitioning algorithm for finding strongly connected components in a graph.
"""
index_counter = [0]
stack = []
lowlinks = {}
index = {}
result = []
def strongconnect(node):
index[node] = index_counter[0]
lowlinks[node] = index_co... |
def compare_dict(lhs, rhs):
"""Implements dictionary comparison for Python 2 and 3 alike"""
lhs_sorted = sorted(lhs, key=lambda x:sorted(x.keys()))
rhs_sorted = sorted(rhs, key=lambda x:sorted(x.keys()))
return (lhs_sorted > rhs_sorted) - (lhs_sorted < rhs_sorted) |
def UrlEscape(url):
"""Scapes XML entities.
Args:
url: potentially with XML invalid characters.
Returns:
same URL after replacing those with XML entities.
"""
return url.replace("'", "'").replace("'", """) |
def format_hex(hex_num, num_digits):
"""Formats hex numbers with set number of digits and upper case letters"""
return "{0:#0{1}X}".format(hex_num, num_digits + 2) |
def substr_surrounded_by_chars(full_str, char_pair, offset=0):
"""
Extract substring surrounded by open & close chars.
For example, 'value: { k1: v1, k2: v2 }'
:param full_str: target string.
:param char_pair: a tuple contains open & close tag.
:param offset: Start point to search substring.
... |
def model_potentialtranspiration(evapoTranspiration = 830.958,
tau = 0.9983):
"""
- Name: PotentialTranspiration -Version: 1.0, -Time step: 1
- Description:
* Title: PotentialTranspiration Model
* Author: Pierre Martre
* Reference: Modelling ener... |
def non_basemap_layers(layers):
"""Retrieve all map layers which are not basemaps"""
return [layer for layer in layers if not layer.is_basemap] |
def interp(start, end, frac):
"""2D linear interpolation"""
# diff = end - start
# return start + (frac * diff)
diff = (end[0] - start[0], end[1] - start[1])
return (
start[0] + frac * diff[0],
start[1] + frac * diff[1]) |
def get_login_post_result_form(uuid):
"""
Assemble form for get_login_post_result
:param uuid: UUID from get_login_result
:return: Form in dict
"""
post_data_dict = dict()
post_data_dict['act'] = '2'
post_data_dict['ret'] = '0'
post_data_dict['message'] = ""
post_data_dict['uid']... |
def update_sequence(s, n, x):
"""Return a tuple copy of s with the nth element replaced by x."""
t = tuple(s)
if -len(t) <= n < len(t):
return t[0:n] + (x,) + t[n + 1 : 0 if n == -1 else None]
else:
raise IndexError("sequence index out of range") |
def add_brackets_around_string(word: str):
"""Adds square brackets for single character strings and round the rest.
"""
if len(word) == 1 or (len(word) == 2 and word.startswith('\\')):
return word
return '(?:' + word + ')' |
def check_user_sync_agent_type(json):
"""
Check type of incoming user statement.
:param json: A user statement.
:type json: dict(str, NoneType)
:return: The type of the verb of the statement.
:rtype: str
"""
obj_type = json['statement']['verb']['display']['en']
return obj_type |
def find_not_in_icd_set(lenoforginalset, numbers_set):
"""This function will find all the icd codes (represented as numbers) not in a given set."""
originalset = [str(i) for i in range(1, lenoforginalset+1, 1)]
numbers_not_in_set = list(set(originalset)-set(numbers_set))
numbers_not_in_set = sorte... |
def __copy__(self) :
"""Return a copy of self"""
return type(self)(self); |
def formatsource(value, endangerment=False):
"""
>>> formatsource({'bibfile': 'hh', 'bibkey': '23'})
'**hh:23**'
>>> formatsource({'bibfile': 'hh', 'bibkey': '23', 'pages': '1-23'})
'**hh:23**:1-23'
>>> formatsource({'bibfile': 'hh', 'bibkey': '23',
... 'pages': '1-23', 'tri... |
def precision(overlap_count, guess_count):
"""Compute the precision in a zero safe way.
:param overlap_count: `int` The number of true positives.
:param guess_count: `int` The number of predicted positives (tp + fp)
:returns: `float` The precision.
"""
if guess_count == 0: return 0.0
retur... |
def flatten(x):
"""Returns the flattened list or tuple."""
if len(x) == 0:
return x
if isinstance(x[0], list) or isinstance(x[0], tuple):
return flatten(x[0]) + flatten(x[1:])
return x[:1] + flatten(x[1:]) |
def _fix_unicode(text):
"""Convert a partial unicode string to full unicode"""
return text.encode('utf-8', 'surrogateescape').decode('utf-8') |
def rgb_to_hex(r, g, b):
"""Turn an RGB float tuple into a hex code.
Args:
r (float): R value
g (float): G value
b (float): B value
Returns:
str: A hex code (no #)
"""
r_int = round((r + 1.0) / 2 * 255)
g_int = round((g + 1.0) / 2 * 255)
b_int = round((b + 1... |
def hard(first, *args, x, **kwargs):
"""A harder test of how command-line args are mapped to parameters."""
return first, args, x, sorted(kwargs.items()) |
def _get_limit(order_field, start=None, end=None):
""" Produces a SQL condition the order_filed to be between start and end."""
query = ""
if start is None and end is None:
return None
if start:
query+="{0}>={1}".format(order_field, start)
if end:
if start:
q... |
def check_lenght_message_complete_with_dont_care(message,fixed_lenght = 245):
"""
This function check the lenght a message(bytes), and if the lengh it's not equal to fixed_lenght,the
message it's modified, append 'X' character, until have the specific lenght
@param message: (bytes) bytes coded at utf-8
@param fi... |
def gentaglist(sublist, checkname, hostname):
"""Generate a tag list for passing to tag checking."""
# Constants
taglist = ["all"]
# remove domain names from hostname
hostname = hostname.split('.')[0]
# Build our taglist
taglist += sublist
taglist.append(hostname)
taglist.append(chec... |
def filter_ending(registration_number: str, items: list):
"""
Get a subset of the provided list that excludes items that were not removed for the specified registration number
:param registration_number: The registration number to filter out items for
:param items: A list of items to be filtered. Must ... |
def validate_domain_to_record(domain):
"""
remove TLD part of validate domain record
Args:
domain: validate domain(include _acme-challenge.[input_domain]
Returns:
_acme-challenge.[input_domain_without_TLD]
"""
domain_list = domain.split('.')[:-2]
if len(domain_list) > 0 and d... |
def luhn(card):
""" Credit Card Validator with Mod 10, or Luhn algorithm
refering to it's creator 'Hans Peter Luhn' """
# return sum(map(int, str(card)[1::2]+str(card)[0::2]*2))%10==0
card=str(card).replace(' ','')
return (sum(map(int, str(card)[1::2])) + \
sum(sum(map(int, str(i*2))) fo... |
def to_text(string):
"""Ensure that the string is text."""
if callable(getattr(string, 'decode', None)):
return string.decode('utf-8')
return string |
def coding_problem_49(arr):
"""
Given an array of numbers, find the maximum sum of any contiguous subarray of the array.
For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements
42, 14, -5, and 86. Given the array [-5, -1, -8, -9], the maximum su... |
def compare_integers(first, second):
"""
Returns the greater of the two integers
:param first:
:param second:
:return: int
"""
return max(int(first), int(second)) |
def in_percent(value, total, round_at=2):
"""
given input in percent and round to given value
:param value: number of some ratings
:param total: total number of all ratings
:param round_at: value to round at
:return: float: rounded value in percent
"""
return round((value / total) * 100, round_at) |
def filter_not_none(iterable):
"""Filter out None values in given iterable collection.
Parameters
----------
iterable : collections.Iterable
The iterable collection to be filtered.
Returns
-------
list
Returns the list of non-None elements.
"""
return [i for i in it... |
def escape_cdata(cdata):
"""Escape a string for an XML CDATA section"""
return cdata.replace(']]>', ']]>]]><![CDATA[') |
def reverse_json_ambi(
json_ambi: dict,
ids: set) -> dict:
"""
Reverse a dict (values as keys, keys as list values).
Parameters
----------
json_ambi : dict
A dict having one string value per key.
ids : set
sample IDs from the biom table.
Returns
-------
... |
def __pair_maximizer(alpha_pairs, pair):
"""
Helping method, maximizing pairs
"""
for alt in alpha_pairs:
if pair != alt and pair[0].issubset(alt[0]) and pair[1].issubset(alt[1]):
return False
return True |
def string_concatenator(string1, string2):
"""Combines strings together by adding them and returning the combination as an output.
Parameters
----------
string1 : string
String that will be added to another string.
string2 : string
String that will be added to anot... |
def get_full_tag(repository, target, version_tag, os_tag):
""" Constructs a tag, excluding the OS_TAG if it is empty.
Additionally ignores the target when it is the default target "kudu".
Examples:
get_tag "kudu" "latest" "" = apache/kudu:latest
get_tag "base" "1.8.0" "" = a... |
def binaryPlusOne(operand):
"""
Adds 1 to the binary string operand.
No safety,i.e.: operand is assumed to be a string, with only binary content 9i.e.: 0s or 1s),
however a string may be returened only if it has the same length as operand.
"""
#print(str(operand))
length = len(o... |
def element_product(x):
""" Return the product of all the element in list x
Parameters
----------
x (list): list of int numbers
Return
------
product (float): the greatest product of size n """
if not x:
return None
if 0 in x:
return 0
product = 1
for ele... |
def get_parameters_options(tuple_options):
"""
:param tuple_options: List of tuples of option name and value
:return: Dictionary of parameters key and value
:rtype: dict
"""
return {k: v for k, v in tuple_options if v is not None} |
def remove_duplicates(nonunique):
"""Remove duplicate values in a list.
Args:
nonunique (list) - a list of values
Returns:
a list of the unique values in the nonunique list
Example:
unique_values(['a', 'a', 'b', 'c']) --> ['a', 'b', 'c']
"""
un... |
def read_template_source(filename):
"""Read the source of a RiveScript template, returning the Unicode text."""
try: # v0.2.0: Issue #3
with open(filename, 'r', encoding='utf-8') as f:
text = f.read()
except Exception: # v0.2.0: Issue #3
text = '' ... |
def is_a_match(input_string, guess_word):
"""
input_string: string, the user input to be spellchecked
guess_word: string, the word from the wordlist to be checked against input_string
returns: bool, True if every letter in guess_word is in input_string in order with
double characters being given for... |
def hasmethod(obj, method_name):
"""Return True if obj.method_name exists and is callable. Otherwise, return False."""
obj_method = getattr(obj, method_name, None)
return callable(obj_method) if obj_method else False |
def pixel_perf_metrics(tp, fp, tn, fn, performanceMetricType):
"""
A function that calculates the performance metric for a pixel-based problem.
"""
n = tp + fp + tn + fn
pre = ((tp+fp)*(tp+fn) + (fn+tn)*(tn+fp)) / (n*n)
pcc = (tp + tn) / n
prec = tp / (tp + fp)
recall =... |
def find_seq_rec(block, name, case_sensitive=True):
"""Given part of a sequence ID, find the first matching record."""
if case_sensitive:
def test(name, rec):
return name in rec['id']
else:
def test(name, rec):
return name.upper() in rec['id'].upper()
for rec in ... |
def get_checked_sites(df):
"""
Returns list of sites that have already been analyzed
:param df: pandas dataframe containing results from reports or parameter study.
:return: List with sites that have already been analyzed.
"""
if df is not None:
checked_sites = df['site'].unique().tolis... |
def box_params(dict_filters, dict_pagination, maybe_sort=None):
"""Mash all the disparate params together into one dict."""
boxed_filters = {}
for key, value in dict_filters.items():
boxed_filters['filter[{0}]'.format(key)] = value
boxed_pagination = {}
for key, value in dict_pagination.it... |
def validate_eyr(field):
"""
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
"""
return field.isdigit() and 2020 <= int(field) <= 2030 |
def add_include_in_ports(step_json: dict, included_ids: list):
"""Add sbg:includeInPorts key to d2 apps for inputs included in ports"""
if step_json['cwlVersion'] == 'sbg:draft-2':
for j, inp in enumerate(step_json['inputs']):
if inp['id'] in included_ids:
step_json['inputs']... |
def shiftdialogs(dialogs, offset):
"""Shifts dialogs ((from, to), txt) by the given amount of offset"""
ret = [((a+offset,b+offset), txt) for (a, b), txt in dialogs]
return ret |
def split(str, delimiters, joiner=None):
"""Split a string into pieces by a set of delimiter characters. The
resulting list is delimited by joiner, or the original delimiter if
joiner is not specified.
Examples:
>>> split('192.168.0.45', '.')
['192', '.', '168', '.', '0', '.', '45']
>>> s... |
def write_rex_file(bytes, path: str):
"""Write to disk a rexfile from its binary format"""
new_file = open(path + ".rex", "wb")
new_file.write(bytes)
return True |
def typename(obj, docp=False, qualp=False):
"""Typename of the obj object
retval-> module:obj<doc> when obj is callable and qualp=False
module:class.obj<doc> when obj is callable and qualp=True
module:class<doc> when obj is a class or an instance of a class
... |
def join_arg(arg_name, arg_type, mode='i'):
"""make string with procedure arguments"""
if mode == 'o':
out_s = 'OUT '
else:
out_s = ''
return '%s%s %s' % (out_s, arg_name, arg_type) |
def intersect2Lists(l1, l2):
"""AND 2 posting lists --> return a list"""
p1 = p2 = 0
resultDocs = []
while p1 < len(l1) and p2 < len(l2):
if l1[p1] == l2[p2]:
resultDocs.append(l1[p1])
p1 = p1 + 1
p2 = p2 + 1
elif (l1[p1]) < (l2[p2]):
p1 = p1 + 1
else:
p2 = p2 + 1
return resultDocs |
def dict_deep_merge(source: dict, destination: dict) -> dict:
"""Deep merges source dict into destination dict."""
# https://stackoverflow.com/a/20666342
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, ... |
def chr_length(chr_id):
""" Return the chromosome length for a given chromosome, based on the reference genome hg38."""
#The data of chromosome length was taken from https://www.ncbi.nlm.nih.gov/grc/human/data?asm=GRCh38
length_dict = {'chr1': 248956422, 'chr2': 242193529, 'chr3': 198295559, 'chr4': 1902145... |
def btw(inputString, lh, rh):
"""Extract a string between two other strings."""
return inputString.split(lh, 1)[1].split(rh, 1)[0] |
def strip_parens(s):
"""Strip parentheses around string"""
if not s:
return s
if s[0] == "(" and s[-1] == ")":
return strip_parens(s[1:-1])
else:
return s |
def ListToString(alist, useAssert=False):
"""Convert a list of strings into a single string
alist is the list to be converted into a string
if useAssert is True, then the function checks whether all elements of alist are strings before proceeding"""
if useAssert:
assert all([isinstance(x, str) for x in alist]), "... |
def is_block(node: dict) -> bool:
"""Check whether a node is a block node."""
return node.get('_type') == 'block' |
def to_hass_level(level):
"""Convert the given Vantage (0.0-100.0) level to HASS (0-255)."""
return int((level * 255) / 100) |
def jumpTable(prefix, *args):
"""
Return a string consisting of a series of <a href='#prefix-xxx'>xxx</a>.
Include <font size='1'></font> around all of it.
"""
header = "<font size='1'>"
sep = ""
for table in args:
header = header + sep + "<a href='#" + prefix + "-" + table + "'>" + ... |
def normalise_two_digit_year(y):
"""
Given a year string, which could be 2 digits, try and get a 4 digit year
out of it as a string
"""
if y[0] == "'":
y = y[1:]
if int(y) < 39:
return '%04d' % (int(y) + 2000)
elif int(y) < 100:
return '%04d' % (int(y) + 1900)
els... |
def superclass(cls):
"""
Return the super class of the given class.
NOTE: This breaks for multiple inheritance, but we don't support that.
"""
mro = cls.__mro__
if len(mro) > 1:
return mro[1]
return None |
def get_string_names(elems, names, label):
"""
Transform the list of values into a string to write
elems is a dictionary with the values
names is the selected keys we want for the output
label is the model label
"""
# Start to write the output string
ss = ""
for name in names:
... |
def get_newest(fromlist):
"""
get_newest(fromlist) where fromlist is a list of DataObjects
Get the newest timestamp out of all the timestamps in the DataObject list.
"""
newest_timestamp = 0
for obj in fromlist:
if obj.newest_sample > newest_timestamp:
newest_timestamp = obj.newest_sample
return... |
def escape_latex_characters(line):
"""
Replace a string with the escaped LaTeX version of reserved characters
:param line: a string to be used in a LaTeX template
:return: a string with the escaped LaTeX version of reserved characters
"""
line = line.replace('\\', '\\textbackslash')
line = l... |
def contfrac_to_rational(frac):
"""
Convert Continued Fraction to Rational
Args:
frac: Continued Fraction List
Return:
x : numerator
y : denominator
"""
if len(frac) == 0:
return (0, 1)
num, denom = 1, 0
frac = frac[::-1]
while True:
t = num
num = frac[0] * num + denom
deno... |
def slow_swap(A, B):
"""
This is a N(O^2) solution
"""
n = len(A)
sumA = sum(A)
sumB = sum(B)
for i in range(n):
for j in range(n):
change = B[j] - A[i]
sumA += change
sumB -= change
if sumA == sumB:
return True, A[i],... |
def sort_with_noise(key_values, key_values_noisy, reverse=True):
"""order clean key values with the order sorted by noisy key values"""
idx = [i[0] for i in sorted(enumerate(key_values_noisy),
key=lambda x:x[1], reverse=reverse)]
key_values_resorted = [key_values[i] for i in ... |
def get_full_class_name(obj, limit=2):
"""Gets full class name of any python object. Used for error names"""
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
name = obj.__class__.__name__
else:
name = module + "." + obj.__class__.__name__
ret... |
def instanceof(obj, classinfo):
"""Wrap isinstance to only return True/False"""
try:
return isinstance(obj, classinfo)
except TypeError: # pragma: no cover
# No coverage since we never call this without a class,
# type, or tuple of classes, types, or such tuples.
return Fals... |
def internal_server_error(error):
"""Error to catch internal server error"""
return {"status": 500, "error": "Internal error!"}, 500 |
def aq_ods_color(*args) -> str:
"""
Return a color from a hexadecimal value.
@param color. Hexadecimal value.
"""
if len(args) == 1:
return hex(args[0])[2:]
else:
return "%02x%02x%02x" % (args[0], args[1], args[2]) |
def price_average(lst):
"""
Returns the average price of the given book
:param lst:
:return:
"""
return sum(lst) / len(lst) |
def packHexStrings(valueDict):
"""Converts a dictionary of lists of floats into a dictionary of lists of hex values arrays"""
hexes = {}
for entry in valueDict: # uglier loop done for compatability with cython
hexes[entry] = [" ".join(float.hex(float(value)) for value in valueDict[entry])]
retu... |
def compile_customization(data):
"""Compile input string for resolution customization.
Args:
data (str): A sentence with customization data.
Returns:
dict: A dict contains customization info.
"""
data=data.split(" ")
optional_data... |
def undecorated_component(component):
"""Returns the given component string without leading/trailing whitespace
and quotation marks."""
return component.strip(" \t\r\n\"'") |
def my_function(my_list):
"""
| change format
|
| Args:
| my_list(list): vector list
|
| Returns:
| list: new format
"""
return list(dict.fromkeys(my_list)) |
def rotate(s, n):
"""
Circularly rotate s by n positions.
"""
return s[n:] + s[:n] |
def is_vowel(letter):
"""Return True if the letter is a vowel, False otherwise
>>> is_vowel("a")
True
>>> is_vowel("b")
False
"""
return letter in "aeiou" |
def strip_unsupported_schema(base_data, schema):
""" Strip keys/columns if not in SCHEMA """
return [
{key: value for key, value in place.items() if key in schema}
for place in base_data
] |
def add_namespace(element):
"""
Adds the namespace to the quakeml xml elements.
"""
return "{http://quakeml.org/xmlns/bed/1.2}" + element |
def make_keys_multicol(columns_to_update_lst):
"""
returns keys to be updated and new names of columns to be updated
:param columns_to_update_lst:
:return joined_str: part of postgres query with keys. E.g. "col1=c.updatecol1 , col2=c.updatecol2"
update_lst: list of new column... |
def dict_key_or_default(d, key, default=None):
"""Avoid if key in d d[key] else None """
if key in d: return d[key]
return default |
def compatibility(i, j, i_n, j_n):
"""
Defines the compatibility function
"""
distance = ((i - i_n)**2.0 + (j - j_n)**2.0)**0.5
return 1 if distance > 0 else 0
# return distance > 0 |
def limit(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Only draw the first N metrics. Useful when testing a wildcard in a metric.
Example:
.. code-block:: none
&target=limit(server*.instance*.memory.free,5)
Draws only the first 5 instance'... |
def selection_sort(arr: list) -> list:
"""
Sort a list to non-decreasing order using selection sort
:param arr: random list or array
:return: sorted list
"""
n = len(arr)
for i in range(n):
min_item = i
for j in range(i+1, n):
if arr[j] < arr[min_item]:
... |
def cell_to_sites(p):
"""Turn a cell ``((i0, j0, k0), (di, dj, dk))`` into the sites it contains.
Examples
--------
>>> cell_to_sites([(3, 4), (2, 2)])
((3, 4), (3, 5), (4, 4), (4, 5))
"""
(i0, j0, k0), (di, dj, dk) = p
return tuple((i, j, k)
for i in range(i0,... |
def isEqual(lhs, rhs):
"""types should be a either a list, tuple, etc"""
for x,y in zip(lhs, rhs):
if x == y:
continue
else:
return False
return True |
def __convertLevel(level, table):
""" Convert yum logging levels using a lookup table. """
# Look up level in the table.
try:
new_level = table[level]
except KeyError:
keys = sorted(table.keys())
# We didn't find the level in the table, check if it's smaller
# than the sm... |
def elf_hash(some_bytes: bytes):
"""The ELF hash (Extremely Lossy Function - also used in ELF format).
unsigned long ElfHash(const unsigned char *s) {
unsigned long h = 0, high;
while (*s) {
h = (h << 4) + *s++;
if (high = h & 0xF0000000)
h ^= high >> 24;... |
def to_address(ptr: int):
"""Convert a ROM pointer to an address."""
if ptr < 0x8000000 or ptr > 0x9FFFFFF:
return -1
return ptr - 0x8000000 |
def _escape_filename(filename):
"""Turns a file into a string representation with correctly escaped backslashes"""
repr = str(filename)
repr = repr.replace('\\', '\\\\')
return repr |
def distance(point1, point2):
"""
Distance between two points
:param tuple point1: first point coordinates (1, 2)
:param tuple point2: second point coordinates (3.0, 4)
:return: line segment length
:rtype: float
>>> distance((0, 0) (3, 4.0))
5.0
"""
x1, y1 = point1
x2, y2 =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.