content stringlengths 42 6.51k |
|---|
def std_scalar(comment, valueType='integer', option=0, **kwargs):
"""Description for standard scalar column."""
return dict(comment=comment, valueType=valueType, dataManagerType='StandardStMan',
dataManagerGroup='StandardStMan', option=option, maxlen=0, **kwargs) |
def subselect_dict_keys_diff(run_id_param_dicts):
"""Select keys from the param_dicts that actually change between configs."""
key_vals = {}
for _, param_dict in run_id_param_dicts:
for key, val in param_dict.items():
if key not in key_vals:
key_vals[key] = []
... |
def get_setting(settings, name):
"""Get a specific setting from Carbon/Django like settings."""
res = None
found = False
try:
res = settings[name]
found = True
except (TypeError, KeyError):
try:
res = getattr(settings, name)
found = True
except... |
def convert_openlayers_roi_to_numpy_image_roi(roi: list, image_height: int) -> list:
"""In both openlayers and numpy, the same roi format applies
Args:
roi (list): roi in format [x, y, width, height]
image_height (int): height of the original image from which the roi is cropped
Returns:
... |
def get_commodity(unit):
"""
Return the commodity corresponding to UNIT, or NONE if it cannot be found.
"""
commodity = None
if (unit == "kW" or unit == "kWh"):
commodity = "Electricity"
return commodity |
def forall(S, P):
"""
If P(x) is true every x in S, return True and None. If there is
some element x in S such that P is not True, return False and x.
Note that this function is NOT suitable to be used in an
if-statement or in any place where a boolean expression is
expected. For those situatio... |
def subjectTermTypeIdentifier(element):
"""
Identifies the termtype of the subject 'element' based on if it is formatted as an IRI or not
"""
if(len(str(element).split(":")) == 2 or "http" in str(element)):
return 'IRI'
elif element == 'nan':
return 'BlankNode'
else:
retu... |
def _diff_cache_subnet_group(current, desired):
"""
If you need to enhance what modify_cache_subnet_group() considers when deciding what is to be
(or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used
in modify_cache_subnet_group() to that in describe_cache_subnet_grou... |
def local_solar_time(local_time, tc):
"""
Corrects the local time to give the local solar time.
Parameters
----------
local_time : float
The local time in hours
tc : the time correction factor
Returns
-------
lst : float
The local solar time in hours.
"""
l... |
def get_required_key(key, config):
"""
Standardizes error checking for loading a key from config
"""
try:
return config[key]
except KeyError:
raise ValueError(
'"{}" is a required key in your config file.'.format(key)
) |
def report_as_table ( report ) :
"""Print a frame report
"""
table = []
for c in report:
name = c.GetName ()
passed = c.GetPass ()
all = c.GetAll ()
table.append ( ( name , passed , all ) )
return table |
def _continue_download(page_state):
"""
Tests to see if enough items have been downloaded, as calculated after a
download.
Parameters:
hits: total number of records from search
page_state: position in the download ; current page
* page_size: number of downloads per page
... |
def average(lst):
"""
Average x.distance from a list of x.
"""
sum_ = 0
for i in lst:
sum_ += i.distance
if len(lst) == 0:
return 10
return sum_ / len(lst) |
def is_sequence(arg):
""" https://stackoverflow.com/questions/1835018/how-to-check-if-an-object-is-a-list-or-tuple-but-not-string/1835259#1835259
"""
return (not hasattr(arg, "strip") and
hasattr(arg, "__getitem__") or
hasattr(arg, "__iter__")) |
def normalize_key(key):
"""Normalize part key so symbols are consecutively mapped to 0, 1, 2, ...
Parameters
----------
key : str
Part key as returned by :py:func:`string_from_array`.
Returns
-------
str
Normalized key with mapped symbols.
Examples
--------
>>>... |
def _reduce_renditions(renditions):
"""
Takes a list, *renditions*, and reduces it to its logical equivalent (as
far as renditions go). Example::
[0, 32, 0, 34, 0, 32]
Would become::
[0, 32]
Other Examples::
[0, 1, 36, 36] -> [0, 1, 36]
[0, 30, 42, 30, 42]... |
def map_attributes(properties, filter_function):
"""Map properties to attributes"""
if not isinstance(properties, list):
properties = list(properties)
return dict(
map(
lambda x: (x.get("@name"), x.get("@value")),
filter(filter_function, properties),
)
) |
def pixel_scale_from_data_resolution(data_resolution):
"""Determine the pixel scale from a data_type resolution type based on real observations.
These options are representative of LSST, Euclid, HST, over-sampled HST and Adaptive Optics image.
Parameters
----------
data_resolution : str
A ... |
def GetPlural(name):
"""Do an English-sensitive pluralization.
So far this supports only label names, which are all pretty simple. If you
need to support other endings, e.g. 'y', just add cases here. See
http://www.csse.monash.edu.au/~damian/papers/HTML/Plurals.html for tips.
Args:
name: A string cont... |
def group_overlapping_intervals(intervals, ends_overlap=True, return_indices=False):
"""Groups intervals (1D segments) together into groups of overlapping intervals.
Intervals will be in different groups only if they are not overlapping.
Overlapping is defined as:
if `ends_overlaps` is True:
... |
def getParsingFormat(interval):
"""Attempts to find a suitable parsing format string for a HH:MM:SS, MM:SS or SS -style time interval."""
timeParts = len(interval.split(":"))
if timeParts == 1:
return "%S"
elif timeParts == 2:
return "%M:%S"
elif timeParts == 3:
return "%H:%M:%S"
else:
return No... |
def fixup(line):
"""Account for misformatted data from FFIEC with one-off fixups"""
if line[0] == "2016" and line[1] == "0000021122" and len(line) == 23:
return line[:6] + line[7:]
return line |
def _get_1d_shape(in_shape):
"""helper function for Grad TopK"""
out_shape = 1
for i in in_shape:
out_shape *= i
return (out_shape,) |
def convert(orig: str, to: str) -> float:
"""Convert a string to a specific type of number
Parameters
----------
orig : str
String to convert
Returns
-------
number : float
Decimal value of string
"""
clean = orig.replace("%", "").replace("+", "").replace(",", "")
... |
def complementary_dna(dna_sequence):
"""Create a complementary DNA sequence."""
cDNA = []
complementary = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
for nucleotide in dna_sequence:
try:
cDNA.append(complementary[nucleotide])
except KeyError:
cDNA.append('X')
# ... |
def _fractional_tune(tune: float) -> float:
"""
Return only the fractional part of a tune value.
Args:
tune (float): tune value.
Returns:
The fractional part.
"""
return tune - int(tune) |
def is_ssn(value):
"""
Test whether a number is between 0 and 1e9.
Note this function does not take into consideration some special numbers that are never allocated.
https://en.wikipedia.org/wiki/Social_Security_number
"""
if type(value) is int:
return 0 < value < 1e9
elif type(valu... |
def findUniqueContours(inlist):
""" Find list of unique contours"""
uniqueContourList = []
for item in inlist:
if item not in uniqueContourList:
uniqueContourList.append(item)
return uniqueContourList |
def datos_partida(usuario,puntaje_logrado,tiempo_jugado):
"""
recibe datos de la partida y retorna un diccionario con
el nombre de usuario y los datos de la partida jugada cargados"""
config = usuario["configuracion"]
niveles = ["facil", "medio", "dificil"]
return {
"nombre": usuario["... |
def sort_dict_by_value(d, increase=True):
"""sort dict by value
Args:
d(dict): dict to be sorted
increase(bool, optional): increase sort or decrease sort. Defaults to True.
Returns:
[type]: [description]
Examples:
>>> d = Dict()
>>> d.sort_dict_by_value({"a": 1... |
def is_symbol_char(char):
""" True if `char` is a symbol. """
# Also used by s2eapp_simplified_image.
result = char in "[]<>.-+/%=~*&|"
return result |
def check_path(path):
"""
file path should be a relative path without ".." in it
:param path: file path
:return: true if the path is relative and doesn't contain ".."
"""
return not path.startswith("/") and ".." not in path |
def list_of_values(dictionary, list_of_keys, default=None):
"""
Converts a dict to a list of its values,
with the default value inserted for each missing key::
>>> list_of_values({"a":1, "b":2, "d":4}, ["d","c","b","a"])
[4, None, 2, 1]
>>> list_of_values({"a":1, "b":2, "d":4}, ["d... |
def rectContains(rect, pt):
"""
This function checks if the point is inside the bounding box
:param rect: The bounding box of the object
:param pt: Point to check it's position
:return: True or False logic
"""
logic = rect[0] < pt[0] < rect[0] + rect[2] and rect[1] < pt[1] < rect[1] + rect[... |
def swap(items, a, b):
"""swap between list/dict items values"""
items[a], items[b] = items[b], items[a]
return items |
def reverse(sequence):
"""
Reverse a string
Args:
sequence (string): Sequence to reverse
Returns:
string: The reversed sequence
"""
return sequence[::-1] |
def _arg_attr(identifier, attr1, attr2):
"""Helper method for tlink_arg{1,2}_attr that checks the identifier."""
return attr1 if identifier.startswith('t') else attr2 |
def flatten(configs):
"""
Parsing the received Json config file (removing metrics key and spread them in parent key).
:param configs: Received configs from Django admin.
:return:
"""
flatten_configs = []
for conf in configs:
parent = {}
for key, val in conf.items():
... |
def find_the_key(dictionary, target_keys):
"""Function to pull out the keys of a dictionary as a list."""
return {key: dictionary[key] for key in target_keys} |
def to_camel(name):
"""
Converts snake_case strings to camelCase.
"""
first, *rest = name.split("_")
return first + "".join(word.capitalize() for word in rest) |
def truncate_string(s, limit=140):
"""Truncate a string, replacing characters over the limit with "...".
"""
if len(s) <= limit:
return s
else:
# Try to find a space
space = s.rfind(' ', limit - 20, limit - 3)
if space == -1:
return s[:limit - 3] + "..."
... |
def euler(n=10):
"""
Function to compute Euler's number, :math:`e` using a Taylor series
.. math::
e = 1 + \\sum_n^\\infty \\frac{1}{n!}
Parameters
----------
n : int, Optional, default: 10
Order of expansion for the Taylor series
Returns
-------
e : float
... |
def _strip_whitespace_basic(value):
"""Strip whitespace from the start and end of `value`"""
if value is not None and hasattr(value, "strip"):
return value.strip()
return value |
def f(n):
""" int -> list[int]"""
# L : list[int]
L = []
for _ in range(0, n):
L.append(42)
return L |
def return_struct_row_address(address):
"""Data structure return function."""
return {'to_address': address,
'log': [],
'queue_count': 0,
'status': "new",
'is_tagged': False,
'hits': 0,
'verdict': {'FILTER_LIST': {}}} |
def removeDuplicates(a_list: list) -> list:
"""
Removes duplicates from a list and returns it.
Type needs to implement __eq__
"""
return list(dict.fromkeys(a_list)) |
def negate_tuple(tmp: tuple) -> tuple:
"""
Reversing tuple values.
"""
return -tmp[0], -tmp[1], -tmp[2] |
def get_item(dictionary, key): # pragma: no cover
"""
Needed because there's no built in .get in django templates
when working with dictionaries.
:param dictionary: python dictionary
:param key: valid dictionary key type
:return: value of that key or None
"""
return dictionary.get(key) |
def extend(value, length):
""" Extends a string value to an exact size """
remainder = length - len(value)
value += b''.join([b'\x00' for _ in range(remainder)])
value = value[:length]
return value |
def twos_comp(val, mode="short"):
"""compute the 2's complement of int value val
"""
if mode =="byte":
bit = 8
elif mode =="short":
bit = 16
elif mode== "long":
bit = 32
else:
raise ValueError("cannnot calculate 2's complement")
if (val & (1 << (bit - 1))) != ... |
def correctString(string, includeSpaces = True, replace = None):
"""
Changes invalid characters.
:param string: str
:param includeSpaces: if True string includes spaces, else suppress them
:param replace: use replace character for invalid
:return: corrected string
"""
parts = []
for... |
def contains_filter_phrases(description, filter_phrases):
"""
Returns True if any phrase in filter_phrases is also in description.
"""
if isinstance(description, float):
contains = False
else:
contains = any([phrase.lower() in description.lower() for phrase in filter_phrases]) ... |
def format_bad_blocks(bad_blocks):
"""Prints out block results in rows"""
return "\n".join(sorted([str(b).replace("\\", "/") for b in bad_blocks])) |
def match(pattern,word):
"""Check if a word matches pattern
Implements a very simple pattern matching algorithm, which allows
only exact matches or glob-like strings (i.e. using a trailing '*'
to indicate a wildcard).
For example: 'ABC*' matches 'ABC', 'ABC1', 'ABCDEFG' etc, while
'ABC' only m... |
def levenshtein_distance(y_true, y_pred):
"""
:param y_true:
:param y_pred:
:return:
"""
edit_distance = 0
return edit_distance |
def correct_output(luminosity):
"""
:param luminosity: Input luminosity
:return: Luminosity limited to the 0 <= l <= 255 range.
"""
if luminosity < 0:
val = 0
elif luminosity > 255:
val = 255
else:
val = luminosity
return round(val) |
def carbonblack_ingress_event_regmod(rec):
"""CarbonBlack Ingress Event Regmod Matched MD5"""
return rec['md5'] == '0E7196981EDE614F1F54FFF2C3843ADF' |
def slice_(array, start=0, end=None):
"""Slices `array` from the `start` index up to, but not including, the
`end` index.
Args:
array (list): Array to slice.
start (int, optional): Start index. Defaults to ``0``.
end (int, optional): End index. Defaults to selecting the value at
... |
def average(iterable):
"""Returns the average value of the iterable."""
return sum(iterable) / float(len(iterable)) |
def gainceiling (val=None):
""" Set or get gain ceilling """
global _gainceiling
if val is not None:
_gainceiling = val
return _gainceiling |
def fix_dups(mylist, sep="", start=1, update_first=True):
"""
https://stackoverflow.com/a/68916219/5168563
"""
mylist_dups = {}
# Build dictionary containing val: [occurrences, suffix]
for val in mylist:
if val not in mylist_dups:
mylist_dups[val] = [1, start - 1]
el... |
def get_dict_key(dictionnary, value):
""" Returns the first key associated to value in dictionnary """
for key, val in dictionnary.items():
if val == value:
return key
return None |
def check_is_const_int(x, op_name, arg_name):
"""check whether x is const int."""
if x is None:
raise TypeError(f"For '{op_name}', the '{arg_name}' should be a const int number, but got not const.")
if not isinstance(x, int):
raise TypeError(f"For '{op_name}', the '{arg_name}' should be a co... |
def to_unicode(data):
"""
Get a string and make it Unicode
@zc00l
"""
out = ""
for char in data:
out += char + "\x00"
return out |
def error_rate(substitution_rate_value=0.0, deletion_rate_value=0.0, insertion_rate_value=0.0):
"""Error rate
Parameters
----------
substitution_rate_value : float >=0
Substitution rate.
Default value 0
deletion_rate_value : float >=0
Deletion rate.
Default value 0
... |
def replace_question_with_best_guess(text):
"""Somewhere in NiH's backend, they have a unicode processing problem.
From inspection, most of the '?' symbols have quite an intuitive origin,
and so this function contains the hard-coded logic for inferring
what symbol used to be in the place of each '?'.
... |
def linear_decay(
start: float, end: float, start_time: int, end_time: int, trade_time: int
) -> float:
"""
Simple linear decay function. Decays from start to end after end_time minutes (starts after start_time minutes)
"""
time = max(0, trade_time - start_time)
rate = (start - end) / (end_time ... |
def GetComplementaryColor(hexStr):
"""Returns complementary RGB color
Example Usage:
>>> GetComplementaryColor('#FFFFFF')
'#000000'
"""
if hexStr[0] == '#':
hexStr = hexStr[1:]
rgb = (hexStr[0:2], hexStr[2:4], hexStr[4:6])
compColor = '#'
for a in rgb:
comp... |
def x_pct_of_number(pct, number, *, precision="2"): # pragma: no cover
"""
Calculate what is the x% of a number.
Arguments:
pct (int): percentage
number (int): number
Keyword arguments (opt):
precision (int): number of digits after the decimal point
... |
def get_urls(session, name, data, find_changelogs_fn, **kwargs):
"""
Gets URLs to changelogs.
:param session: requests Session instance
:param name: str, package name
:param data: dict, meta data
:param find_changelogs_fn: function, find_changelogs
:return: tuple, (set(changelog URLs), set(r... |
def af_to_genotypes(alt_af):
"""
Returns the Hardy Weinberg equilibrium for a given alternate pooled allele frequency
:param alt_af: [0, 1]
:return: [homozygous Reference, heterozygous, homozygous Alternate]
"""
return (1 - alt_af) ** 2, 2 * alt_af * (1 - alt_af), alt_af ** 2 |
def check_for_unassigned_atom(mol):
"""
Check there isn't a missing atom group ie. '*'
A '*' in a SMILES string is an atom with an atomic num of 0
"""
if mol is None:
return None
try:
atoms = mol.GetAtoms()
except:
return None
for atom in atoms:
if atom.... |
def round_hour(tval):
"""Round tval to nearest hour."""
return(round(tval/3600) * 3600) |
def percent_used(used, total, decimal=2):
"""
Return percent used by giving total and used value.
:param used: Used value.
:type used: Integer
:param total: Total value.
:type total: Integer
:return: Float for percent used.
:rtype: Float
"""
pused = round((100. / total) * used, ... |
def species_level(prediction):
"""Is this prediction at species level.
Returns True for a binomial name (at least one space), False for genus
only or no prediction.
"""
assert ";" not in prediction, prediction
return prediction and " " in prediction |
def replace_right(source, target, replacement, replacements=1):
"""
Replace the last occurence of a string.
:param source:
:param target:
:param replacement:
:param replacements:
:return:
"""
return replacement.join(source.rsplit(target, replacements)) |
def is_scalar(X):
"""Returns True of X is a scaler."""
try:
return(len(X.shape))==0
except:
return False |
def rel_change(exist, after):
""" The difference between the largest and smallest frames
Args:
exist: Frame currently intercepted by video.
after: Capture the next frame after video.
Returns:
The difference between frames.
"""
diff = (after - exist) / max(exist, after)
... |
def strip_quotes(s):
""" Remove surrounding single or double quotes
>>> print strip_quotes('hello')
hello
>>> print strip_quotes('"hello"')
hello
>>> print strip_quotes("'hello'")
hello
>>> print strip_quotes("'hello")
'hello
"""
single_quote = "'"
double_quote = '"'
... |
def read_maze(file_name):
"""
Reads a maze stored in a text file and returns a 2d list containing the maze representation.
"""
try:
with open(file_name) as fh:
maze = [[char for char in line.strip("\n")] for line in fh]
num_cols_top_row = len(maze[0])
for row ... |
def is_gcs_path(path):
"""Check argument string is GCS path or not
Args:
path: str
Returns:
True when string is GCS path
"""
return path.startswith("gs://") |
def jax_np_interp(x, xt, yt, indx_hi):
"""JAX-friendly implementation of np.interp.
This is a relic from before this was implemented in JAX.
Requires indx_hi to be precomputed, e.g., using np.searchsorted.
Parameters
----------
x : ndarray of shape (n, )
Abscissa values in the interpola... |
def stirling2nd2(n: int) -> int:
"""Stirling number of second kind (k = 2)
Args:
n (int): [description]
Returns:
int: [description]
"""
if n <= 2:
return 1
return 1 + 2 * stirling2nd2(n - 1) |
def checkio(game_result):
"""Given game_result, return who win or draw"""
def get_wins(gr, player):
"Return number of 'wins' for given game_result gr"
wins = 0
for row in gr:
print(row)
if row == (player * 3):
wins += 1
for col in zip(*gr... |
def is_prime(n):
"""
Trial division, should be ok for numbers less than 20 digits if prime.
"""
if n==0 or n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
... |
def get_assign_counts(line_executions, assign_counts={}):
"""Gather the assign counts for each line.
"""
for line_execution in line_executions:
metrics = line_execution['metrics']
if metrics['var_type'] != "DataFrame":
continue
assign_key = "%d:%s" % (line_execution['line... |
def exact_change_dynamic(amount,coins):
"""
counts[x] counts the number of ways an amount of x can be made in exact change out of a subset of coins
given in the list of denominations 'coins'.
Initially there are no possibilities, if no coins are allowed
>>> exact_change_dynamic(20,[50,20,10,5,2,1])
... |
def mapFunc(arg):
"""
Create `(key, value)` pairs.
You may need to modify this code.
"""
return (arg[0], 1) |
def Ql_from_Qi_Qe(Qi, Qe):
"""
1/Ql = 1/Qi+1/Qe
"""
Ql = 1/(1/Qi+1/Qe)
return Ql |
def intersects(box, new_box):
"""
Check whether two bounding boxes are intersected
:param box: one bounding box
:type box: list[int]
:param new_box: another bounding box
:type new_box: list[int]
:return: whether two bounding boxes are intersected
:rtype: bool
"""
box_x1, box_y1,... |
def remove_offset(uri_string):
"""From a SciGraph URI with offset (http://scigraph.springernature.com/things/articles/4545218dc0eb528cdc3a9f869758a907#offset_496_503) remove the offset infos"""
return uri_string.split("#")[0] |
def make_pod_body(name: str):
"""Make simple Pod body for testing"""
return {
'apiVersion': 'v1',
'kind': 'Pod',
'metadata': {'name': name},
'spec': {'containers': [{'name': "main", 'image': "busybox"}]},
} |
def toString(obj):
""" Transforme all variables to a string format"""
if type(obj) == type(()) or type(obj) == type([]):
return " ".join(map(str,obj))
else: return str(obj) |
def convex_hull(nodes):
"""collect edges that build the convex hull."""
# Get a local list copy of the nodes and sort them lexically.
points = list(nodes)
points.sort()
if len(points) <= 1:
return points
# 2D cross product of OA and OB vectors, i.e. z-component of
# their 3D cross ... |
def grid_maker(width, height):
"""Accepts width, height (ints). Returns widthxheight grid with '.' as values."""
grid = [['.' for i in range(width)] for j in range(height)]
return grid |
def _check_expressions(words, possible_match, sentence_score_factors, word_index):
"""
This method will analyze if the possible match received is right with the
text received in list of words.
If all words are in the words list and in the same order the expression is a match,
so the ... |
def commonPaths(paths):
""" Returns the common component and the stripped paths
It expects that directories do always end with a trailing slash and
paths never begin with a slash (except root).
:param paths: The list of paths (``[str, str, ...]``)
:type paths: ``list``
:re... |
def to_list(inp):
""" Convert to list """
if not isinstance(inp, (list, tuple)):
return [inp]
return list(inp) |
def _is_hd(release_name):
""" Determine if a release is classified as high-definition
:param release_name: release name to parse
:type release_name: basestring
:return: high-def status
:rtype: bool
"""
if "720" in release_name or "1080" in release_name:
return True
return False |
def isExcludedAuthorEmail(authorEmail):
""" Check if an email address is a robot
@param authorEmail email to check
"""
excludedAuthorEmails = {
"treehugger-gerrit@google.com",
"android-build-merger@google.com",
"noreply-gerritcodereview@google.com"
}
return authorEmail in excludedAuthorEmails |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.