content stringlengths 42 6.51k |
|---|
def combinations(input_list):
"""Return all possible combinations of the elements in an input
sequence. The last returned element will be the empty list.
E.g., combinations([0,1]) returns [[0, 1], [0], [1], []]
Taken from the internet:
http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-... |
def map_range(number, in_min, in_max, out_min, out_max):
"""Maps a number from one range to another.
:param number: The input number to map.
:param in_min: The minimum value of an input number.
:param in_max: The maximum value of an input number.
:param out_min: The minimum value of an output nu... |
def remove(list_, item):
"""Removes an item from a list."""
return [i for i in list_ if i != item] |
def get_time_pairs(mapping):
"""
Gets a list of the timestep_tags for all buildings
Returns
time_pairs -- list of tuples of (building_name, timestep_tag), in the order specified by mapping.json
"""
ts_group = []
for building_name in mapping.keys():
controls = mapping[building_name]["Control"]
print(control... |
def consecutive(arr):
"""
Sort the string from min to max
get the range from the min to max number and store in a variable,
return the difference of the 2 lists
:param arr: The array to evaluate
:return: the number of consecutive numbers needed
"""
if len(arr) == 0 or len(arr) == 1:
... |
def message(data, **kwargs):
"""Create message."""
ctr_info = {"broker_id": -1, "explorer_id": -1, "agent_id": -1, "cmd": "train"}
ctr_info.update(**kwargs)
return {"data": data, "ctr_info": ctr_info} |
def is_unique_sets(s):
"""
The most straightforward approach in python is to utilize the power of sets.
Sets are implementations of hash table that allows fast read/write operations
In this case we will split the string into a list then convert into
"""
s_splitted = s.split()
ret... |
def IsConstuctor(value, fullName, context):
""" Check if the passed value is the contructor or destructor """
fullName = fullName.replace("~", "")
names = fullName.split("::")
if len(names) != 1 and names[-1] == value :
return True
if context != None and context.type in ["CLASS_BLOCK... |
def calculate_desired_noise_rms(signal_rms, snr):
"""
Given the Root Mean Square (RMS) of a clean sound and a desired signal-to-noise ratio (SNR),
calculate the desired RMS of a noise sound to be mixed in.
Based on:
- https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a10... |
def find_linestarts(codeobj):
"""Finds the offsets in a bytecode which are the start a line in the source code.
Parameters
=========================================
codeobj (code): code object
Returns
=========================================
dict: a dictionary with offsets as the keys and ... |
def Root_f(header, body, footer):
""" :param header: The "header" of this Root
:param body: The "body" of this Root
:param footer: The "footer" of this Root
"""
return header + body + footer |
def find_ngrams(single_words, n):
"""
Args:
single_words: list of words in the text, in the order they appear in the text
all words are made of lowercase characters
n: length of 'n-gram' window
Returns:
list of n-grams from input text list, or an empty l... |
def _to_numeric(value):
"""Try to convert a string to an integer or a float.
If not possible, returns the initial string.
"""
try:
value = int(value)
except:
try:
value = float(value)
except:
pass
return value |
def shortLex(s1, s2):
"""Shortlex less or equal comparator"""
if len(s1) > len(s2):
return False
if len(s1) < len(s2):
return True
return s1 <= s2 |
def status_message(status: int, message: str) -> str:
"""Construct a status message (presumably from a process exit code.)"""
if status == 0:
message += " \u2705"
else:
message += " \u274c {:d}".format(status)
return message |
def unmount_datastore(datastore, host):
"""Unmount a datastore"""
try:
for d in host.datastore:
if d.name == datastore:
host.configManager.datastoreSystem.RemoveDatastore(d)
return True
return False
except:
return False |
def split_file_name(file_absolute_name):
"""
Splits a file name into: [directory, name, extension]
:param full_name_template:
:return:
"""
split_template = file_absolute_name.split('/')
[name, extension] = split_template[-1].split('.')
directory = "/".join(split_template[0: len(split_te... |
def isnum(n):
""" Check if n is a number """
return type(n) in (int, float, complex) |
def get_per_channel_param(pack_paths_channels, get_param):
"""Get One value of a parameter per channel in pack_paths_channels.
See get_single_param."""
return [get_param(pack_path, channel) for pack_path, channel in pack_paths_channels] |
def fit_config(rnd: int):
"""Return training configuration dict for each round.
Keep batch size fixed at 32, perform two rounds of training with one
local epoch, increase to two local epochs afterwards.
"""
config = {
"batch_size": 16,
"local_epochs": 1 if rnd < 2 else 2,
}
... |
def tuplefy(value):
"""Returns the value in or as a tuple if not already a tuple."""
return value if isinstance(value, tuple) \
else tuple(value) if isinstance(value, list) else (value, ) |
def atbash_cipher_encryptor_decryptor(message: str) -> str:
"""Encrypts and decrypts a given message using an AtBash Cipher (substitutes a letter of the plaintext
alphabet with the corresponding letter of the reversed alphabet).
a <-> z
b <-> y
c <-> x
Args:
message (str): Message to ... |
def kickOnAt(i, i_set, j, j_set):
"""@
kick on at
Turns on debugging parameters when the specific indices i and j
meet the condition that (i,j) = (i_set, j_set), and turns these
debugging parameters off under other conditions.
"""
flag_on = False
if i_set == i and j == j_... |
def isFloat(string):
""" Helper method to test if val can be float
without throwing an actual error.
"""
try:
float(string)
return True
except ValueError:
return False |
def dict_mins(dict1):
"""
Determines the minima of all coordinates. returns the minima for the 3
axes separately. Returns a tuple with min x, y and z
"""
x_dim = []
y_dim = []
z_dim = []
for (i, j, k) in dict1.keys():
y_dim.append(j)
x_dim.append(i)
z_d... |
def sort_key_dfcolnames(x):
"""Sort key function for list of pandas DataFrame column names.
Used to put 'JobID' column first in pandas DataFrame"""
if x == 'JobID':
return (0, x)
elif x == 'ModelFile':
return (1, x)
elif x == 'SampleFile':
return (2, x)
else:
ret... |
def welcommessage(version):
"""Return welcome message."""
message = 'Kaidoku - player, solver and creater of sudoku puzzles.\n' + \
' https://sekika.github.io/kaidoku/\n' + \
'Type h for help, c for showing a problem, q for quit.'
return message |
def _valid_size(size):
"""
Pyrsistent invariant for filesystem size, which must be a multiple of 1024
bytes.
"""
if size % 1024 == 0:
return (True, "")
return (
False, "Filesystem size must be multiple of 1024, not %d" % (size,)
) |
def filter_words(words, filters):
""" Filter words from a list of filters """
filters = set(filters)
return [w for w in words if w.lower() not in filters] |
def is_android(bot_cfg):
"""Determine whether the given bot is an Android bot."""
return ('Android' in bot_cfg.get('extra_config', '') or
bot_cfg.get('os') == 'Android') |
def compute_qtype_acc(predictions, qtype, key_name='vqa_ans'):
"""
Compute QA accuracy for qtype
"""
acc, cnt = 0, 0
for entry in predictions:
if key_name in entry and entry['type'] == qtype:
if entry[key_name] == entry['answer']:
acc += 1
cnt += 1
... |
def kdel(x,y):
"""Kronecker Delta"""
if x == y:
return 1
else:
return 0 |
def A070939(i: int = 0) -> int:
"""Length of binary representation of n."""
return len(f"{i:b}") |
def splitIntoLiteralsAndNonLiterals(str1, quoteValue="'"):
"""
Break the string (str1) into a list of literals and non-literals where every
even number element is a non-literal and every odd number element is a literal.
The delimiter between literals and non-literals is the quoteValue, so this
funct... |
def Distance(a, b):
"""Function that calculates the Levenshtein distance between any two
indexable objects.
"""
c = {}
n = len(a); m = len(b)
for i in range(0, n + 1):
c[i, 0] = i
for j in range(0, m + 1):
c[0, j] = j
for i in range(1, n + 1):
for j in range(1, m + 1):
x = c[i - 1,... |
def p(n, d):
""" Helper to calculate the percentage of n / d,
returning 0 if d == 0.
"""
if d == 0:
return 0.0
return float(n) / d |
def mifareclassic_IsTrailerBlock( uiBlock: int):
"""
Indicates whether the specified block number is the sector trailer
"""
# Test if we are in the small or big sectors
if (uiBlock < 128):
return ((uiBlock + 1) % 4 == 0)
else:
return ((uiBlock + 1) % 16 == 0) |
def provides_priority_sorting(a,b):
"""
Sorting function for ``ctn_accept_binding``
"""
if a[0].startswith('*/'): return -1
if b[0].startswith('*/'): return 1
if a[0].endswith('/*'): return -1
if b[0].endswith('/*'): return 1
a_prio = a[1][0]
b_prio = b[1][0]
if a_prio > b_prio: ... |
def remove_chars(value,char_list=''):
"""
Remove specific chars from a string
:param value: Value to be formatted
:type value: String
:param char_list: String containing the characters you want to remove
:type char_list: String
:returns: String without punctuation symbols
:rtype: St... |
def update_needs_bg_power_workaround(data):
"""Check if a push update needs the bg_power workaround.
Some devices will push the incorrect state for bg_power.
To work around this any time we are pushed an update
with bg_power, we force poll state which will be correct.
"""
return "bg_power" in ... |
def insertPayload(url, payload):
"""
:Description: This function inserts the Payload as GET Parameter in the URL
:param url: Target URL
:type type: String
:param payload: Payload string
:type payload: String
:return: The URL with a concatenated strin... |
def methods_of(obj):
"""Return non-private methods from an object.
Get all callable methods of an object that don't start with underscore
:return: a list of tuples of the form (method_name, method)
"""
result = []
for i in dir(obj):
if callable(getattr(obj, i)) and not i.startsw... |
def check_result(func,**kwargs):
"""
wrap calls to sheep-server API, check return code, and return response content
"""
response = func(**kwargs)
if response["status_code"] != 200:
print(response["content"])
raise RuntimeError("Error in call to sheep-server")
return response["con... |
def convert_hex_to_rgb_255(hex_str):
"""Convert hex color to rgb in range 0-255."""
hex_color = hex_str.lstrip("#")
n = len(hex_color)
rgb = list(int(hex_color[i : i + int(n / 3)], 16) for i in range(0, int(n), int(n / 3)))
return rgb |
def mod(value, mod=1):
"""
RETURN NON-NEGATIVE MODULO
RETURN None WHEN GIVEN INVALID ARGUMENTS
"""
if value == None:
return None
elif mod <= 0:
return None
elif value < 0:
return (value % mod + mod) % mod
else:
return value % mod |
def rotate(l: list, n: int) -> list:
"""Method to rotate elements in a list.
Parameters
----------
l : list
input list
n : int
number of element to rotate over
Returns
-------
list
rotated list
"""
return l[-n:] + l[:-n] |
def fast_fib(n):
""": fast_fib { n m }
n 1 begin 2dup >= while 2* repeat to m
1 0 begin m 2/ dup to m
while swap 2dup * 2*
swap dup *
rot dup * dup
rot + -rot +
n m and
if tuck + then
repeat nip ;
"""
# ( Slower version without local variables )
# 1 begin 2dup >= while 2*... |
def is_valid_componenet_name(name):
"""Validate actor name
"""
# so far no restrictions
return True |
def mk_eqv_expr(expr1, expr2):
"""
returns an or expression
of the form (EXPR1 <=> EXPR2)
where EXPR1 and EXPR2 are expressions
"""
return {"type": "eqv",
"expr1": expr1,
"expr2": expr2} |
def go_down(name, exists, lower, upper):
"""bisection to find first free slot
"""
if upper - lower < 2:
if exists(name + '-%d' % lower):
return name + '-%d' % upper
else:
return name + '-%d' % lower
else:
mid = (upper + lower) // 2
if exists(name +... |
def get_pip_command_action(command):
"""Return pip action for a pip command."""
return command.split()[1] |
def compute_average_cosine_similarity(square_norm_of_sum, num_vectors):
"""Calculate the average cosine similarity between unit length vectors.
Args:
square_norm_of_sum: The squared norm of the sum of the normalized vectors.
num_vectors: The number of vectors the sum was taken over.
Returns:
A float... |
def attr(name, grp=True):
"""Return a regular expression to match an XML attribute.
name: name of the attribute to match
grp: boolean indicating whether to retain the attribute value subgroup.
returns: regular expression text
"""
return '(?: +{0}="({1}[^"]+)")'.format(name, "" if grp else "... |
def filter_max_loan_size(loan_amount, bank_list):
"""Filters the bank list by the maximum allowed loan amount.
Args:
loan_amount (int): The requested loan amount.
bank_list (list of lists): The available bank loans.
Returns:
A list of qualifying bank loans.
"""
#EH: create a... |
def intersection_covers(points_IN, simplex):
"""Computes the points in the intersection specified by a nerve simplex.
Parameters
----------
points_IN : :obj:`list(list(Numpy Array 1D))`
Identification Numbers (IN) of points in covering hypercubes.
simplex : :obj:`Numpy Array`
Simpl... |
def _get_defaults(func):
"""Internal helper to extract the default arguments, by name."""
code = func.__code__
pos_count = code.co_argcount
arg_names = code.co_varnames
arg_names = arg_names[:pos_count]
defaults = func.__defaults__ or ()
kwdefaults = func.__kwdefaults__
res = dict(kwdefa... |
def default_filter(annos, annotation):
"""default filter comparing 'time', 'text' and 'tags' parameters"""
result = []
for anno in annos:
if anno.get('time') != annotation.get('time'):
continue
if anno.get('text') != annotation.get('text'):
continue
if anno.ge... |
def _in_out_back(x: float) -> float:
"""https://easings.net/#easeInOutBack"""
c = 1.70158 * 1.525
if x < 0.5:
return (pow(2 * x, 2) * ((c + 1) * 2 * x - c)) / 2
else:
return (pow(2 * x - 2, 2) * ((c + 1) * (x * 2 - 2) + c) + 2) / 2 |
def get_metadata(output, key, mimetype=None):
"""Resolve an output metadata key
If mimetype given, resolve at mimetype level first,
then fallback to top-level.
Otherwise, just resolve at top-level.
Returns None if no data found.
"""
md = output.get("metadata") or {}
if mimetype and mime... |
def cut_off_str(obj, max_len: int) -> str:
"""Create a string representation of an object, no longer than max_len characters.
Uses repr(obj) to create the string representation. If this is longer than max_len -3
characters, the last three will be replaced with elipsis.
"""
s = repr(obj)
if len(... |
def stringify_groups(groups):
"""Change a list of Group (or skills or languages) objects into a
space-delimited string.
"""
return u','.join([group.name for group in groups]) |
def count_of_occurrences(n, p):
"""
Return Number of times 'p' occurs in n!
for eg: f(30 , 7) = 4
"""
cnt = 0
while n:
n //= p
cnt += n
return cnt |
def bisection(func, min_guess, max_guess, err_tolerance):
"""
Find the root of a function using bisection method. (Bracketing method)
arguments:
func: f(x)
min_guess: minimum x as guess
max_guess: maximum x as guess
err_tolerance: value where f(root) must be less than err_tolerance
"""
... |
def intToGreenRedColor(pInt, minValue, maxValue):
""" Red means value equals to max, green, equals to min"""
if pInt < minValue:
pInt = minValue
if pInt > maxValue:
pInt = maxValue
ratio = int(float(pInt - minValue) / (maxValue - minValue) * 255)
red_hex = hex(ratio)
green_hex... |
def smartcast(value):
"""Returns the value converted to float if possible, else string, else the
uncasted value.
"""
for test in [float, str]:
try:
return test(value)
except ValueError:
continue
# No match
return value |
def reverseComplement(read):
"""
Returns the reverse complemnt of read
:param read: a string consisting of only 'A', 'T', 'C', 'G's
"""
complementDict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
return ''.join([complementDict[c] for c in read[::-1]]) |
def concatenation(L):
""" list[tuple[int, int]] -> list[tuple[int, int]] """
return L[:2] + L[2:] |
def expand_list(_list):
"""
Convert list of '.' separated values to a nested dict.
Taken from SO article which I now can't find, this will take a list
and return a dictionary which contains an empty dict as each leaf
node.
>>> expand_list(['a', 'b.c'])
{
'a': {},
... |
def writeTable(filename, table):
"""Writes a numpy array with column names to a csv file.
Arguments:
filename (str): filename to save table to
table (annotated array): table to write to file
Returns:
str: file name
"""
with open(filename,'w') as f:
... |
def determinant(xa, ya, xb, yb, xc, yc):
"""Returns determinant of three points
"""
return (xb - xa) * (yc - ya) - \
(xc - xa) * (yb - ya) |
def simplify(row):
"""
This function simplify a string which has few space between characters.
:param row: string, a string of words
:return: ans, a string without space between characters
"""
ans = ''
for ch in row:
if ch.isalpha():
ans += ch
return ans |
def is_int(s):
""" return True if string is an int """
try:
int(s)
return True
except ValueError:
return False |
def init_selected_window_sizes(window_sizes, number_of_states):
"""Initialize a selected window sizes data structure.
:param window_sizes: The required window sizes.
:param number_of_states: The number of states.
:return: The initialized selected window sizes data structure.
"""
structure = []
... |
def prettyFormat(text):
"""If text is of the form <http://purl.obolibrary.org/obo/GO_0071554> this function returns GO:0071554
:param text: Text to be formatted
:type text: str
:rtype: str
"""
if text[0] == "<" and text[-1] == ">":
text = text[1:-1]
text = text.... |
def string_to_list(a):
"""Transform a string with coma separated values to a list of values."""
return a if isinstance(a, list) or a is None else a.split(",") |
def get_subject_url(endpoint_dict, subject):
"""Get the Ingest service url for a given subject.
Args:
endpoint_dict (dict): Dict representing the JSON response from the root Ingest service url.
subject (str): The name of the subject to look for. (e.g. 'submissionEnvelope', 'add-file-reference')... |
def has_prefix(sub_s, d):
"""
:param sub_s:
:return:
"""
for key in d:
if key.startswith(sub_s):
return True |
def is_in_bbox(x, y, bbox):
"""
Answers True or Folse if the x, y is inside the BBOX.
"""
xMin, yMin, xMax, yMax = bbox
if xMin <= x <= xMax and yMin <= y <= yMax:
return True
return False |
def make_casedir_name(label: str) -> str:
"""Create case directory name based on a label
Arguments:
label Label for case directory
Returns:
Name of case directory
"""
return f"data_{label}" |
def is_valid_combination( row ):
"""
Should return True if combination is valid and False otherwise.
Test row that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
n = len(row)
if ... |
def ffmpeg_command(images_dirname, output_filename, width, height, fps):
"""prepare a command for ffmpeg"""
command = (
"ffmpeg -y -r " + str(fps) +
" -f image2 -s " + str(width) + "x" + str(height) +
" -i " + images_dirname + "/%04d.png " +
"-threads 2 -vcodec libx264 -crf 25 -p... |
def generate_n_grams(list):
"""Prioritizes larger substrings over smaller substrings"""
list.sort(key=len, reverse=True)
concatenated = [" ".join(substring) for substring in list] #concatenated the words within the substrings cuz they were in lists before
return concatenated |
def get_dut_list(vars):
"""
API to get the list of DUT's from vars
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param vars:
:return:
"""
if vars and "dut_list" in vars:
return vars.dut_list
return [] |
def get_fraction(number: int) -> float:
"""
Return the fraction associated with a fractional part.
>>> get_fraction(9)
0.9
>>> get_fraction(123)
0.123
>>> get_fraction(1)
0.1
"""
if number < 0:
raise Exception("Number should be a positive integer... |
def rescale_between(workload, minimum=0, maximum=200):
"""Re-scales the given workload, which is expected to be between -1 and 1,
so that it becomes between the given minimum and maximum values.
Arguments:
``workload``: the normalized workload to rescale (it is not modified)
``minimum``: th... |
def _clean(request_body):
""" Removes unused text from the request body for proper parsing.
For example: AnimalsCollectRequest(ids:[1,2,3]) --> ids:[1,2,3]
:param request_body: the request body
:type request_body: str
:returns: a cleaned request_body that is simpler to parse
:rtype: str
"... |
def is_xblock_an_assignment(xblock):
"""
Takes in a leaf xblock and returns a boolean if the xblock is an assignment.
"""
graded = getattr(xblock, 'graded', False)
has_score = getattr(xblock, 'has_score', False)
weight = getattr(xblock, 'weight', 1)
scored = has_score and (weight is None or ... |
def keywords(l):
"""
Accepts list of strings to use in keywords.
Separated by spaces
Ex: keywords(l = ['helpdesk', 'IT'])
"""
_ = 'keywords='
list1 = l.split()
if len(list1) == 1:
return _ + list1[0]
else:
return _ + '%20'.join(list1) |
def validate_parcel_data(parcel):
""" this funtion validates the parcel data """
# Check for empty parcel_name
if parcel['parcel_name'] == '':
return {'warning': 'parcel_name is a required field'}, 400
# Check for empty pickup_location
elif parcel['pickup_location'] == ' ':
ret... |
def parse_req(spec: str) -> str:
""" Parse package name==version out of requirments file"""
if ";" in spec:
# remove restriction
spec, _ = [x.strip() for x in spec.split(";", 1)]
if "#" in spec:
# remove comment
spec = spec.strip().split("#")[0]
if "\\" in spec:
#... |
def _is_closed_by_author(pr):
"""If the author closed the PR themselves we ignore it."""
if not pr['author']:
return False
if pr['state'] != 'CLOSED':
return False
timeline = pr.get('timelineItems')
if not timeline:
return False
open_login = pr['author'].get('login')
... |
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{bytes:.2f}{unit}{suffix}"
bytes /= factor |
def imxy2kxy(x, y, x0, y0, fx, fy):
"""
Conversion from Cartesian coordinate in binned image (x, y) to momentum coordinates (kx, ky).
**Parameters**\n
x, y: numeric, numeric
Components of the Cartesian coordinates.
x0, y0: numeric, numeric
Origins of the Cartesian coordinates.
f... |
def get_rgrids(max_value, rgrid_count):
"""Calculate radial grid steps and return it as a list"""
import math
digits = math.floor(math.log(max_value, 10))
scale = max_value / (10**digits)
ubound = math.ceil(scale) * (10**digits)
step = ubound / (rgrid_count+1)
return list(step * i for i ... |
def check_operation_once(matrix):
"""
Check if the solution violates the operation once constraint.
Returns True if the constraint is violated.
Keyword arguments:
matrix (List[List[int]]): Matrix of x_i,t values
"""
for x_it_vals in matrix:
if sum(x_it_vals) != 1:
... |
def get_number(s):
""" Check that s is number
In this plugin, heatmaps are created only for columns that contain numbers. This
function checks to make sure an input value is able to be converted into a number.
Inputs:
s - An input string or number
Outputs:
value - Either float(s... |
def count_trees(area_data: list, down: int, right: int) -> int:
"""Count the trees you would hit on a straight trajectory
:param area_data: List containing a map of tree locations
:param down: Number of units down per step
:param right: Number of units right per step
:return: Total number of trees ... |
def wellek_to_f2(eps, n_groups):
"""Convert Wellek's effect size (sqrt) to Cohen's f-squared
This computes the following effect size :
f2 = 1 / n_groups * eps**2
Parameters
----------
eps : float or ndarray
Wellek's effect size used in anova equivalence test
n_groups : int
... |
def func(a, b, c=0):
""" just something to do """
return(a, b, c) |
def generate_avro_schema(data_name: str, layer: str, list_dict_cols: list) -> dict:
"""
list_dict_cols:
[{'name': 'id', 'type': 'long', 'comment': 'oracle: ear_nro_arquivo'},
{'name': 'text', 'type': 'string', 'comment': 'oracle: ear_arquivo'}]
"""
avro_schema = {
"type": "recor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.