content stringlengths 42 6.51k |
|---|
def is_say_ingredients(text: str) -> bool:
"""
A utility method to determine if the user said the intent 'say_ingredients'.
"""
exact_match_phrases = [
"ingredient", "ingredients"
]
sample_phrases = [
'say ingredient', 'tell me the ingredient', 'what are the ingredient', 'tell th... |
def strip_pem(x):
"""
Strips PEM to bare base64 encoded form
:param x:
:return:
"""
if x is None:
return None
pem = x.replace('-----BEGIN CERTIFICATE-----', '')
pem = pem.replace('-----END CERTIFICATE-----', '')
pem = pem.replace(' ', '')
pem = pem.replace('\t', '')
... |
def t48tot68(t48):
"""Convert from IPTS-48 to IPTS-68 temperature scales,
as specified in the CF Standard Name information for
sea_water_temperature
http://cfconventions.org/Data/cf-standard-names/27/build/cf-standard-name-table.html
temperatures are in degrees C"""
t68 = t48... |
def weight_path(model_path):
""" Get path of weights based on path to IR
Params:
model_path: the string contains path to IR file
Return:
Path to weights file
"""
assert model_path.endswith('.xml'), "Wrong topology path was provided"
return model_path[:-3] + 'bin' |
def check_unified_length(data):
"""
check nested list data have same length
:param data: list
:return: bool
"""
assert isinstance(data, list)
length_list = map(len, data)
if len(set(length_list)) == 1:
return True
else:
return False |
def human_addr(addr):
""" Turns a MAC address into human readable form. """
return ":".join(map(lambda a: "%02x" % ord(a), addr)) |
def create_logdir(dataset, label, rd):
""" Directory to save training logs, weights, biases, etc."""
return "dsebm/train_logs/{}/label{}/rd{}".format(
dataset,label, rd) |
def gravity_gpemgh(GPE,mass,height):
"""Usage: Find gravity from gravitational potential energy, mass and height"""
result=GPE/mass*height
return result |
def is_valid_tuple(data, length):
"""
Returns true if the tuple has the expected length and does NOT contain None values.
:param data: The tuple
:param length: The expected length
:return: True if valid, false otherwise
"""
return len(data) == length and None not in data |
def condensed_index(n, i, j):
"""
Calculate the condensed index of element (i, j) in an n x n condensed
matrix.
"""
if i < j:
return n * i - (i * (i + 1) // 2) + (j - i - 1)
elif i > j:
return n * j - (j * (j + 1) // 2) + (i - j - 1) |
def clear_cached_catalog(db_session):
"""Clear the locally cached catalog."""
try:
c = db_session.cursor()
tables = ["artists", "albums", "songs"]
for table_name in tables:
c.execute("""DELETE FROM %s""" % table_name)
db_session.commit()
c.close()
except:
... |
def klGaussian(mean_1, mean_2, sig2=1.):
"""Kullback-Leibler divergence for Gaussian distributions."""
return ((mean_1 - mean_2) ** 2) / (2 * sig2) |
def poly_export(poly):
"""Saves parts of a polytope as a dictionary for export to MATLAB.
@param poly: L{Polytope} that will be exported.
@return output: dictionary containing fields of poly
"""
if poly is None:
return dict()
return dict(A=poly.A, b=poly.b) |
def remove_dict_nulls(d):
"""Return a shallow copy of a dictionary with all `None` values excluded.
Args:
d (dict): The dictionary to reduce.
"""
return {k: v for k, v in d.items() if v is not None} |
def get_pure_wordlist(tweet):
""" (str) -> list of str
Return a list of string containing all words ending with alphanumerics.
>>> get_pure_wordlist('Hello! @Leehom- @StarWay.')
['hello', '@leehom', '@starway']
>>> get_pure_wordlist('@Here: @1223 @here: me')
['@here', '@1223', '@h... |
def get_include_guard_extension(Filename):
"""Transforms the letters of a filename, so that they can appear in a C-macro."""
include_guard_extension = ""
for letter in Filename:
if letter.isalpha() or letter.isdigit() or letter == "_":
include_guard_extension += letter.upper()
el... |
def prep_docs_for_assesment(docs, labels):
"""
Sorts training docs into groups by their respective topics. Used for "gueesing: which model topic index belongs
to which real topic id.
:param training_docs: if not provided training docs from initialization will be used otherwise no action
will be perf... |
def amz_user_grant(user_id, name, permission):
"""
Returns XML Grant for user.
:param user_id: user id
:param name: user name
:param permission: permission value
"""
grant = (
'<Grant>'
'<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
'xsi:type="Cano... |
def merge_dictionaries(base, primary):
"""
:param base: dictionary to replace values with
:param primary: dictionary whose values we care about most
:return: merged dictionary
"""
# create the dictionary if we pass a None
base = base or {}
primary = primary or {}
merged = base.copy(... |
def unflatten(dictionary):
"""Unflattens a dictionary by splitting keys at '.'s.
This function unflattens a hierarchical dictionary by splitting
its keys at '.'s. It is used internally for converting the
configuration dictionary to more convenient formats. Implementation was
inspired by `this Stack... |
def revcomp(s):
"""Reverse complement function"""
comp_map = {"A": "T", "a": "t", "C": "G", "c": "g", "g": "c", "G": "C", "T": "A", "t": "a"}
return "".join(reversed([comp_map.get(x, x) for x in s])) |
def get_next_set_offset(context, matching_sets):
"""Get the set search offset for the next query."""
# Set the next offset. If we found all matching sets, set the offset to 'done'
if len(matching_sets) == 8:
return f"{context.inline_query_id}:{context.offset + 8}"
# We reached the end of the st... |
def normalize_sum(array):
"""normalize a vector to sum to 1"""
s = sum(array)
return [x / s for x in array] |
def args_and_keywords(function):
""" Return the information about the function's argument signature.
Return a list of the function's positional argument names and a
dictionary containing the function's keyword arguments.
Example:
>>> import random
>>> args, kw = arg... |
def clean_conversation(conv, x):
"""
Removes first turn
"""
return conv[1:] if x > 1 else conv |
def ru(s=""):
"""
resolve unicode and return printable string
"""
if type(s) == type(1) or type(s) == type(9999999999999999):
return s
return None if not s else s.encode('ascii', 'ignore') |
def unique(input_list):
"""Return unique value of the input list"""
try:
# intilize a null list
unique_list = []
# traverse for all elements
for x in input_list:
# check if exists in unique_list or not
if x not in unique_list:
uniqu... |
def parse_align_focus(tgt_src_align_focus):
"""Parse the input 'tgt_src_align_focus' string list."""
if isinstance(tgt_src_align_focus, str):
# for compatibility reason from legacy models
assert tgt_src_align_focus[0] == 'p' and tgt_src_align_focus[2] == 'n'
prv = int(tgt_src_align_focus... |
def sanitise_phone_number(val):
"""
We store (almost) whatever number the user provided but massage it later.
"""
return '+44%s' % val[1:] if val.startswith('0') else val |
def TypeOrVar(dart_type, comment=None):
"""Returns string for declaring something with |dart_type| in a context
where if a type is omitted, 'var' must be used instead."""
if dart_type == 'dynamic':
if comment:
return 'var /*%s*/' % comment # e.g. var /*T*/ x;
else:
re... |
def check_revealed_tile(board, tile):
"""
Function checks if a tile location contains a ship piece.
board -> the tiled board either a ship piece or none
tile -> location of tile
returns True if ship piece exists at tile location
"""
return board[tile[0][0]][tile[0][1]] != None |
def is_binary_file(path, bufsize=1024):
""" detects whether the file given in `path` is a binary file.
`bufsize` determines how many bytes of the file are checked.
The method was inspired by http://stackoverflow.com/a/7392391/932593
"""
# determine the set of binary characters or load them... |
def write_tlv(data):
"""Convert a dict to TLV8 bytes."""
tlv = b''
for key, value in data.items():
tag = bytes([int(key)])
length = len(value)
pos = 0
# A tag with length > 255 is added multiple times and concatenated into
# one buffer when reading the TLV again.
... |
def default(value, default):
"""
Returns a specified default value if the provided value is None.
Args:
value (object): The value.
default (object): The default value to use if value is None.
Returns:
object: Either value, or the default.
"""
return value if value is no... |
def contains_embedded_molfile(field_value):
"""Returns True if the RD file $DATUM field value contains an embedded
molfile, otherwise returns False."""
return field_value == '$MFMT' |
def roundf(x, precision=0):
"""Like round but works with large exponents in floats and high precision
Based on http://stackoverflow.com/a/6539677/623735
>>> 234042163./(2**24)
13.94999998807...
>>> roundf(234042163./(2**24), 5)
13.95
>>> roundf(1234.1234e-123, 5)
1.2341e-120
>>> roun... |
def _diff_list(a, b):
"""
Compares 2 lists and returns the elements in list a only
"""
b = set(b)
return [aa for aa in a if aa not in b] |
def ImagePropFromGlobalDict(glob_dict, mount_point):
"""Build an image property dictionary from the global dictionary.
Args:
glob_dict: the global dictionary from the build system.
mount_point: such as "system", "data" etc.
"""
d = {}
if "build.prop" in glob_dict:
bp = glob_dict["build.prop"]
... |
def get_ln_flag_pair_of_bit(flag_bit: int) -> int:
"""Ln Feature flags are assigned in pairs, one even, one odd. See BOLT-09.
Return the other flag from the pair.
e.g. 6 -> 7
e.g. 7 -> 6
"""
if flag_bit % 2 == 0:
return flag_bit + 1
else:
return flag_bit - 1 |
def CRRAutilityP_inv(uP, gam):
"""
Evaluates the inverse of the CRRA marginal utility function (with risk aversion
parameter gam) at a given marginal utility level uP.
Parameters
----------
uP : float
Marginal utility value
gam : float
Risk aversion
Returns
-------
... |
def deserialize_gn_args(args):
"""Deserialize the raw string of gn args into a dict."""
if not args:
return {}
args_hash = {}
for line in args.splitlines():
key, val = line.split('=')
args_hash[key.strip()] = val.strip()
return args_hash |
def checksum_raw_fletcher16(message):
"""
Fletcher16 check function. Receives a message with a checksum appended and returns 0 if message is correct and another value if not.
"""
sum1 = 0
sum2 = 0
for byte in message:
sum1 = (sum1 + byte)
sum2 = (sum1 + sum2)
sum1 %= 255
... |
def is_list(node: dict) -> bool:
"""Check whether a node is a list node."""
return 'listItem' in node |
def my_mean(inp):
"""
Calculate average of numerical values in the list
Parameters
----------
inp : list
input
"""
result = 0
count = 0
if inp:
if isinstance(inp, list):
for t in inp:
if isinstance(t, int) or isinstance(t, float):
... |
def closest_power_2(x):
""" Returns the closest power of 2 that is less than x
>>> closest_power_2(6)
4
>>> closest_power_2(32)
16
>>> closest_power_2(87)
64
>>> closest_power_2(4095)
2048
>>> closest_power_2(524290)
524288
"""
n=1
while 2**n <x:
n = n+1
... |
def to_list(root):
"""
returns a List repr of a Binary Tree
"""
def _to_list(root, acc):
if root is None:
return acc
acc.append(root.val if root.val else None)
_to_list(root.left, acc)
_to_list(root.right, acc)
return acc
return _to_list(root, []) |
def find_usable_exits(room, stuff):
"""
Given a room, and the player's stuff, find a list of exits that they can use right now.
That means the exits must not be hidden, and if they require a key, the player has it.
RETURNS
- a list of exits that are visible (not hidden) and don't require a key!
... |
def sites_to_cell(sites):
"""Get the minimum covering cell for ``sites``.
Examples
--------
>>> sites_to_cell([(1, 3, 3), (2, 2, 4)])
((1, 2, 3) , (2, 2, 2))
"""
imin = jmin = kmin = float('inf')
imax = jmax = kmax = float('-inf')
for i, j, k in sites:
imin, jmin, k... |
def sum_medians(medians):
"""
Takes a list of integers; returns a sum of all elements.
"""
sum_of_medians = 0
for m in medians:
sum_of_medians += m
return sum_of_medians |
def obj_to_list(sa_obj, field_order):
"""Takes a SQLAlchemy object - returns a list of all its data"""
return [getattr(sa_obj, field_name, None) for field_name in field_order] |
def count_words(tokenized_sentences):
"""
Count the number of word appearence in the tokenized sentences
Args:
tokenized_sentences: List of lists of strings
Returns:
dict that maps word (str) to the frequency (int)
"""
word_counts = {}
### START CODE HERE (... |
def _save_div(x, y):
"""
Args:
x:
y:
Returns:
"""
if y != 0.0:
return x / y
return x |
def _and(queries):
"""
Returns a query item matching the "and" of all query items.
Args:
queries (List[str]): A list of query terms to and.
Returns:
The query string.
"""
if len(queries) == 1:
return queries[0]
return f"({' '.join(queries)})" |
def filter_articles(raw_html: str) -> str:
"""Filters HTML out, which is not enclosed by article-tags.
Beautifulsoup is inaccurate and slow when applied on a larger
HTML string, this filtration fixes this.
"""
raw_html_lst = raw_html.split("\n")
# count number of article tags within the documen... |
def angle_in_bounds(angle, min_angle, max_angle):
"""
Determine if an angle is between two other angles.
"""
if min_angle <= max_angle:
return min_angle <= angle <= max_angle
else:
# If min_angle < max_angle then range crosses
# zero degrees, so break up test
# into t... |
def whitespace_tokenizer(s, **kwargs):
"""Tokenize on whitespace"""
token_list = s.split(' ')
return token_list |
def get_image_paras(image_paras):
"""Gets image parameters.
Args:
image_paras (dict): The dictionary containing image parameters.
Returns:
tuple: A tuple containing no_data, min_size, min_depth, interval, resolution.
"""
no_data = image_paras["no_data"]
min_size = image_par... |
def print_verilog_literal(size, value):
"""Print a verilog literal with expicilt size"""
if(value >= 0):
return "%s'd%s" % (size, value)
else:
return "-%s'd%s" % (size, abs(value)) |
def get_client_ip(request):
"""
Naively yank the first IP address in an X-Forwarded-For header
and assume this is correct.
Note: Don't use this in security sensitive situations since this
value may be forged from a client.
"""
if request:
try:
return request.META['HTTP_X... |
def triangle_area(base, height):
"""Returns the area of a triangle"""
return (base * height) / 2 |
def off_square(point, edge_length):
"""Calculate if we have jumped off the current square"""
middle_point = int(edge_length / 2)
return abs(point.real) > middle_point or abs(point.imag) > middle_point |
def sort_unique(edges):
"""Make sure there are no duplicate edges and that for each
``coo_a < coo_b``.
"""
return tuple(sorted(
tuple(sorted(edge))
for edge in set(map(frozenset, edges))
)) |
def get_pair_linear_scaling(s0,t0):
"""
Get pair for linear scaling with number of stations.
Parameters
----------
s0 : int
station id
t0 : int
polarization id
"""
pair=[str(s0),str(t0),"A","A"]
return(pair) |
def to_tensor_item(value):
"""
Transform from None to -1 or retain the initial value.
:param value: a value to be changed to an element/item in a tensor
:return: a number representing the value, tensor with value -1 represents
the None input
"""
if value is None:
value = -1.0
re... |
def sub_from_color(color, value):
"""Subtract value from a color."""
sub = lambda v: (v - value) % 256
if isinstance(color, int):
return sub(color)
return tuple(map(sub, color)) |
def get_filename(img_path):
"""
gets the filename of the image
"""
return img_path.split("/")[-1] |
def remove_star_text(input_string):
"""
Simple preprocess custom method
"""
if "star-rating" in input_string[0]:
return input_string[0].split(" ")[-1]
return input_string |
def parse_hostportstr(hostportstr):
""" Parse hostportstr like 'xxx.xxx.xxx.xxx:xxx'
"""
host = hostportstr.split(':')[0]
port = int(hostportstr.split(':')[1])
return host, port |
def fix_image_file_name(barcode, file_name):
"""
volume barcodes containing underscore, like "Cal5th_001", may have file_name incorrectly as
Cal5th_00100196_1.tif instead of Cal5th_001_00100196_1.tif. Attempt to fix by replacing
portion before first underscore with barcode. Caller should the... |
def join_strings_by_keywords(list, keywords, join=' '):
"""Join strings by keywords. Returns a new list with joined strings."""
res = []
append = False
for i, elem in enumerate(list):
if (append):
try:
res[-1] = res[-1] + join + elem
except:
... |
def get_filename(path: str):
""" Extract the file name and return it """
if type(path) != str:
return ""
chunks = path.split("/")
return chunks[-1] |
def _GetReleaseTracks(api_version):
"""Returns a string representation of release tracks.
Args:
api_version: API version to generate release tracks for.
"""
if 'alpha' in api_version:
return '[ALPHA]'
elif 'beta' in api_version:
return '[ALPHA, BETA]'
else:
return '[ALPHA, BETA, GA]' |
def reduce_structure(reduce, accumulate, *param_dicts):
""" For every element in the structure, apply the reduce operation and accumulate it to the rest with the
accumulate operation """
result = None
for d in param_dicts:
for key, value in d.items():
if result:
resu... |
def float_eq( a, b, err=1e-08):
"""
Check if floats a and b are equal within tolerance err
@return boolean
"""
return abs(a - b) <= err |
def truncate_coordinate(coordinate):
"""
Author: https://stackoverflow.com/questions/783897/truncating-floats-in-python
This is function truncates coordinates to 3-decimal places.
Inputs:
- coordinate: float, of latitude or longitude
Outputs:
- trunc_coordinate: float, truncated la... |
def check_grid_side(ctx, param, value: int) -> int:
"""
check the size of the grid
:type value: int
"""
if value < 5:
raise ValueError("all sides of grid must be at least 5")
return value |
def ParseJava(full_name):
"""Breaks java full_name into parts.
See unit tests for example signatures.
Returns:
A tuple of (full_name, template_name, name), where:
* full_name = "class_with_package#member(args): type"
* template_name = "class_with_package#member"
* name = "class_without_pac... |
def _audience_condition_deserializer(obj_dict):
""" Deserializer defining how dict objects need to be decoded for audience conditions.
Args:
obj_dict: Dict representing one audience condition.
Returns:
List consisting of condition key with corresponding value, type and match.
"""
return [
... |
def immutable(method, self, *args, **kwargs):
"""
Decorator. Passes a copy of the entity to the method so that the original object remains un touched.
Used in methods to get a fluent immatable API.
"""
return method(self.copy(), *args, **kwargs) |
def read_file_data(filepath):
# type: (str) -> list
"""
reads the database files and returns them as list.
"""
dblist = []
try:
with open(filepath, 'r') as f:
dblist = f.read().splitlines()
except (IOError, TypeError) as e:
print(e)
return dblist |
def filter_tagged_vocabulary(tagged_vocabulary, vocabulary, split="|"):
"""Filters tagged_vocabulary (tokens merged with tags) for tokens
occurring in vocabulary.
Parameters
----------
tagged_vocabulary : collection
vocabulary of tokens (can be merged with tags)
vocabulary : collection
... |
def truthy(value):
""" Stringy Truthyness
"""
value=str(value).lower().strip(' ')
if value in ['none','false','0','nope','','[]']:
return False
else:
return True |
def get_senml_json_record(parsed, urn, label):
"""helper function returning value of associated label
example SenML input:
[{'bn': '/1/', 'n': '0/0', 'v': 123}, {'n': '0/1', 'v': 300},
{'n': '0/2', 'v': 0}, {'n': '0/3', 'v': 0}, {'n': '0/5', 'v': 0},
{'n': '0/6', 'vb': False}, {'n': '0... |
def to_bytes(s, encoding='utf-8'):
"""Ensure that s is converted to bytes from the encoding."""
if hasattr(s, 'encode') and not isinstance(s, bytes):
s = s.encode(encoding)
return s |
def overlaps_with_subspace(wavefunc: dict, subspace: list) -> bool:
"""
Calculates if there is overlap betweeen the wavefunction and the subspace spanned
by the computational basis vectors provided in the subspace parameter.
Note: This only works for subspaces aligned with the comp. basis.
:param wa... |
def TransformSize(r, zero='0', precision=1, units_in=None, units_out=None,
min=0):
"""Formats a human readable size in bytes.
Args:
r: A size in bytes.
zero: Returns this if size==0. Ignored if None.
precision: The number of digits displayed after the decimal point.
units_in: A un... |
def escape_strings(escapist: str) -> str:
"""Escapes strings as required for ultisnips snippets
Escapes instances of \\, `, {, }, $
Parameters
----------
escapist: str
A string to apply string replacement on
Returns
-------
str
The input string with all defined replace... |
def check_replace(val, replace_rules):
"""Replaces string in val by rules in dictionary replace_rules
For example:
REPLACE_RULES = {
"1,-1": ["i", "[", "]", "l", "7", "?", "t"],
"q,": ["qg","qq","gg","gq"]
}
Arguments:
val {str} -- input string
replace_rules {d... |
def capitalize_all_words(str):
"""Capitalizes all words in the string
Args:
- str: passed in string to be capitalized
"""
string_list = str.split()
output = ''
for string in string_list:
output += string.capitalize() + ' '
output = output[:-1]
return output |
def render_bookmarks_bar(label, name):
"""Renders a bookmarks bar with all available sections"""
## note that this relies on document.radiopadre.add_section() above to populate each bookmark bar
return f"""
<div>
<a name="{label}" />
<div class="rp-section-bookmarks" data-na... |
def _testinfra_validator(instruction):
""" """
try:
compile(instruction, '_testinfra_validator', 'exec')
except SyntaxError as exc:
return str(exc) |
def intersect_two_lists(list_a, list_b):
"""
Finds the intersections between two lists of TimeSlots. Internally, each list
should not have any TimeSlots that intersect
"""
result = [ ]
for item_a in list_a:
for item_b in list_b:
intersect = item_a.intersect(item_b)
if intersect:
result.appe... |
def _eval_factored_isogeny(phis, P):
"""
This method pushes a point `P` through a given sequence ``phis``
of compatible isogenies.
EXAMPLES::
sage: from sage.schemes.elliptic_curves import hom_composite
sage: E = EllipticCurve(GF(419), [1,0])
sage: Q = E(21,8)
sage: phi... |
def cardinal_direction(b):
""" Calculate the cardinal direction for a given bearing.
Ex: 0 is 'North
Args:
b: bearing (in degrees)
Returns:
A string representing cardinal direction
"""
dirs = ["North", "North-East", "East", "South-East", "South", "South-West", "West",
... |
def mention_match(mention1, mention2):
"""
Checks if two mentions matches each other.
Matching condition: One of the mentions is sub-string of the other one.
"""
match = ((mention1 in mention2) or (mention2 in mention1))
return match |
def csv_drop_unknown(data):
"""Drop keys whose values are `(Unknown)`."""
_ = lambda x: None if x == "(Unknown)" else x
data = [{k: v for k, v in ds.items() if v != "(Unknown)"} for ds in data]
for ds in data:
if "exchanges" in ds:
ds["exchanges"] = [
{k: v for k, v... |
def powersof2(n):
"""
O(log(n))
"""
powers = []
power = 1
while n > 0:
remainder = n % 2
n = n / 2
if remainder > 0:
powers += [power]
power *= 2
return powers |
def split_by_pred(pred, iterable, constructor=list):
"""Sort elements of `iterable` into two lists based on predicate `pred`.
Returns a tuple (l1, l2), where
* l1: list of elements in `iterable` for which pred(elem) == True
* l2: list of elements in `iterable` for which pred(elem) == False
"""
... |
def get_gaps(bands):
"""Calculate gaps from bands
Parameters
----------
bands : array_like of array_like of float
Energy bands of model
Returns
-------
gaps list of float
Energy gaps of model
"""
if not len(bands):
return None
b = bands[0]
gaps = [[0... |
def _int_floor(value, multiple_of=1):
"""Round C{value} down to be a C{multiple_of} something."""
# Mimicks the Excel "floor" function (for code stolen from occupancy calculator)
from math import floor
return int(floor(value/multiple_of))*multiple_of |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.