content stringlengths 42 6.51k |
|---|
def token_combiner(tokens):
"""Dummy token combiner."""
return ''.join(tokens) |
def slice_to_range(slicer, r_max):
"""Convert a slice object to the corresponding index list"""
step = 1 if slicer.step is None else slicer.step
if slicer.start is None:
start = r_max - 1 if step < 0 else 0
else:
start = slicer.start
if slicer.stop is None:
stop = -1 if step ... |
def isFile(path: str):
""" Check whether path points to a file """
from os.path import isfile
return isfile(path) |
def _fabric_network_ipam_name(fabric_name, network_type):
"""
:param fabric_name: string
:param network_type: string (One of the constants defined in NetworkType)
:return: string
"""
return '%s-%s-network-ipam' % (fabric_name, network_type) |
def path_directories(path_dirs: dict):
"""
Setting up the desired path directories for each type of file to be converted
:return:
"""
# Setting up the finances
trips_tuple = (path_dirs['trips_path'], path_dirs['trips_csv_folder'], path_dirs['trips_sheet_tab'],
path_dirs['trips... |
def filter_running_tasks(tasks):
""" Filters those tasks where it's state is TASK_RUNNING.
:param tasks: a list of mesos.cli.Task
:return filtered: a list of running tasks
"""
return [task for task in tasks if task['state'] == 'TASK_RUNNING'] |
def _arithmetic_mean(nums) -> float:
"""Return arithmetic mean of nums : (a1 + a2 + ... + an)/n"""
return sum(nums) / len(nums) |
def _backslashreplace_backport(ex):
"""Replace byte sequences that failed to decode with character escapes.
Does the same thing as errors="backslashreplace" from Python 3. Python 2
lacks this functionality out of the box, so we need to backport it.
Parameters
----------
ex: UnicodeDecodeError... |
def sort_dictionary(dictionary: dict,
recursive: bool):
""" Function to (recursively) sort dictionaries used for package data. This procedure is used to ensure
that models always produce the same hash independent of the order of the keys in the dictionaries.
Sorting is done by the Python... |
def normalize_color(color):
"""Gets a 3-tuple of RGB ints and return a 3-tuple of unity floats"""
return (color[0] / 255.0, color[1] / 255.0, color[2] / 255.0) |
def is_nested_dict(item):
""" Check if item provides a nested dictionary"""
item = next(iter(item.values()))
return isinstance(item, dict) |
def get_marker(func_item, mark):
""" Getting mark which works in various pytest versions """
pytetstmark = [m for m in (getattr(func_item, 'pytestmark', None) or []) if m.name == mark]
if pytetstmark:
return pytetstmark[0] |
def space_tokenizer(sequence):
""" Splits sequence based on spaces. """
if sequence:
return sequence.split(' ') |
def escape_jira_strings(v):
"""in JIRA ticket body, "{" and "[" are special symbols that need to be escaped"""
if type(v) is str:
return v.replace(r"{", r"\{").replace(r"[", r"\[")
if type(v) is list:
return [escape_jira_strings(x) for x in v]
return escape_jira_strings(str(v)) |
def findHomozygotes(diptable={}):
"""
Given a summary table of diploids, finds those
which are homozygous
"""
mydiptable=diptable
homozygouslist=[]
mydipkeys=mydiptable.keys()
for key in mydipkeys:
if key[0]==key[1]:
homozygouslist.append(key)
homozygtable = {}
for key in homozygouslist:
homozygtable... |
def _list_to_tuple(v):
"""Convert v to a tuple if it is a list."""
if isinstance(v, list):
return tuple(v)
return v |
def _kern_class(class_definition, coverage_glyphs):
"""Transpose a ttx classDef
{glyph_name: idx, glyph_name: idx} --> {idx: [glyph_name, glyph_name]}
Classdef 0 is not defined in the font. It is created by subtracting
the glyphs found in the lookup coverage against all the glyphs used to
define t... |
def base_url(server, app):
"""Base URL for the running application."""
return f"http://127.0.0.1:{server['port']}" |
def cl_labels(dim):
"""
Return the classical-basis labels based on a vector dimension.
Parameters
----------
dim : int
The dimension of the basis to generate labels for (e.g.
2 for a single classical bit).
Returns
-------
list of strs
"""
if dim == 0: return []
... |
def move_point(point):
"""Move point by it velocity."""
for index, change in enumerate(point['velocity']):
point['position'][index] += change
return point |
def countBits(n):
"""
:type num: int
:rtype: List[int]
"""
# Approach 1:
# res = [0]
# for i in range(1, n+1):
# res.append(res[i>>1] + (i&1))
# return res
# Approach 2:
# res = [0]
# for i in range(1, n+1):
# res.append(res[i&(i-1)] + 1)
# return res
... |
def precision_from_tpr_fpr(tpr, fpr, positive_prior):
"""
Computes precision for a given positive prevalence from TPR and FPR
"""
return (positive_prior * tpr) / ((positive_prior * tpr) + ((1 - positive_prior) * fpr)) |
def remove_timestamp(html_text):
"""
Return the `html_text` generated attribution stripped from timestamps: the
timestamp is wrapped in italic block in the default template.
"""
return '\n'.join(x for x in html_text.splitlines() if not '<i>' in x) |
def utf_encode_list(text):
"""utf encode every element of a list."""
return [x.encode('utf-8') for x in text] |
def SPAlt( ang ):
"""
Returns list ang cycled such that the ang[2] is the smallest angle
"""
indexMin = 0
itemMin = 360
for i, item in enumerate( ang ):
if (item < itemMin):
indexMin = i
itemMin = item
return ( ang[(indexMin-2)%4:] + ang[:(indexMin-2)%4] ... |
def handler(context, inputs):
"""Set a name for a machine
:param inputs
:param inputs.resourceNames: Contains the original name of the machine.
It is supplied from the event data during actual provisioning
or from user input for testing purposes.
:param inputs.newName: The new mac... |
def _is_internal_name(name):
"""Determine whether or not *name* is an "__internal" name.
:param str name: a name defined in a class ``__dict__``
:return: ``True`` if *name* is an "__internal" name, else ``False``
:rtype: bool
"""
return name.startswith("__") and not name.endswith("__") |
def sphere(ind):
"""Sphere function defined as:
$$ f(x) = \sum_{i=1}^{n} x_i^{2} $$
with a search domain of $-5.12 < x_i < 5.12, 1 \leq i \leq n$.
The global minimum is at $f(x_1, ..., x_n) = f(0, ..., 0) = 0.
It is continuous, convex and unimodal.
"""
return sum((x ** 2. for x in ind)), |
def get_layer_parents(adjList,lidx):
""" Returns parent layer indices for a given layer index. """
# Return all parents (layer indices in list) for layer lidx
return [e[0] for e in adjList if e[1]==lidx] |
def generate_sql_query_cmd(sql_event_name_condition_arg, sql_event_time_condition_arg):
"""
The function to generate completed SQL query command.
@param sql_event_name_condition_arg The SQL condition of event name.
@param sql_event_time_condition_arg The SQL condition of event time.
@return The completed SQL query... |
def fuzzy_match(pattern, instring, adj_bonus=5, sep_bonus=10, camel_bonus=10,
lead_penalty=-3, max_lead_penalty=-9, unmatched_penalty=-1):
"""Return match boolean and match score.
:param pattern: the pattern to be matched
:type pattern: ``str``
:param instring: the containing string to ... |
def color_name_to_id(color_name: str) -> str:
"""
map color_name to hex color
:param color_name:
:return:
"""
color_id = {
'gray': '#A0A5AA',
'red': '#FA8282',
'orange': '#FA9C3E',
'yellow': '#F2CA00',
'green': '#94BF13',
'blue': '#499DF2',
... |
def GCD(x,y):
"""Takes two inputs and returns the Greatest common divisor and returns it"""
while(y):
x, y = y, x % y
return x |
def is_question(input_string):
"""
Function to determine if the input contains '?'
Function taken from A3
Inputs:
string
Outputs:
string
"""
if '?' in input_string:
output = True
return output
else:
output = False
return output |
def check_and_fix_names_starting_with_numbers(name):
"""
Since I3 map names cannot start with a number, add a letter 'a' to any names starting with a
number
Args:
name: The name to check for a beginning number
Returns: The new name (unchanged if the name properly started with a letter)... |
def count_logistic(x):
"""Return value of a simple chaotic function."""
val = 3.9 * x * (1-x)
return val |
def clean_view(view_orig, superunits):
"""
Define a view of the system that comes from a view of another one.
Superunits are cleaned in such a way that no inconsistencies are present
in the new view.
Args:
view_orig (dict): the original view we would like to clean
superunits (list): l... |
def group_uris(cesnet_groups):
"""Group URIs fixture."""
return {
'exists': 'urn:geant:cesnet.cz:groupAttributes:f0c14f62-b19c-447e-b044-c3098cebb426?=displayName=example#perun.cesnet.cz',
'new': 'urn:geant:cesnet.cz:groupAttributes:f0c14f62-b19c-447e-b044-c3098c3bb426?=displayName=new#perun.ces... |
def transform_json_from_studio_to_vulcan(studio_json):
"""Transforms a json from the studio format to the vulcan format."""
# Initialize variables
vulcan_json = []
# Loop through all studio images
for studio_image in studio_json['images']:
# Initialize vulcan prediction
vulcan_pred ... |
def cubic_ease_out(p):
"""Modeled after the cubic y = (x - 1)^3 + 1"""
f = p - 1
return (f * f * f) + 1 |
def make_key(app_id, app_key, task_id):
"""This is a naming convention for both redis and s3"""
return app_id + "/" + app_key + "/" + task_id |
def dataset_name_normalization(name: str) -> str:
"""Normalize a dataset name."""
return name.lower().replace('_', '') |
def construct_version_string(major, minor, micro, dev=None):
"""
Construct version tag: "major.minor.micro" (or if 'dev' is specified: "major.minor.micro-dev").
"""
version_tag = f"{major}.{minor}.{micro}"
if dev is not None:
version_tag += f"-{dev}"
return version_tag |
def move_to_corner(move):
"""Take a move ('color', (row,col)).
where row, col are 0-indexed (from sgfmill)
Figure out which corner it's in
Transform it to be in the upper right corner;
Returns [corners, move]
corners: A list of the indices of the corners it is in (0-3)
move: The transform... |
def processPupil(pupil_positions, pupil_coulmn,
recStartTimeAlt, filterForConf,
confidence_threshold):
"""extract the pupil data from the eye traker to get standar deviation,
mean, and filter the dataset"""
diameters = []
frames = []
timeStamps = []
simpleTimeS... |
def expand_dict(info):
"""
converts a dictionary with keys of the for a:b to a dictionary of
dictionaries. Also expands strings with ',' separated substring to a
list of strings.
:param info: dictionary
:return: dictionary of dictionaries
"""
res = {}
for key, val in info.ite... |
def all_but_axis(i, axis, num_axes):
"""
Return a slice covering all combinations with coordinate i along
axis. (Effectively the hyperplane perpendicular to axis at i.)
"""
the_slice = ()
for j in range(num_axes):
if j == axis:
the_slice = the_slice + (i, )
else:
... |
def rgb(value, minimum, maximum):
"""
Calculates an rgb color of a value depending of
the minimum and maximum values.
Parameters
----------
value: float or int
minimum: float or int
maximum: float or int
Returns
-------
rgb: tuple
"""
value = float(value)
minimu... |
def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float:
"""
Convert a given value from Rankine to Kelvin and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
>>> rankine_to_kelvin(0)
... |
def chain_remaining_sets(first, prev, remaining_sets):
"""
Search remaining_sets for candidates that can chain with prev, recursively,
until all sets have been used to take exactly 1 candidate from
first: if len(remaining_sets) == 1, we must close the chain with first two digits of first
prev: must ... |
def index2string(index):
"""
Convert an int to string
Parameter
---------
index: int
index to be converted
Return
------
string: string
string corresponding to the string
"""
if index == 0:
string = 'BENIGN'
elif index == 1:
string = 'FTP-Pa... |
def get_value(state: dict, key: str):
"""
get the value of a given key in the state
:param state: the dict
:param key: key, can be a path like color/r
:return: the value if found or None
"""
k = key.split("/", 1)
if len(k) > 1:
if k[0] not in state:
return... |
def tract_id_equals(tract_id, geo_id):
"""
Determines if a 11-digit GEOID (from the US census files) refers to the same place as a six-digit Chicago census
tract ID.
:param tract_id: A 6-digit Chicago census tract ID (i.e., '821402')
:param geo_id: An 11-digit GEOID from the US Census "Gazetteer" f... |
def req_yaml_template(pip=False, version=True, build=False):
"""
Builds a template string for requirement lines in the YAML format.
:pip: [bool] Whether to build a Conda requirement line or a pip line
:version: [bool] Includes the version template
:build: [bool] Includes the build template. Makes ... |
def reverse_map(k_map):
"""
Return the reversed map from k_map
Change each 1 by 0, and each 0 by a 1
"""
r_map = []
for line in k_map:
r_line = []
for case in line:
r_line.append(not case)
r_map.append(r_line)
return r_map |
def deg2dmm(degrees: float, latlon: str) -> str:
"""
Convert decimal degrees to degrees decimal minutes string.
:param float degrees: degrees
:param str latlon: "lat" or "lon"
:return: degrees as dm.m formatted string
:rtype: str
"""
if not isinstance(degrees, (float, int))... |
def is_identifier_match(identifier: str, project: dict) -> bool:
"""
Determines whether or not the specified identifier matches
any of the criteria of the given project context data values
and returns the result as a boolean.
"""
matches = (
'{:.0f}'.format(project.get('index', -1) + 1),... |
def _fix_slice(slc):
"""
Fix up a slc object to be tuple of slices.
slc = None is treated as no slc
slc is container and each element is converted into a slice object
None is treated as slice(None)
Parameters
----------
slc : None or sequence of tuples
Range of values for sl... |
def _update(s, _lambda, P):
"""
Update ``P`` such that for the updated `P'` `P' v = e_{s}`.
"""
k = min([j for j in range(s, len(_lambda)) if _lambda[j] != 0])
for r in range(len(_lambda)):
if r != k:
P[r] = [P[r][j] - (P[k][j] * _lambda[r]) / _lambda[k] for j in range(len(P[r])... |
def create_gap_from_distmat(matrix, s, t):
"""Creates gapped strings based on distance matrix."""
gapped_s, gapped_t = '', ''
i, j = len(s), len(t)
while (i > 0 and j > 0):
left = matrix[i][j - 1]
up = matrix[i - 1][j]
diag = matrix[i - 1][j - 1]
best = min(left, up, di... |
def clean(input_list, exclude_list=[]):
"""Returns list with digits, numberwords and useless words from list of
key phrases removed
Inputs:
input_list -- List of strings containing key phrases to be processed
exclude_list -- List of strings containing words to be removed
... |
def simpsons_diversity_index(*args):
"""
From https://en.wikipedia.org/wiki/Diversity_index#Simpson_index
The measure equals the probability that two entities taken at random from
the dataset of interest represent the same type.
"""
if len(args) < 2:
return 0
def __n_times_n_minus_... |
def dict_map_leaves(nested_dicts, func_to_call):
"""
Applies a given callable to the leaves of a given tree / set of nested dictionaries, returning the result (without
modifying the original dictionary)
:param nested_dicts: Nested dictionaries to traverse
:param func_to_call: Function to call on th... |
def grid_contains_point(point_coord, grid_list_coord):
""" Identify if a point is within a grid of coordinates
Args:
point_coord ([lat,lon]): Coordinates of a point
grid_list_coord (list): List of grid centroids
Returns:
tuple: (boolean) is contained in point , and an exit message ... |
def shift(g, d, n):
"""Shift a list of the given value"""
return g[n:] + g[:n], d[n:] + d[:n] |
def dict_to_filter_params(d, prefix=''):
"""
Translate a dictionary of attributes to a nested set of parameters suitable for QuerySet filtering. For example:
{
"name": "Foo",
"rack": {
"facility_id": "R101"
}
}
Becomes:
{
... |
def partition_strict(function, items):
"""Like 'partition' but returns two lists instead of lazy iterators.
Should be faster than partition because it only goes through 'items' once.
>>> is_odd = lambda x : (x % 2)
>>> partition_strict(is_odd, [1, 2, 3, 4, 5, 6])
([1, 3, 5], [2, 4, 6])
"""
... |
def filter_query(filter_dict, required_keys):
"""Ensure that the dict has all of the information available. If not, return what does"""
if not isinstance(filter_dict, dict):
raise TypeError("dict_list is not a list. Please try again")
if not isinstance(required_keys, list):
raise TypeError(... |
def _GetBuildProperty(build_properties, property_name):
"""Get the specified build property from the build properties dictionary.
Example property names are Chromium OS Version ('branch'), Chromium OS
Version ('buildspec_version'), and GIT Revision ('git_revision').
Args:
build_properties: The properties ... |
def _Append(text):
"""Inserts a space to text if it is not empty and returns it."""
if not text:
return ''
if text[-1].isspace():
return text
return ' ' + text |
def find(d, value):
""" Look for the first key correspondind to value `value` in dictionnary `d` """
for (k, v) in d.items():
if v == value:
return k |
def display_binary_4bit(num: int):
"""Displays the binary string representation for a given integer. If the number is within 4 bits, the output will be 4 binary digits; if the number is 8 bits then 8 binary digits will be the output.
Examples:
>>> display_binary_4bit(151)\n
'10010111'
... |
def xor_bytes(bts1: bytes, bts2: bytes) -> bytes:
"""Make a xor by bytes
@param bts1:
@param bts2:
@return:
"""
return bytes([byte1 ^ byte2 for byte1, byte2 in zip(bts1, bts2)]) |
def get_perfdata(label, value, uom, warn, crit, _min, _max):
"""Returns 'label'=value[UOM];[warn];[crit];[min];[max]
"""
msg = "'{}'={}".format(label, value)
if uom is not None:
msg += uom
msg += ';'
if warn is not None:
msg += str(warn)
msg += ';'
if crit is not None:
... |
def my_sqrt(x):
"""
:type x: int
:rtype: int
"""
if x <= 1:
return x
l, r = 0, x
while l + 1 < r:
mid = l + (r - l) // 2
if mid * mid <= x < (mid + 1) * (mid + 1):
return mid
elif mid * mid > x:
r = mid
else:
l = mid |
def URL(s):
""" take an input string and replace spaces with %20"""
return s.replace(" ", "%20") |
def check_online(device):
"""Home Assistant Logic for Determining Device Availability"""
return 'offline' not in device |
def get_precision(tp, fp):
"""
This function returns the precision for indels by size.
:param tp: Number of true positives
:type tp: int
:param fp: Number of false positives
:type fp: int
:return: The precision, (tp) / (tp+fp)
:rtype: float
"""
if tp + fp == 0:
return '... |
def __discretizePoints(x,cut_points):
"""
Function to discretize a vector given a list of cutpoints.
This function dicretizes a vector given the list of points to cut
:param x: a vector composed by real numbers
:param cut_points:a list with the points at which the vector has to be cut
:return: A... |
def sdiv(a: float, b: float) -> float:
"""Returns the quotient of a and b, or 0 if b is 0."""
return 0 if b == 0 else a / b |
def fix_indent(rating):
"""Fixes the spacing between the moveset rating and the moves
Returns three spaces if the rating is one character, two if it is two characters (A-, B-, etc)
"""
if len(rating) == 1:
return ' ' * 3
else:
return ' ' * 2 |
def filled(f,d):
"""
Check if a field exists in a dictionary, and if that field is not None or the empty string.
"""
return f in d and d[f] is not None and d[f] != "" |
def gaps(ranges):
"""Get a list with the size of the gaps between the ranges
"""
gaps = []
for cur, nxt in zip(ranges[:-1], ranges[1:]):
gaps.append(nxt[0] - cur[1]) # 1: end, 0: start
return gaps |
def get_collection_for_lingsync_doc(doc):
"""A LingSync document is identified by its `collection` attribute, which is
valuated by a string like 'sessions', or 'datums'. Sometimes, however,
there is no `collection` attribute and the `fieldDBtype` attribute is
used and evaluates to a capitalized, singula... |
def extract_port_from_name(name, default_port):
"""
extractPortFromName takes a string in the form `id:port` and returns the ID and the port
If there's no `:`, the default port is returned
"""
idx = name.rfind(":")
if idx >= 0:
return name[:idx], name[idx+1:]
return name... |
def eta( r_net_day, evaporative_fraction, temperature):
"""
eta( r_net_day, evaporative_fraction, temperature)
"""
t_celsius = temperature - 273.15
latent = 86400.0/((2.501-0.002361*t_celsius)*pow(10,6))
result = r_net_day * evaporative_fraction * latent
return result |
def Mcnu_to_M(Mc, nu):
"""Convert chirp mass and symmetric mass ratio to total mass"""
return Mc*nu**(-3./5.) |
def italic(s):
"""Return the string italicized.
Source: http://stackoverflow.com/a/16264094/2570866
:param s:
:type s: str
:return:
:rtype: str
"""
return r'\textit{' + s + '}' |
def _gaussian_gradients(x, y, a, sigma, mu):
"""Compute weight deltas"""
sig2 = sigma**2
delta_b = (mu / sig2) - (y / sig2) * (2 * sig2 + 1 - y**2 + mu * y)
delta_a = (1 / a) + delta_b * x
return delta_a, delta_b |
def suzuki_trotter(trotter_order, trotter_steps):
"""
Generate trotterization coefficients for a given number of Trotter steps.
U = exp(A + B) is approximated as exp(w1*o1)exp(w2*o2)... This method returns
a list [(w1, o1), (w2, o2), ... , (wm, om)] of tuples where o=0 corresponds
to the A operator... |
def map_to_range(start_val, current_range_min, current_range_max, wanted_range_min, wanted_range_max):
"""Maps x and y from a range to another, desired range"""
out_range = wanted_range_max - wanted_range_min
in_range = current_range_max - current_range_min
in_val = start_val - current_range_min
... |
def reflexive_missing_elements(relation, set):
"""Returns missing elements to a reflexive relation"""
missingElements = []
for element in set:
if [element, element] not in relation:
missingElements.append((element,element))
return missingElements |
def RGB2HEX(color):
"""In: RGB color array
Out: HEX string"""
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2])) |
def is_def_arg_private(arg_name):
"""Return a boolean indicating if the argument name is private."""
return arg_name.startswith("_") |
def output_list(master_list):
"""Removes the extra brackets when outputting a list of lists
into a csv file.
Args:
masterList: input list of lists
Returns:
list: output list
"""
output = []
for item in master_list:
# check if item is a list
if isinstance(it... |
def RPL_ADMINLOC1(sender, receipient, message):
""" Reply Code 257 """
return "<" + sender + ">: " + message |
def estimate_coef(clear_x, clear_y):
"""
Linear regression function.
:param clear_x: cleared_x
:type clear_x : list
:param clear_y: cleared_y
:type clear_y : list
:return: [slope,intercept]
"""
try:
n = len(clear_x)
mean_x = sum(clear_x) / n
mean_y = sum(clea... |
def generate_spec(key_condictions):
"""get mongo query filter by recursion
key_condictions is a list of (key, value, direction)
>>> generate_spec([
... ('a', '10', 1),
... ('b', '20', 0),
... ])
{'$or': [{'$and': [{'a': '10'}, {'b': {'$lt': '20'}}]}, {'a': {'$gt': '10'}}]}
"""
... |
def skip_material(mtl: int) -> int:
"""Computes the next material index with respect to default avatar skin indices.
Args:
mtl (int): The current material index.
Returns:
int: The next material index to be used.
"""
if mtl == 1 or mtl == 6:
return mtl + 2
return mtl + 1 |
def add_dict(dict1, dict2):
"""
Add two dictionaries together.
Parameters
----------
dict1 : dict
First dictionary to add.
dict2 : dict
Second dictionary to add.
Returns
-------
dict
The sum of the two dictionaries.
Examples
--------
>>>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.