content stringlengths 42 6.51k |
|---|
def _read_data_configs(config_data):
"""Creates list of dictionaries.
Each dict is a set of config parameters for the data.
Args:
config_data: dictionary with data parameters
Returns:
list with all config parameters.
"""
parameters_data = []
for config in config_data:
parameters = {}
if c... |
def print_failed(failed):
"""Print failed counts."""
lines = []
for key, val in sorted(failed.items()):
if key != 'failed-cutoff':
pretty_key = key.replace('-', ' ').title()
lines.append(f' {pretty_key}: {len(val)}')
return '\n'.join(lines) |
def GetCmdReturn(shell_text, cmd):
"""Return the result of a command launched in MicroPython
:param shell_text: The text catched on the shell panel
:type shell_text: str
:param cmd: The cmd return asked
:type cmd: str
:return: the return of the command searched
:rtype: str
"""
if c... |
def choose_best(ordered_choices, possible, check, default=None):
"""
Select the best xref from several possible xrefs given the ordered list of
xref database names. This function will iterate over each database name and
select all xrefs that come from the first (most preferred) database. This
uses t... |
def bracket_block(text):
"""
finds start and end of the first bracketed block
"""
istart=text.find('(')
cursor=istart
if cursor != -1:
counter=1
while (cursor<len(text)) and counter>0:
cursor+=1
if text[cursor]=='(':
counter += 1
elif text[cursor]==')':
counte... |
def extract_longitude(input_string):
"""
Extracts the longitude from the provided text, value is all in degrees and
negative if West of London.
:param input_string: Text to extract the longitude from.
:return: Longitude
"""
if "E" in input_string:
find_me = "E"
elif "W" in inp... |
def command( *args ):
"""
Returns the command as a string joining the given arguments. Arguments
with embedded spaces are double quoted, as are empty arguments.
"""
cmd = ''
for s in args:
if cmd: cmd += ' '
if not s or ' ' in s:
cmd += '"'+s+'"'
else:
... |
def find_stem(arr):
"""
From https://www.geeksforgeeks.org/longest-common-substring-array-strings/
"""
# Determine size of the array
n = len(arr)
# Take first word from array
# as reference
s = arr[0]
ll = len(s)
res = ""
for i in range(ll):
for j in range(i + 1, ll... |
def latex_var(name, value, desc=None, xspace=True):
"""Create a variable NAME with a given VALUE.
Primarily for output to LaTeX.
Returns a string."""
xspace_str = r"\xspace" if xspace else ""
return "".join(['\\newcommand{\\', str(name), '}{', str(value), xspace_str, '}'] + ([' % ', desc] if desc el... |
def has_two_elements_that_sum_bonus(elements, k):
"""
Bonus: This implementation is a bit uglier, but it's still O(n) space and goest over it once
"""
required = set()
for e in elements:
difference = k - e
if e in required:
return True
else:
required.a... |
def enforce_min_sites(cache, min_sites):
"""Remove blocks with fewer than min_sites informative sites and then
merge adjacent blocks in the same state."""
cache = [c for c in cache if c['informative-sites'] >= min_sites]
if len(cache) < 2: return cache
icache = [cache[0]]
for i, c in enumerate(... |
def environment_setting_format(value):
"""Space-separated values in 'key=value' format."""
try:
env_name, env_value = value.split('=')
except ValueError:
message = ("Incorrectly formatted environment settings. "
"Argument values should be in the format a=b c=d")
ra... |
def sidebar_update(res):
"""[summary]
Args:
res ([type]): [description]
Returns:
[type]: [description]
"""
sidebar_updates = {
"event": "sidebar_update",
"plugin_id": "sales.zuri.chat",
"data": {
"name": "Company Sales Prospects",
"gr... |
def get_minimun(list_values):
"""
function to obtain the min. score of ppmi
:param list_values:
:return:
"""
min_score = min(list_values)
return min_score |
def square_params(x_initial, x, y_initial, y):
"""
Calculates square parameters acquired from the mouse movements for rendering the square on the image.
"""
side = abs(y_initial - y)
x_top = round(x - side/2)
x_bottom = round(x + side/2)
y_top = min(y_initial, y)
y_bottom = ... |
def _extra_args_to_dict(extra_args):
"""Parses comma-separated list of flag_name=flag_value to dict."""
args_dict = {}
if extra_args is None:
return args_dict
for extra_arg in extra_args.split(','):
(flag_name, flag_value) = extra_arg.split('=')
flag_name = flag_name.strip('-')
# Check for boole... |
def eliminate_internal_polygons(polys_in):
"""Eliminate any polygons in a list that are fully contained within another polygon"""
polys_out = []
poly_num = len(polys_in)
# Iterate through list of polygons twice for comparisons
for i in range(0,poly_num):
within_flag = False
... |
def resource_name(obj_type):
"""
Transforms an object type into a resource name
:param obj_type:
The object type, i.e. ``user`` or ``user_reference``
:returns: The name of the resource, i.e. the last part of the URL for the
resource's index URL
:rtype: str
"""
if obj_type.en... |
def find_smaller_of_a_kind(playable_items):
"""
Gets list of playable moves from find_3_of_a_kind and adds smaller possible moves to that list
For (3b,3g,3r,3s) this will add (3b,3g,3r), (3b,3g,3s), ...
:param playable_items: Possible moves, the user can do
:return: list of possible ... |
def extract_1_gram(token_list):
"""
Extract 1-gram in a bug report text part
"""
features = set()
for term in token_list:
if len(term) > 0:
features.add(term)
return features |
def floor_amount(x):
"""Returns x floored to n significant figures.
from https://mail.python.org/pipermail/tutor/2009-September/071393.html
"""
factor = 1000000
return 1.0 * int(x * factor) / factor |
def one_k_encoding(value, choices):
"""
Creates a one-hot encoding with an extra category for uncommon values.
:param value: The value for which the encoding should be one.
:param choices: A list of possible values.
:return: A one-hot encoding of the :code:`value` in a list of length :code:`len(choi... |
def madd(a,b,c):
"""Return a+c*b where a and b are vectors."""
if len(a)!=len(b):
raise RuntimeError('Vector dimensions not equal')
return [ai+c*bi for ai,bi in zip(a,b)] |
def pad_if_needed(inp_list):
"""
Checks the number of elements in the input list, if number is odd then one element is added
input: inp_list, list containing n elements
returs: inp_list, list containing n or n+1 elements
"""
n = len(inp_list)
if n % 2 == 0:
return inp_list, False
else:
inp_list.append(0)... |
def chocolate_feast(n, c, m):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/chocolate-feast/problem
Function that calculates how many chocolates Bobby can purchase and eat. Problem stated below:
Little Bobby loves chocolate. He frequently goes to his favorite 5&10 store, Penny Auntie, to b... |
def solve_substring_left_to_right(text):
"""
Solve a flat/small equation that has no nested parentheses
Read from left to right, regardless of the operation
:param str text: A flat equation to solve
:return: The result of the given equation
:rtype: int
"""
text = text.replace("(", "")
... |
def wxToGtkLabel(s):
"""
The message catalog for internationalization should only contain
labels with wx style ('&' to tag shortcut character)
"""
return s.replace("&", "_") |
def Min(a, b) :
"""Max define as algrebraic forumal with 'abs' for proper computation on vectors """
return (a + b - abs(b - a)) / 2 |
def parse_snippets(snippets: dict):
"""
Parses raw snippets definitions with possibly multiple keys into a plan
snippet map
"""
result = {}
for k in snippets.keys():
for name in k.split('|'):
result[name] = snippets[k]
return result |
def version(showfile=True):
"""
Returns the CVS revision number.
"""
myversion = "$Id: plotbandpass3.py,v 1.210 2021/02/19 18:10:02 thunter Exp $"
if (showfile):
print("Loaded from %s" % (__file__))
return myversion |
def set_piece(board, index, val):
"""Sets the nth piece of the provided board"""
negative = board < 0
board = board if board >= 0 else -board
factor = 10 ** index
chopped = board // factor
leftover = board % factor
old_piece = chopped % 10
chopped -= old_piece
chopped += val
mo... |
def quast_qc_check(quast_results, estimated_genome_size):
"""
QUAST PASS CRITERIA:
1. total length within +/- 10% of expected genome size
Args:
quast_results (dict): Quast results
qc_thresholds (dict): Threshold values for determining QC pass/fail
Returns:
boolean: Assembly p... |
def create_resumo(fulltext):
"""
Get the first `resumo_length` (hard-coded) characters from `fulltext`
that appear after `beginning_marker` (hard-coded) or small variations
of it. If `beginning_marker` is not found, return `fulltext`.
"""
beginning_marker = 'resolve'
resumo_length = 500... |
def get_tlv(tlvs, cls):
"""Find the instance of a class in a list"""
for tlv in tlvs:
if isinstance(tlv, cls):
return tlv |
def multList(list_a, list_b):
"""
Zips 'list_a' items with 'list_b' items and multiplies them together
:param list_a: list of digits
:param list_b: list of digits
:return: list of digits
"""
return [x*y for x, y in zip(list_a, list_b)] |
def get_base_worker_instance_name(experiment):
"""GCE will create instances for this group in the format
"w-|experiment|-$UNIQUE_ID". 'w' is short for "worker"."""
return 'w-' + experiment |
def long_url(l):
"""This function is defined in order to differntiate website based on the length of the URL"""
l= str(l)
if len(l) < 53:
return 0
elif len(l)>=53 and len(l)<75:
return 2
else:
return 1 |
def smtp_config_writer_ssl(kwargs, config):
"""
Set SSL/TLS config.
:param kwargs: Values. Refer to `:func:smtp_config_writer`.
:type kwargs: dict
:param config: Configuration dictionary.
:type config: dict
"""
if kwargs['is_ssl'] is not None:
config['is_ssl'] = str(kwargs['is_... |
def get_movies(movie_dict, target_genres):
"""
Returns a list of movie names that has in its list of genres all genres in
target_genres.
"""
movie_names = []
# Fill in body of the function here.
return movie_names |
def kml_start(params):
"""Define basic kml
header string"""
kmlstart = '''
<Document>
<name>%s</name>
<open>1</open>
<description>%s</description>
'''
return kmlstart % (params[0], params[1]) |
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens |
def remove_empty_lines(txt):
"""
replace("\n\n", "\n") does not work in cases with more than two empty
consective empty lines
"""
return "\n".join(t for t in txt.splitlines() if t.strip()) |
def calc_score( winning_deck ):
"""
This function returns the score of the winning player
"""
score = 0
for point, card in enumerate( winning_deck[::-1] ):
score += (point+1) * card
return score |
def inverse_map(i: int, n: int):
"""
Accumulative STP of logical variables is bijective.
Given a result i (\delta_{2^n}^i), find the corresponding logical values.
:return a list of 0/1
"""
r = []
while n > 0:
if i % 2 == 0:
r.append(0)
i = i // 2
else... |
def compute_unique_id(x):
"""RPython equivalent of id(x). The 'x' must be an RPython instance.
This operation can be very costly depending on the garbage collector.
To remind you of this fact, we don't support id(x) directly.
"""
return id(x) # XXX need to return r_longlong on some platforms |
def update_extreme(val, fncn, new_val):
""" Calculate min / max in the presence of None values """
if val is None: return new_val
else: return fncn(val, new_val) |
def multithresh(arr, lbs, ubs, ths):
""" Multilevel thresholding of a 1D array. Somewhat similar to bit depth reduction.
**Parameters**\n
arr: 1D array
Array for thresholding.
lbs, ubs: list/tuple/array, list/tuple/array
Paired lower and upper bounds for each thresholding level.
ths... |
def is_e164_format(phone):
"""Return true if string is in E.164 format with leading +, for example "+46701740605" """
return len(phone) > 2 and phone[0] == "+" and phone[1:].isdigit() and len(phone) <= 16 |
def clean_field(node):
"""Get Edges & Nodes"""
return_value = []
if node.get("edges"):
fields = node["edges"]["node"]
for key, val in fields.items():
if val:
items = clean_field(val)
return_value.extend([f"{key}.{i}" for i in items])
el... |
def load_player(data):
"""
Loading the player specs.
Parameters:
data(dict): Nested dictionaries containing
all information of the game.
Returns:
player_specs(tuple): Tuple of player specs.
"""
player_specs = (data['Player']['Position'], data['Player']['Inventory'])... |
def make_dict(list1, list2):
"""
Makes a dictionary using the provided lists.
Input:
list1 (list): List to be used for keys.
list2 (list): list to be used for values.
Output:
out_dict (dict): Dictionary using the input lists
"""
out_dict = {}
i = 0
for item in list1:
... |
def LinkConfig(reset=0, loopback=0, scrambling=1):
"""Link Configuration of TS1/TS2 Ordered Sets."""
value = ( reset << 0)
value |= ( loopback << 2)
value |= ((not scrambling) << 3)
return value |
def solution(dataset: list) -> int:
""" "there is a '\n' on the end of the first line but zip() will only go to the sortest length.
If both lines have '\n's then they will be equivalent and won't be counted"""
return sum(i != j for i, j in zip(*dataset)) |
def is_image(name, exts=None):
"""return True if the name or path is endswith {jpg|png|gif|jpeg}"""
default = ['jpg', 'png', 'gif', 'jpeg']
if exts:
default += exts
flag = False
for ext in default:
if name.lower().endswith(ext):
flag = True
break
return ... |
def number_of_samples(X, y, **kwargs):
"""It represents the total number of samples in the dataset"""
try:
return X.shape[0]
except:
return len(X) |
def decodeModifiers (modifier):
"""
{:032b}
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 0 0 1 0 1 0 1 1
0 11 12 13 14 15 31
cmd 00000000000100000000000100001000 b11
alt 00000000000010000000000100100000 b12
ctrl 0000000000000100000000010000000... |
def split_list_with_len(lst: list, length: int):
"""
return a list of sublists with len == length (except the last one)
"""
return [lst[i:i + length] for i in range(0, len(lst), length)] |
def get_initial_state(inp):
"""
return tuple of (terminals,initial assignments) where terminals is a dictionnay key = target and value is a
list of start and end coordinates
"""
terminals = {}
assignments = {}
for row_ind in range(len(inp)):
for col_ind in range(len(inp[row_ind]... |
def add_toc(txt):
"""Add github-style ToC to start of md content.
"""
lines = txt.split('\n')
toc_lines = []
mindepth = None
for line in lines:
if not line.startswith('#'):
continue
parts = line.split()
hashblock = parts[0]
if set(hashblock) != set(... |
def _merge(old, new):
"""Concatenate two environment paths avoiding repeats.
Here `old` is the environment string before the base class initialize
function is called and `new` is the string after the call. The new string
will be a fixed string if it is not obtained from the current enviroment,
or t... |
def is_iterable(maybe_iter, unless=(dict)):
""" Return whether ``maybe_iter`` is an iterable, unless it's an instance of one
of the base class, or tuple of base classes, given in ``unless``.
Example::
>>> is_iterable('foo')
False
>>> is_iterable(['foo'])
True
>>> is... |
def get_a_field_set_from_data(data, index=0):
"""
Extract a unique (non-repeating) columnar set from supplied data
It takes parameters:
data (data in the form of a list of lists)
and optionally:
index (by default 0, it is the column field to extract)
It returns a set of column field data s... |
def className(obj):
""" Return the name of a class as a string. """
return obj.__class__.__name__ |
def handle_tensorboard_not_found(e):
"""Handle exception: tensorboard script not found."""
return "Tensorboard not found on your system." \
" Please install tensorflow first. Sorry.", 503 |
def test(arg: str) -> bool:
"""Hello
>>> 1 + 13
14
:param arg: An argument
:return: Return the resulting value
"""
return arg == 'foo' |
def valid_parentheses_brackets(input_string: str) -> bool:
"""
Determine whether the brackets, braces, and parentheses in a string are valid.
Works only on strings containing only brackets, braces, and parentheses.
Explanation: https://www.educative.io/edpresso/the-valid-parentheses-problem
:param... |
def ean8_check_digit(num):
"""
EAN checksum
gewichtete Summe: die letzte Stelle (vor der Pruefziffer) mal 3,
die vorletzte mal 1, ..., addiert Pruefziffer ist dann die Differenz
dieser Summe zum naechsten Vielfachen von 10
:param num: (?)
:return: (?)
"""
s = str(num)[::-1] # in str... |
def remove_possible_title_from_text(
text: str, title: str, min_title_length: int = 3, overlap_ratio: float = 0.5
) -> str:
"""
Remove title from text document.
:param text:
text string
:param title:
title to remove
:param min_title_length:
minimum length of title to rem... |
def get_progress_rate(k, c_species, v_reactants):
"""Returns the progress rate for a reaction of the form: va*A+vb*B --> vc*C.
INPUTS
=======
k: float
Reaction rate coefficient
c_species: 1D list of floats
Concentration of all species
v_reactants: 1D list of floats
Stoi... |
def is_iterable(x):
"""Determines whether the element is iterable.
>>> isiterable([1, 2, 3])
True
>>> isiterable('abc')
True
>>> isiterable(5)
False"""
try:
iter(x)
return True
except TypeError:
return False |
def register_to_signed_int(x, base=16):
"""
Modbus uses 16-bit integers, which can sometimes be treated as a signed 15-bit number.
This handles converting a signed 16-bit number to a proper int
Optionally can also work on other bases, but that's not normally needed
"""
if x & (1 << (base-1)):
... |
def count_string_dictionary(list_of_strings):
"""
Count the number of instances in a list and return them in a dictionary where the keys are the strings and
the value the number of times it appeared in the list
"""
to_return = {}
for e in list_of_strings:
try:
to_ret... |
def _find_file_type(file_names, extension):
"""
Returns files that end with the given extension from a list of file names.
"""
return [f for f in file_names if f.lower().endswith(extension)] |
def generate_combinations(items, count_min, count_max, cur_items):
"""Generate possible combinations of items froum count_min to count_max."""
if len(cur_items) == count_max:
return [cur_items]
combinations = []
if len(cur_items) >= count_min:
combinations.append(cur_items)
for item ... |
def delete_suppliers_list(data):
"""Delete the list of suppliers added by ``add_suppliers_to_markets``.
This information was used by ``allocate_suppliers`` and ``update_market_production_volumes``, but is no longer useful."""
for ds in data:
if 'suppliers' in ds:
del ds['suppliers']
... |
def remove_trailing_space(s, punctuation="!?.,"):
""" Removes a trailing space in a sentence eg.
"I saw a foo ." to "I saw a foo."
"""
for punc in punctuation:
if len(s) < 2:
return s
if " %s" % punc == s[-2:]:
s = s[:-2] + punc
for punc in punctuation:
... |
def zero_remove(line):
"""
This function just returns a sublist of the passed parameter after removing all zeros
It takes O(n) time --> linear runtime complexity
:param line:
:return non_zero:
"""
non_zero = []
for num in line:
if num != 0:
non_zero.append(num)
return non_z... |
def get_remaining_cores(sellers):
"""
sellers is a list of list where each list contains follwing item in order
1. Seller Name
2. Number of available cores
3. Price of each core
return the total number of cores unallocated
"""
rem_core=0
for selleri in sellers:
rem_core+=selleri[1]
return rem_core |
def getSize(isInside):
""" Returns size of points depending on if they're close to rect """
if isInside:
return 1.5
else:
return 0.2 |
def num_length(num):
"""
Returns the length in digits of num
:param num: Num
:return: Length in digits
"""
return len(str(num)) |
def create_alias(name):
"""
Clean an alias to be an acceptable Python variable
"""
return name.replace(' ', '_').replace('.', '_').lower() |
def Hermite( x, n ):
"""
Function used to compute the Hermite polynomials.
Args:
x (any): variable.
n (int): polynomials order
Returns:
any: returns the value of the polynomials at a given order for a given variable value.
Testing:
Already tested in... |
def dict_values(dict, tuple_index, tuple_index_value):
"""
:param dict: a dictionary whose keys are a tuple
:param tuple_index: index of tuple that is of interest
:param tuple_index_value: value required of tuple at tuple_index
:return: list of appropriate keys of dict & corresponding values
"""... |
def dirname_from_params(**kwargs):
"""Concatenate key, value pairs alphabetically, split by underscore."""
ordered = sorted(kwargs.items())
words = ["_".join([key, str(value)]) for key, value in ordered]
return "_".join(words) |
def vector_add(v, w):
"""adds two vectors componentwise"""
return [v_i + w_i for v_i, w_i in zip(v,w)] |
def divisors_more_concise(integer: int):
"""
Here's what someone else did, using 'or' to conditionally return
"""
return [i for i in range(2, integer) if not integer % i] or '%d is prime' % integer |
def permutations(values):
"""Permutes the provided list
Args:
values (list): List to permute values within
Returns:
list: List of permutations of values
"""
if len(values) == 1:
return values[0]
ret = []
i = 0
for item in values:
values.remove(item)
... |
def round_nearest(hours, interval=0.5):
"""Rounds the given hours to the nearest interval-hour"""
if interval <= 0:
raise ValueError('interval must be greater than zero')
return round(hours / interval) * interval |
def transformIntoZero(value):
"""fonction permettant de transformer un string vide en 0"""
if value == "":
return 0
else:
return value |
def _bound(color_component: float, minimum: float=0,
maximum: float=255) -> float:
"""
Bound the given color component value between the given min and max values.
The minimum and maximum values will be included in the valid output.
i.e. Given a color_component of 0 and a minimum of 10, the r... |
def ssa_from_acf_slope(volume_fraction, acf_slope_at_origin):
"""
compute the ssa from given slope of an autocorrelation function
C(r) at the origin and the volume fraction.
This relation is often called Debye relation
"""
##################################################
# repl... |
def overlap(start1, end1, start2, end2):
"""
Check if the two ranges overlap.
"""
return end1 >= start2 and end2 >= start1 |
def construct_doc2author(corpus, author2doc):
"""Create a mapping from document IDs to author IDs.
Parameters
----------
corpus: iterable of list of (int, float)
Corpus in BoW format.
author2doc: dict of (str, list of int)
Mapping of authors to documents.
Returns
... |
def query_delete_table(table):
"""Generate table delete query for table with name 'table'"""
return 'DROP TABLE IF EXISTS ' + table |
def reverse(pattern):
"""[reverses a string]
Args:
pattern ([string]): [string to be reversed]
Returns:
[string]: [reversed version of inputted string "pattern"]
"""
return ''.join(reversed(pattern))
# OR return pattern[::-1]
|
def type_or_class_match(node_a, node_b):
"""
Checks whether `node_a` is an instance of the same type as `node_b`, or
if either `node_a`/`node_b` is a type and the other is an instance of that
type. This is used in subgraph matching to allow the subgraph pattern to
be either a graph of instantiated n... |
def to_data(s):
"""
Format a data variable name.
"""
if s.startswith('GPSTime'):
s = 'Gps' + s[3:]
if '_' in s:
return "".join([i.capitalize() for i in s.split("_")])
return s |
def flatten_list(list_of_lists):
""" Will convert a list of lists in a list with the items inside each sub-list.
Parameters
----------
list_of_lists: list[list[object]]
Returns
-------
list
"""
if not list_of_lists:
return []
if isinstance(list_of_lists[0], list):
... |
def flatten(arr, type):
"""Flatten an array of type."""
res = []
for i in arr:
if isinstance(i, type):
res.append(i)
else:
res.extend(flatten(i, type))
return res |
def issouth(bb1, bb2, north_vector=[0,1,0]):
""" Returns True if bb1 is south of bb2
For obj1 to be south of obj2 if we assume a north_vector of [0,1,0]
- The max Y of bb1 is less than the min Y of bb2
"""
#Currently a North Vector of 0,1,0 (North is in the positive Y direction)
#i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.