content stringlengths 42 6.51k |
|---|
def set_log_range(module, releases, earlier, later, releases_list):
"""
Set range to get logs for from parsed args or defaults if not given.
Args:
module(str): Module to get logs for
releases(list of str): Releases range
earlier(str): Specified start point
later(str): Specif... |
def thing_name(topic):
"""Get thing name from provided shadow topic"""
return topic.split("/")[2] |
def transpose_result_data(result_files):
"""Reassociate data from multiple result files into single categories.
We reorganize the data so that we can compare results on the same
category across multiple result files.
"""
categories = {}
for result_file in result_files:
for key, value i... |
def merge_sequence(dcts):
""" merge a sequence of dictionaries
"""
merged_dct = {}
for dct in dcts:
merged_dct.update(dct)
return merged_dct |
def either_dict_or_kwargs(
pos_kwargs,
kw_kwargs,
func_name,
):
"""Clone from xarray.core.utils."""
if pos_kwargs is not None:
if not hasattr(pos_kwargs, "keys") and hasattr(pos_kwargs, "__getitem__"):
raise ValueError("the first argument to .%s must be a dictionary" % func_name)... |
def dict_of_relay_gens(relays, gens):
"""
Create dictionaries of the gen keys from the
relay elements
"""
relay_gens = {k: list() for k in relays.keys()}
for gen_name, gen in gens.items():
gen_relay_mappings = gen['relay']
for r in gen_relay_mappings:
relay_gens[r].a... |
def twoscompl16(x):
"""Returns the reciprocal of 16-bit x in two's complement."""
return ((x ^ 0xffff) + 1) & 0xffff |
def SumMultipleDigits(ll,nd):
""" sum of multiple digits >>int32, each number is put in a row list """
s=[]
sumStr='' #make sure it is NOT same name with funciton sum!!!
base=10
for col in range(len(ll[0])):
s.append( sum([ll[row][col] for row in range(len(ll)) ]) )
for i i... |
def get_cdo_weights_filename(method, input_sampling, output_sampling):
"""Generate the filename where to save the CDO interpolation weights."""
# Normalization option
# Nearest_neighbor option
filename = "CDO_" + method + "_weights_IN_" + input_sampling + "_OUT_"+ output_sampling + ".nc"
return fi... |
def remove_dashes_from_string(str):
"""Function to remove dashes from a string and return the updated string
Args:
str (String): Input string
Returns:
String: Output String without dashes
"""
return str.replace('-', '').lower() |
def addParam(baseLength: int, sqlBase, sqlToAdd, separator: str = ", "):
"""concatenates text with separator if the text length is longer than specified"""
if len(sqlBase) > baseLength:
sqlBase += separator
return sqlBase + sqlToAdd |
def isEnabled(newStates, enable, estopState):
"""
Function to handle enable and estop states. it was getting annoying to look at.
"""
enable = True
# # to reset after estop left and right bumper buttons - press together to cancel estop
# if newStates["trigger_l_1"] == 1 and newStates["trigger_r... |
def num_or_str(x):
"""The argument is a string; convert to a number if
possible, or strip it.
"""
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return str(x).strip() |
def sub_inplace(X, varX, Y, varY):
"""In-place subtraction with error propagation"""
# Z = X - Y
# varZ = varX + varY
X -= Y
varX += varY
return X, varX |
def seq2xyz(seq_arr):
"""
Convert octomap sequence (0..7) into XYZ coordinate
:param seq_arr: list of parent-child sequences for one of given type (free, occupied, unknown)
:return: list of XYZ boxes with their "size category" (shorted the sequence bigger the voxel)
"""
xyz = []
if len(seq_a... |
def binary_to_string(num):
"""
This solution is a straight python implementation of Gayle's solution
in CtCI.
"""
if num >= 1 or num <= 0:
return 'ERROR'
binary = []
binary.append('.')
while num > 0:
#Setting a limit on length: 32 characters
if len(binary) >= 32:... |
def kinetic_energy(m, v):
"""
Calculate and return the value of kinetic energy using given values of the params
How to Use:
Give arguments for m and v params
*USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE
IT'LL BE HARD TO UNDERSTAND AND USE.'
Parameters... |
def up_to_first_space(s):
"""Return the substring of s up to the first space, or all of s if it does
not contain a space."""
i = s.find(' ')
if i == -1:
i = len(s)
return s[:i] |
def parent_from_gff_comment(commentline):
"""
takes a comment string from a gff file and returns the parent sequence ID
"""
style = ""
temp = ""
if "Parent=" in commentline:
temp = [x.strip() for x in commentline.split(";")
if x.strip().startswith("Parent=")][0].repla... |
def base64_to_data_uri(img_base64_str):
"""For display in html.
"""
datauri = "data:image/jpeg;base64," + img_base64_str
return datauri |
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (typ... |
def array_to_string(solution: str) -> str:
"""
Print the solution array as a string
solution:
return: string showing where to put the digits 1-9
"""
sol_string = '\n'.join(
' '.join(
[
str(num)
for num
in row
]
... |
def married_type(mdata):
"""return whether there are modulators or durations
(need only check first non-empty element, as consistency is required)
return a bit mask:
return 0 : simple times
return 1 : has amplitude modulators
return 2 : has duration modulators
... |
def parse_sph_header( fh ):
"""Read the file-format header for an sph file
The SPH header-file is exactly 1024 bytes at the head of the file,
there is a simple textual format which AFAIK is always ASCII, but
we allow here for latin1 encoding. The format has a type declaration
for each field a... |
def make_path(d, *paths):
"""Create nested dictionaries in path in dictionary
Parameters
----------
d : Dict[str, Any]
Provided dictionary
*args:
Variable length list of path segments to create if not present
Returns
-------
Dict
Dict with nested dicts ... |
def microgram_to_grams(x: float) -> float:
"""Convert mass in ug to g.
Args:
x (float): Mass in ug.
Returns:
float: Mass in g
"""
return x * 10**-6 |
def a078633(n: int) -> int:
"""
https://oeis.org/A078633
>>> a078633(1)
4
>>> a078633(4)
12
>>> a078633(50)
115
"""
from math import ceil, sqrt
return (2 * n) + ceil(2 * sqrt(n)) |
def _get_paths(config_dict):
"""Return a list of all paths referenced by the config dict."""
return_list = [
config_dict["diag_table"],
config_dict["data_table"],
config_dict["forcing"],
config_dict["initial_conditions"],
]
patch_files = config_dict.get("patch_files", [])... |
def build_links(tld, region_code, states):
"""
This will build start_urls, It needs to be available before the ChipotleSpider creation
:param tld: 3rd level domain name to use for building the links e.g .co.uk
:param region_code: region is an important url param required for the search
:param state... |
def _make_choices_from_int_list(source_list):
"""
Converts a given list of Integers to tuple choices.
Returns a dictionary containing two keys:
- max_length: the maximum char length for this source list,
- choices: the list of (value, value) tuple choices.
"""
_choices = []
for value in... |
def get_value(configobj, path):
"""
Returns the value specified by the full path to the key (specified as an
iterable). Returns None if the key does not exist.
"""
for i in range(0, len(path) - 1):
configobj = configobj.get(path[i], {})
return configobj.get(path[-1], None) |
def parse_atrv(v):
"""
Parses the battery voltage and returns it in [Volt] as float with 1 decimal place
:param str v: e.g. "12.3V"
:return float:
"""
try:
return float(v.replace('V', ''))
except ValueError:
return None |
def _applyPadding(dims, rect, padding):
""" Apply padding to each side of a rectangle based on width and height percentage. """
assert len(dims) == 3
img_h, img_w, _ = dims
left, right, top, bottom = rect
box_h = bottom - top
box_w = right - left
# Apply bounded padding.
left = max(0, left - int(paddi... |
def divide(a, b):
"""Divide two numbers and return the quotient"""
#Perform the division if the denominator is not zero
if b != 0:
quotient = round(a/b, 4)
print("The quotient of " + str(a) + " and " + str(b) + " is " + str(quotient) + ".")
return str(a) + " / " + str(b) + " = " + st... |
def list_of(_list, _class):
"""
Chequea que la lista _list contenga elementos del mismo tipo, desciptos en _class.
Args:
- _list:
- list().
- Lista de elementos sobre la que se desea trabajar.
- El argumento solo acepta objetos de class list.
- _class:
... |
def get_pos_flds(region):
""" return chrom, start, end from genomic region chr:start-end"""
chrom, span = region.split(':')
start, end = span.split('-')
return chrom, start, end |
def collect_parameters(px):
"""Return `set` of parameters from `px`."""
c = set()
c.update(d['a'] for d in px.values())
c.update(d['b'] for d in px.values())
assert len(c) == 2 * len(px), (c, px)
return c |
def create_headers(bearer_token):
"""
Parameters
----------
bearer_token : str
Twitter bearer token
"""
headers = {"Authorization": "Bearer {}".format(bearer_token)}
return headers |
def null_empty(dict, key):
"""
Function that checks if the a key exists in the dict and the value is not empty
:return: true or false
"""
if key in dict:
return False
return True |
def urlify_pythonic(text, length):
"""solution using standard library"""
return text[:length].replace(" ", "%20") |
def toFENhash(fen):
""" Removes the two last parts of the FEN notation
"""
return ' '.join(fen.split(" ")[:-2]) |
def num_dir(direction):
"""
Converts a direction input to a number, in which Input = 0 and Output = 1.
:param direction:
:return:
"""
return {'Input': 0,
'Output': 1,
'input': 0,
'output': 1,
0: 0,
1: 1,
'0': 0,
... |
def dble_pwr_law(time_bins, tau, alpha, beta, factor=1):
"""
Double Power Law star formation history
Parameters
----------
time_bins: list or numpy.ndarray
Time bins
tau: float or int
alpha: float or int
beta: float or int
factor: float or int, optional
Default = 1
... |
def pad_sentences(sentences, maxlen=56, padding_word="<PAD/>"):
"""
Pads all sentences to the same length.
Returns padded sentences.
"""
sequence_length = maxlen # max(len(x) for x in sentences)
padded_sentences = []
for i in range(len(sentences)):
sentence = sentences[i]
nu... |
def convert_to_base(decimal_number, base, digits):
"""Converts decimal numbers to strings of a custom base using custom digits."""
if decimal_number == 0:
return ''
return digits[decimal_number % base] + convert_to_base(decimal_number // base, base, digits) |
def _measureType(x):
"""Takes Numeric Code and returns String API code
Input Values: 1:"Base", 2:"Advanced", 3:"Misc", 4:"Four Factors", 5:"Scoring", 6:"Opponent", 7:"Usage"
Used in:
"""
measure = {1:"Base", 2:"Advanced", 3:"Misc", 4:"Four Factors", 5:"Scoring", 6:"Opponent", 7:"Usage"}
try:
... |
def unique_ancestors(node):
"""
Returns the list of all nodes dominating the given node, where
there is only a single path of descent.
"""
results = []
try:
current = node.parent()
except AttributeError:
# if node is a leaf, we cannot retrieve its parent
return result... |
def google_street_view_url(lat, lon):
"""
Generate a Google Street View URL for a given lat/lon.
Documentation:
https://developers.google.com/maps/documentation/urls/get-started#street-view-action
"""
return f"https://www.google.com/maps/@?api=1&map_action=pano&viewpoint={lat},{lon}" |
def fromBinary( s ):
""" s is a string of 0's and 1's """
if s == '': return 0
lowbit = ord(s[-1]) - ord('0')
return lowbit + 2*fromBinary( s[:-1] ) |
def combine_lists(list_of_lists):
"""Produce all combinations of one word from each list in input list of lists
The key principle is to think only about combining this list with all previous ones,
assuming those have already been dealt with. I.e. an inductive solution.
"""
list_size = len(list_of_lists)
t... |
def mapped_opts(v):
"""
Used internally when creating a string of options to pass to
Maxima.
INPUT:
- ``v`` - an object
OUTPUT: a string.
The main use of this is to turn Python bools into lower case
strings.
EXAMPLES::
sage: sage.calculus.calculus.mapped_opts(True)
... |
def process_comment(repo_type, host_usernames, comment):
""" Helper function to process a comment.
This function processes the comment JSON to get the comment path,
creation date, comment author, and comment text.
Args:
repo_type: The repository type.
host_usernames: A set containing a... |
def solved(values):
"""Checks if a sudoku puzzle is solved or unsolvable, returns -1 if unsolvable, 1 if solved and 0 if not solved"""
for u in values:
if len(values[u]) < 1:
return -1
elif len(values[u]) > 1:
return 0
return 1 |
def deleteForbiddenCharacters(filename: str):
"""
Removes forbidden characters from filename
"""
FORBIDDEN_CHARS = {'<', '>', ':', '"', '/', '\\', '|', '?', '*'}
return ''.join(c for c in filename if c not in FORBIDDEN_CHARS) |
def deepupdate(original, update):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
:param update:
:param original:
"""
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
... |
def read_user_header(head):
"""
The 'User-Id' header contains the current online user's id, which is an integer
-1 if no user online
:param head: the request's header
:return: online user's id, abort type error if the header is not an integer.
"""
try:
return int(head['User-Id'])
... |
def mkrows(l, pad, width, height):
"""
Compute the optimal number of rows based on our lists' largest element and
our terminal size in columns and rows.
Work out our maximum column number by dividing the width of the terminal by
our largest element.
While the length of our list is greater than... |
def _count_substr(stack, needle):
"""
Counts occurrences of needle in stack.
Example: in aaaa there are 3 occurrences of aa
"""
count = 0
for i in range(len(stack) - len(needle) + 1):
if stack[i: i + len(needle)] == needle:
count += 1
return count |
def get_api_interfaces_by_type(api_interfaces, type_str):
"""
Extract Interface API responses by type
:param api_interfaces: Interface API response
:param type_str: Type string to match
:return: Interfaces API response dict only containing type matching type_str
"""
interface_list = []
f... |
def checkInformativeHeaders(headers):
"""
Check for Informative Headers, like version disclosure.
Parameters:
headers (dict): HTTP Headers
Returns:
disclosedOnes (dict): Informative HTTP headers with disclosed version
undisclosedOnes (dict): Informative HTTP... |
def z_to_r(z, a=200.0, b=1.6):
"""Conversion from reflectivities to rain rates.
Calculates rain rates from radar reflectivities using
a power law Z/R relationship Z = a*R**b
Parameters
----------
z : float
a float or an array of floats
Corresponds to reflectivity Z in mm**6/m**... |
def optimal_cache_hit_ratio(pdf, cache_size):
"""Return the value of the optimal cache hit ratio of a cache under IRM
stationary demand with a given pdf.
In practice this function returns the probability of a cache hit if cache
is filled with the *cache_size* most popular times. This value also
cor... |
def colors(col):
"""
Returns a color. DO NOT MODIFY!!!
:param col: color number
:return: String representing a color
"""
if col == 0:
return "turquoise"
elif col == 1:
return "lightblue"
elif col == 2:
return "lightgray"
elif col == 3:
return "violet" |
def merge_dict(dict1, dict2):
"""Merges two dictionaries."""
dict_merged = {}
for (key1, value1), (key2, value2) in zip(dict1.items(), dict2.items()):
if type(value1) is list:
dict_merged[key1] = value1 + value2
else:
if key1 == 'user_label' and value1 == value2:
dict_merged[key1] = value1
else:
... |
def class_name_to_function_name(name):
"""Convert a python class name in CamelCase to a lower case function_name with underscores."""
function_name = ""
for char_idx, char in enumerate(name):
if char == char.upper() and char_idx > 0 and name[char_idx - 1] == name[char_idx - 1].lower():
f... |
def increase_version_number(version_number: str, version_part: str) -> str:
"""Increment the current version number according to SemVer type.
Args:
version_number (str): Current version number
version_part (str): SemVer version part, one of `patch`, `minor` or `major`
Returns:
str:... |
def contrast_reflectance(signal, reference):
"""Return '(signal - reference) / (signal + reference)'."""
return (signal - reference)/(signal + reference) |
def extract_qword(question):
"""
Function used to extract question word in question sentence
Question words: who | which
"""
if 'who' in question.lower():
return 'who'
elif 'which' in question.lower():
return 'which'
return None |
def getAllCompetences(dictionary, competences=[]):
"""
Gets all competences and synonyms in competence dictionary without
hirarchical list
"""
for competence in dictionary:
competences.append(competence['competence'])
if 'synonyms' in competence:
for synonym in competence... |
def comp(val, size=8):
""" Returns the one's complement of a positive number """
return (2**size) - 1 - val |
def coords_to_simbad(ra, dec, search_radius):
"""
Get SIMBAD search url for objects within search_radius of ra, dec coordinates.
Args:
ra (float): right ascension in degrees
dec (float): declination in degrees
search_radius (float): search radius around ra, dec in arcseconds
Ret... |
def temp_check(temp_source, temp_sink, condition):
"""
function determining if source can provide heat for a sink.
:param temp_source: temperature of the heat source.
:type temp_source: float.
:param temp_sink: temperature of the heat sink.
:type temp_sink: float.
:param condition: determin... |
def create_table(
name, num_pages, tuple_size, index_type="none", is_sorted=False,
clustered=False, clustering_factor=0, primary_index=False):
"""
Creates a table (as a dict) and returns it as a pair where the first
element in the pair is the table name and the second element is the
tabl... |
def factorial(num):
"""
Factirial of a number : input a number and it returns its factirial
"""
if num==1:
return 1
else:
return num * factorial(num -1) |
def base_convert(n, base):
"""
convert 10 base number to any base number
"""
result = ""
while True:
tup = divmod(n, base)
result += str(tup[1])
if tup[0] == 0:
return result[::-1]
else:
n = tup[0] |
def html_decode(s):
"""
Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like <p>.
"""
html_codes = (
("'", '''),
('"', '"'),
('>', '>'),
('<', '<'),
('&', '&')
)
for code in html_code... |
def hosts_to_dictionary(arg):
"""Changes list format of hosts to dictionary format. The key of the dictionary is the index
of the host. The index is defined by the host's suffix, example: overcloud-controller-10 is 10.
If there is no suffix, I use an incremented value above 1000000."""
dictionary = {}... |
def ip_range(starting_ip: str, ending_ip: str) -> list:
""" Calculates a list of IPs between two given.
:param starting_ip: Range starting IP address
:param ending_ip: Range ending IP address
:returns: List of ports between two given IPs
"""
# Create a list contaning the 4 octets f... |
def tree_size(t):
""" Returns the number of elements in a tree. """
if t is None:
return 0
else:
return 1 + tree_size(t.left) + tree_size(t.right) |
def _next_cell_number(n_horizontal, n_vertical, n, shift):
"""gives you the index of the next unit cell in the list of all unit cells
:param n_horizontal: number unit cells in x direction
:type n_horizontal: int
:param n_vertical: number of unit cells in y direction
:type n_vertical: int
:param... |
def csv_list(value):
"""
Convert a comma separated string into a list
Parameters
----------
value : str
The string object to convert to a list
Returns
-------
list
A list based on splitting the string on the ',' character
"""
if value:
result = []
... |
def op_key(op):
"""
Returns a sort key that sorts by by active and then opid.
"""
return '{0}{1}'.format('a' if op['active'] else 'i', op['opid']) |
def exception_to_dict(error):
"""Takes in an exception and outputs its details, excluding the stacktrace, to a dict
Args:
error (Exception): The exception to serialize
Returns:
dict: The serialized exception
"""
return {"type": str(type(error).__name__), "message": str(error)} |
def html_code__macro_confluence(text):
"""
Wrap into html macro
:param text:
:return:
"""
return ('''\
<ac:structured-macro ac:name="html" ac:schema-version="1">
<ac:plain-text-body><![CDATA[{text}]]></ac:plain-text-body>
</ac:structured-macro>... |
def hex_rotate_60(x, y, z, n=1):
"""Rotates the given hex n * 60 degrees counter clockwise around the origin,
and returns the co-ordinates of the new hex."""
n = n % 6
if n == 0:
return x, y, z
if n == 1:
return -y, -z, -x
if n == 2:
return z, x, y
if n == 3:
... |
def combine_sets(*sets):
"""
Combine multiple sets to create a single larger set.
"""
combined = set()
for s in sets:
combined.update(s)
return combined |
def get_N_teachers(school_type, N_classes):
"""Return the number of teachers / class for different school types."""
teachers = {
'primary':N_classes + int(N_classes / 2),
'primary_dc':N_classes * 2,
'lower_secondary':int(N_classes * 2.5),
'lower_secondary_dc':N_classes * 3,
'upper_secondary':int(N_classes *... |
def convert_coord_to_axis(coord):
"""
Converts coordinate type to its single character axis identifier (tzyx).
:param coord: (str) The coordinate to convert.
:return: (str) The single character axis identifier of the coordinate (tzyx).
"""
axis_dict = {"time": "t", "longitude": "x", "latitude"... |
def _check_start_normalize(start, ndim):
"""check and normalize start argument for rollaxis."""
if start < -ndim or start > ndim:
raise ValueError(
f"For rollaxis, start {start} is out of bounds. Ranging from {-ndim} to {ndim} is allowed.")
if start < 0:
start = start + ndim
... |
def stringBits(words):
"""
Function to skip a letter in the string.
Given a string, return a new string made of every other character starting
with the first, so "Hello" yields "Hlo".
Args:
words (String): String provided by user
Return:
result (String): String with every other... |
def is_caught(layers, positions, layer):
"""Check if you are caught on layer."""
return layer in layers and positions[layer] == 0 |
def _merge(lst1: list, lst2: list) -> list:
"""Return a sorted list with the elements in <lst1> and <lst2>.
Precondition: <lst1> and <lst2> are sorted.
"""
index1 = 0
index2 = 0
merged = []
while index1 < len(lst1) and index2 < len(lst2):
if lst1[index1] <= lst2[index2]:
... |
def compare_samples(act_samples, vcf_samples):
"""
Compare samples from activity file and vcf file.
Return only samples in both as a list and delete those not found in both from the act_samples dict.
Args:
act_samples (dict): {(act_sample_names (str)): sample_indices (int)}
vcf_samples... |
def MINSN(LX, X, XMIN, INDEX):
"""
MINSN find the minimum element of an array, taking into account the algebraic signs of the elements.
p. 21
"""
INDEX = 0
for I in range(LX):
if (X[INDEX] > X[I]):
INDEX = I
XMIN = X[INDEX]
return (XMIN, INDEX) |
def check_range(index, value):
"""
Checks if the selected gene of the unit are is in the right range
:param index: Index of the gene (int) in one unit
:param value: Value of the gene (int) in one unit
:return: true/false - if the selected gene is in the right range
"""
if index == 0:
... |
def int_to_date(date):
"""
Transform date to string
"""
nbr_years = int(date)
nbr_months = int((date - nbr_years)*12)
maturity_string = ''
if nbr_years != 0:
if nbr_years > 1:
maturity_string += str(nbr_years) + ' Years'
else:
maturity_string += str(n... |
def calcul_acc(labels, preds):
"""
a private function for calculating accuracy
Args:
labels (Object): actual labels
preds (Object): predict labels
Returns:
None
"""
return sum(1 for x, y in zip(labels, preds) if x == y) / len(lab... |
def pyimpl_apply(fn, *varargs):
"""Implementation for macro apply."""
args = []
kwargs = {}
for vararg in varargs:
if isinstance(vararg, dict):
kwargs.update(vararg)
else:
assert isinstance(vararg, tuple)
args.extend(vararg)
return fn(*args, **kwar... |
def get_sec(time_str):
"""Get mins from time."""
h, m = time_str.split(':')
return int(h) * 60 + int(m) |
def decimalToAlphabetical(index):
"""
Converts int to an alphabetical index. e.g.: 0 -> 'a', 1 -> 'b', 2 -> 'c', 'yama' -> 440414
:param index: int
:return: str
"""
assert isinstance(index, int) and index >= 0
from string import ascii_lowercase
alphanum = ''
index += 1 # because alp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.