content stringlengths 42 6.51k |
|---|
def get_twotuple_value(twotuple_tuple_or_list, key):
""" from a tuple like (('lS', 5.6), ('lT', 3.4000000000000004)), get the value from giving a key """
return list(filter(lambda el: el[0] == key, list(twotuple_tuple_or_list)))[0][1] |
def get_dimension(testlist, dim=0):
"""
tests if testlist is a list and how many dimensions it has
returns -1 if it is no list at all, 0 if list is empty
and otherwise the dimensions of it
"""
if isinstance(testlist, list):
if testlist == []:
return dim
dim = dim + 1
... |
def getCommons(people, owned, want, mode='and', checkprintcount=False):
"""Finds users who have and want specific cards
:param List[Dict[str, Union[int, str, float, List[Dict[str, Union[int, str]]]]]] people: A list of people to search through
:param List[int] owned: A list of user-owned card ids to check
... |
def _filter_annotations_list(annotations_list, image,
small_object_area_threshold,
foreground_class_of_interest_id):
"""Filters COCO annotations_list to visual wakewords annotations_list.
Each image is assigned a label 1 or 0. The label 1 is assigned as lon... |
def _lrn_edges(x, y, n_channel, lr):
"""Number of edges in lrn."""
return x * y * (n_channel * lr - (lr ** 2 - 1) / 4) |
def is_iterable(object_):
"""
Returns whether the object is iterable.
Parameters
----------
object_ : `Any`
The object to check.
Returns
-------
is_iterable : `bool`
"""
return hasattr(type(object_), '__iter__') |
def parse_tags(tag_list):
"""
>>> 'tag2' in parse_tags(['tag1=value1', 'tag2=value2'])
True
"""
tags = {}
for t in tag_list:
k, v = t.split('=')
tags[k] = v
return tags |
def color_negative_red_positive_green(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, green otherwise.
:param val: input value
:type val: float
:return: css property
:rtype: str
"""
color = 'red' if val < 0 else 'green'
... |
def sleep(time):
"""
Function that returns UR script for sleep()
Args:
time: float.in s
Returns:
script: UR script
"""
script = "sleep(%s) \n" %(time)
return script |
def string_7bit(string):
"""Strip hte highest bit of evey character in string"""
s = ""
for c in string: s += chr(ord(c) & 0x7f)
return s |
def is_table_associative(table):
"""Determine whether the table supports an associative operation."""
result = True
elements = table[0] # The first row should correspond to the elements of a group
for a in elements:
for b in elements:
for c in elements:
ab = table[a]... |
def canUnlockAll(boxes):
""" Method that seeks for keys inside boxes to open other boxes
Args:
boxes: list of lists "locked boxes" Each box is numbered sequentially
from 0 to n - 1 and each box may contain keys to the other boxes.
Return:
True if all boxes can be opened, el... |
def complexity(individual, mst_edges, n_instances):
"""
:param individual: the individual (labels)
:param mst_edges: list of MSTs
:param n_instances: amount of instances
:return: the complexity
"""
# 1. Store the nodes of the spanning tree with different class.
nodes = [-1] * n_instances... |
def return_default_nb_of_cores(nb_of_cores, openmp_proportion=2):
"""Function that returns the number of cores used by OpenMP and Nipype by default.
Given ``openmp_proportion``, the proportion of cores dedicated to OpenMP threads,
``openmp_nb_of_cores`` and ``nipype_nb_of_cores`` are set by default to the ... |
def clean_symbol_code(code):
"""Cleans Weather Symbol code"""
sentence = code.split('_')
return (' '.join(sentence)).capitalize() |
def is_binary(x):
"""Returns true if x is binary"""
return set(x) == {0,1} |
def encode_config_topic(string):
"""Encode a config topic to UTF-8."""
return string.encode("ascii", "ignore").decode("utf-8") |
def _mat_mat_sub_fp(x, y):
"""Subtract to matrices."""
return [[a - b for a, b in zip(x_row, y_row)]
for x_row, y_row in zip(x, y)] |
def get_rough_size(points):
""" gets the rough width and height of the points selected """
minx, miny, maxx, maxy = 1e8, 1e8, -1e8, -1e8
for (x_coord, y_coord) in points:
minx = min(x_coord, minx)
miny = min(y_coord, miny)
maxx = max(x_coord, maxx)
maxy = max(y_coord, maxy)
... |
def mapping(private_address):
"""Given a private IP address, map to the public IP:Port -- inverse of the NAT rule."""
last_octet = int(private_address.split('.')[-1])
external = "207.189.188.118"
port = 2000 + last_octet
return "%s:%s" % (external, port) |
def ISLOGICAL(value):
"""
Checks whether a value is `True` or `False`.
>>> ISLOGICAL(True)
True
>>> ISLOGICAL(False)
True
>>> ISLOGICAL(0)
False
>>> ISLOGICAL(None)
False
>>> ISLOGICAL("Test")
False
"""
return isinstance(value, bool) |
def ODEStep1(u, t, dt, F):
"""Special formula for 1st time step (u_t=0 as IC)."""
up = u + 0.5*dt*dt*F(u, t)
return up |
def complete_lmax_res(lmax, res_beta, res_alpha):
"""
try to use FFT
i.e. 2 * lmax + 1 == res_alpha
"""
if res_beta is None:
res_beta = 2 * (lmax + 1) # minimum req. to go on sphere and back
if res_alpha is None:
if lmax is not None:
if res_beta is not None:
... |
def relay_nnvm_defaults(target='cpu', device_id=0):
"""Format options for nnvm/relay."""
return dict(target=target, device_id=device_id) |
def fail_status(job_data, token):
""" Return a reference to the first job of the specified type. """
output = '<font style="color: #%s;">%s</font>'
if job_data['status'] == 'Failed':
color = 'FF0000'
elif job_data['status'] == 'Success':
color = '00AA00'
else:
color = '000000... |
def calculateClimb(elevations):
"""returns climb between elevations"""
total = []
previous_elevation = None
for elevation in elevations:
total.append(elevation - previous_elevation if previous_elevation and elevation - previous_elevation > 0 else 0)
previous_elevation = elevation
return total |
def is_numeric(s):
"""
Return True is the string ``s`` is a numeric string.
Parameters
----------
s : str
A string.
Returns
-------
res : bool
If True, ``s`` is a numeric string and can be converted to an int or a
float. Otherwise False will be returned.
""... |
def cross_product(t1, t2):
"""
Return the cross-product of tables t1 and t2.
Example:
> R1 = [["A", "B"], [1,2], [3,4]]
> R2 = [["C", "D"], [5,6]]
[["A", "B", "C", "D"], [1, 2, 5, 6], [3, 4, 5, 6]]
"""
i = 1
j = 1
# result = []
# pass
result = [t1[0] + t2[0]]
while... |
def float_if_can(s):
"""tries to convert to float, otherwise leaves as it is"""
try:
return float(s)
except: return s |
def ft_to_toplevel(fasttext_lbl):
"""Example: '__label__STEM.Technology' -> 'STEM'"""
return fasttext_lbl.replace('__label__','').split('.')[0] |
def getObjectCounts(meshes):
"""
Count the total number of vertex groups and shapes required for all
specified meshes.
"""
nVertexGroups = 0
for mesh in meshes:
if mesh.vertexWeights is None:
continue
for weights in mesh.vertexWeights.data:
if weights:
... |
def dp(u, v):
"""
Return the dot product of u and v
@param list[float] u: vector of floats
@param list[float] v: vector of floats
@rtype: float
"""
assert len(u) == len(v)
# sum of products of pairs of corresponding coordinates of u and v
return sum([u_coord * v_coord for ... |
def resolve_expected_status(status):
"""Resolve expected status, that are to be checked for the selected package + version."""
expected_statuses = {"successful": "Successful",
"conflict": "Conflict"}
return expected_statuses.get(status, "Failure") |
def CleanFCSstring(strFCS):
""" If string can be converted to int,
then returns clean string with only the int.
othervise returns '-1'."""
try:
return str(int(strFCS))
except:
return "-1" |
def coverage_pop(coverage, population_total):
"""
Calculate the population coverage.
"""
output = round(population_total * (coverage/100))
return output |
def append_host(host, pool):
"""Encode pool into host info."""
if not host or not pool:
return host
new_host = "#".join([host, pool])
return new_host |
def fbool(value):
"""boolean"""
if isinstance(value, str):
value = value.lower()
if value == "false":
value = False
elif value == "true":
value = True
elif value:
value = bool(float(value))
else:
raise ValueError("empty stri... |
def binary_search(arr, element, low=0, high=None):
"""Returns the index of the given element within the array by
performing a binary search.
"""
if high == None:
high = len(arr) - 1
if high < low:
return -1
mid = (high + low) // 2
if arr[mid] == element:
r... |
def combo_to_int(value, replace_string='None', replace_with=0):
"""
Used for the values of combo quants with numerical values and one string value.
The default use case is to replace the 'None' option with a 0.
"""
if value == replace_string:
return int(replace_with)
else:
return... |
def CompareProperty(obj, key, value):
"""Compare the property value for the given key with the given value."""
if not hasattr(obj, key) or str(getattr(obj, key)) != str(value):
return False
return True |
def serialize_dict_keys(d, prefix=""):
"""returns all the keys in nested a dictionary.
>>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } }))
['a', 'a.b', 'a.b.b', 'a.b.c']
"""
keys = []
for k, v in d.items():
fqk = "{}{}".format(prefix, k)
keys.append(fqk)
if ... |
def array_swap_items(input_array, index1, index2):
"""
Swap 2 items in an array
:param array: the array where items are swapped
:param index1: element to swap
:param index2: element to swap
:return: the array with items swapped
"""
output_array = input_array.copy()
temp = output_arra... |
def parse_command(txt):
""" Determine a sqf command from a supportInfo entry ...
>>> "b:OBJECT setdammage SCALAR"
"setdamage"
"""
kind, _, spec = txt.partition(":")
if kind == "t":
# This is like t:TASK t:DISPLAY t:SCALAR
return
elif kind == "n":
return spec
elif... |
def jefferson(votes, seats):
"""Apportion seats using the Jefferson method.
Known also as the D'Hondt method or Hagenbach-Bischoff method.
:param list votes: a list of vote counts
:param int seats: the number of seats to apportion
"""
allocated = [0] * len(votes)
while sum(allocated) < sea... |
def insertion_sort(to_be_sorted):
"""
Quadratic, i.e. O(n^2)
:param to_be_sorted:
:return:
"""
if len(to_be_sorted) < 2:
return to_be_sorted
for i in range(1, len(to_be_sorted)):
j = i - 1
while to_be_sorted[j] > to_be_sorted[i]:
j -= 1
to_be_s... |
def parse_nmea_checksum(nmea_line):
"""
Given the complete nmea line (including starting '$' and ending checksum '*##')
calculate the checksum from the body of the line.
NOTE: this does not check for structural correctness, so you
should check that '$' and '*##' checksum are present before
... |
def get_token_string(auth):
"""
Retrieve the actual token string from a
token creation. Used for knox support.
:param auth: The instance or tuple returned by the token's .create()
:type auth tuple | rest_framework.authtoken.models.Token
:return: The actual token string
:rtype: str
"""
... |
def get_path(data):
"""
Function which joins the objects in result list and returns the command to remove objects
"""
path = ""
for i, value in enumerate(data):
if i == 0:
if isinstance(value, str):
path = f"data.get('{value}')"
elif i == len(data) - 1:
... |
def lldoutput(results):
"""
Generate the appropriate LLD DATA dictionary for protobix to send
"""
llddata = {}
def lldify(orig):
"""Append _lld to the original string, and return"""
return orig + '_lld'
for zbxtype in results:
if not zbxtype in llddata:
llddat... |
def generic(
target, namespace, pass_cond=None, message="deserialization object",
default=None):
"""Deserialize object similarly to keras .get.
Parameters
----------
target : object
target deserialization object.
namespace : object
namespace to search in.
Keywor... |
def aggregate_run_results(collection_failures, test_results):
"""
Determines overall status of run based on all failures and results.
* 'ERROR' - At least one collection failure occurred during the run.
* 'FAIL' - Template failed at least one test
* 'PASS' - All tests executed properly and no failu... |
def to_int(x):
"""Convert bytes to an integer."""
return int(x.hex(), 16) |
def prepare_query_string(args):
"""
Creates a simple query string.
This is an alternative to Requests's parameter feature. Requests
strips stuff out and coverts everything. This does a simple join,
preserving everything.
:param args: The data which is to be prepared
:type args: dict
:... |
def parsePowerFile(powerFile):
"""Returns Accumulated Energy from csv file"""
try:
with open(powerFile, "r") as f:
lines = f.readlines()
if lines:
powerline = lines[-1]
powerdata = powerline.split(",")
energy = float(powerdata[0])
time... |
def get_name(in_file):
"""
:param in_file: Path to file to convert
:return: The inferred sample name, defined by file name shorn of any file extensions
"""
return in_file.split('/')[-1].split('.')[0] |
def boolean(values):
"""
:type values: set
"""
value = values.pop()
if value:
return "t"
else:
return "f" |
def get_reorg_matrix(m, m_size, transition_state_nb):
"""
Reorder the matrix to only keep the rows with the transition states
By storing the new order in an array, we can have a mapping between new pos (idx) and old pos (value)
For example reorg_states = [2,3,1,0] means the first new row/col was in posi... |
def extract_karma_coverage_summary(line):
"""
Example coverage summary line (table row):
All files | 4.82 | 0.43 | 0.78 | 4.91 | |
"""
totals = line.replace(' ', '').split('|')
statements_percent, branches_percent, functions_percent, lines_percent = [float... |
def sanitize_markdown(markdown_body):
"""
There are some symbols used in the markdown body, which when go through Markdown -> HTML
conversion, break. This does a global replace on markdown strings for these symbols.
"""
return markdown_body.replace(
# This is to solve the issue where <s> and... |
def is_leap(year):
"""
Check if this is a leap year \n
very easy
"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False |
def get_head(text, headpos, numchars):
"""Return text before start of entity."""
wheretostart = headpos - numchars
if wheretostart < 0:
wheretostart = 0
thehead = text[wheretostart: headpos]
return thehead |
def list2dict(lst):
"""Takes a list of (key,value) pairs and turns it into a dict."""
dic = {}
for k,v in lst: dic[k] = v
return dic |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: ?
Space Complexity: ?
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
# default both variables to t... |
def _remove_sensitive_info(obj, patterns_to_filter):
"""
Filter known sensitive info
"""
if isinstance(obj, dict):
obj = {
key: _remove_sensitive_info(value, patterns_to_filter)
for key, value in obj.items()
if not any(patt in key for patt in patterns_to_filte... |
def triangle_area(a, b, c):
""" Return the area of the triangle defined by ``[a, b, c]``, where each
vertex contains floats ``[x, y]`` """
return 0.5 * abs(
a[0] * (b[1] - c[1]) +
b[0] * (c[1] - a[1]) +
c[0] * (a[1] - b[1])
) |
def over_the_road(address, n):
""" You've just moved into a perfectly straight street with exactly n identical houses on either side of the road.
Naturally, you would like to find out the house number of the people on the other side of the street.
Args:
address (integer): current address.
... |
def parse_geo_comments_section(contents):
"""Parse a COMMENTS section from a .geo file.
Args:
contents (list of str): contents of the section.
Returns: string
"""
sets = []
set_lines = []
for line in contents:
if len(line) > 3 and line[:3] == "UHL":
... |
def contains_term(email, terms):
""" Return a boolean indicating whether an email contains any of the given
sub-terms. Helper for filter_emails.
"""
contains = False
if isinstance(email,(str,)):
for term in terms:
if isinstance(term,(str,)):
if term.lower() in em... |
def class_path_of(obj) -> str:
"""
get the full class path of object
:param obj:
:return:
"""
return "{0}.{1}".format(obj.__class__.__module__, obj.__class__.__name__) |
def interpolate(x0, y0, x1, y1, x):
"""Linear interpolation between two values
Parameters
----------
x0: int
Lower x-value
y0: int
Lower y-value
x1: int
Upper x-value
y1: int
Upper y-value
x: int
Requested x-value
Returns
-------
int... |
def request_count(response):
"""Count the number of request on this route"""
return "count", 1 |
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
# If list has no elements return None
if not ints:
return None
# If the size of the list is 1 than return the pre... |
def _serializable_req(pay_req):
"""
Convert payment request json (from signed JWT)
to dict that can be serialized.
"""
pay_req = pay_req.copy()
del pay_req['_config']
return pay_req |
def _index_list_of_dict_by_key(seq, key):
""" If you need to fetch repeatedly from name, you should index them by name (using a dictionary), this way get
operations would be O(1) time. An idea:
Source: https://stackoverflow.com/a/4391722/4562156
:param seq: list of dictionaries
:param key: key to ... |
def percentagify(numerator, denominator):
"""Given a numerator and a denominator, return them expressed as a percentage.
Return 'N/A' in the case of division by 0.
"""
if denominator:
return '{:04.2f}%'.format((numerator / denominator) * 100)
else:
return 'N/A' |
def extract_env_version(release_version):
"""Returns environment version based on release version.
A release version consists of 'OSt' and 'MOS' versions: '2014.1.1-5.0.2'
so we need to extract 'MOS' version and returns it as result.
:param release_version: a string which represents a release version
... |
def partition_2(a,l,r):
"""
partition array a[l..r]
Pivot: Use the last element of the array. Swap with the first element.
"""
# swap the first and last
temp = a[l]
a[l] = a[r]
a[r] = temp
p = a[l]
i = l+1
j = l+1
while j <= r:
if a[j] <= p:
temp ... |
def clear_fitarg(fitarg):
"""Clear default values from fitarg dict."""
ret = fitarg.copy()
for key, value in fitarg.items():
if key.startswith('limit_') and value==None:
ret.pop(key)
if key.startswith('fix_') and value==False:
ret.pop(key)
return ret |
def usage(pyfile):
""" Usage """
return 'Usage: {} <groupname>'.format(pyfile) |
def get_target_base_length(target):
"""
Returns the base length of the
smallest triangle that envelops coord
"""
return abs(target[0]) + 1 + target[1] |
def get_shells(data):
"""
:param data: an iterable
:return: a list holding tuples. Each tuple holds the shells in outer-to-inner order.
If the data holds an odd number of elements, the central element is returned
as a singleton.
:rtype: list
>>> l = [1, 2, 3, 4]
>>> get_shells(l)
[(1, 4), (2, 3)]
>>> l... |
def test_policy_template_value(recipe):
"""Test that policy template is valid.
Args:
recipe: Recipe object.
Returns:
Tuple of Bool: Failure or success, and a string describing the
test and result.
"""
result = False
description = "POLICY_TEMPLATE is 'PolicyTemplate.xml'... |
def parseResults(results):
"""Pull out results/Failures from a DeferredList."""
return [x[1] for x in results] |
def is_file_like(obj):
"""Check if the object is a file-like object, per PANDAS' definition.
An object is considered file-like if it has an iterator AND has a either or
both `read()` / `write()` methods as attributes.
Parameters
----------
obj : object
Object to check for file-like prop... |
def directly_follows(trace):
"""
Get the directly-follows relations given a list of activities
Parameters
--------------
trace
List activities
Returns
--------------
rel
Directly-follows relations inside the trace
"""
return set((trace[i], trace[i+1]) for i in r... |
def opencv_ellipse_angle_to_robot_yaw(angle):
""" See my hand-drawn notes from 09/03/2017. It simplifies to this. """
assert 0 <= angle <= 180
yaw = 90 - angle
assert -90 <= yaw <= 90
return yaw |
def check_chrom_bounds(gene, slack, bounds):
"""
:param gene:
:param slack:
:param bounds:
:return:
"""
s, e = int(gene[1]), int(gene[2])
assert s >= 0, 'Gene start invalid: {}'.format(s)
assert e > 0, 'Gene end invalid: {}'.format(e)
if gene[5] == '+':
if bounds['start']... |
def alpha_rate(iteration):
"""
the learning rate: alpha
:param iteration: the count of iteration
:return: alpha learning rate
"""
#return np.log(iteration+1)/(iteration+1)
return 150/(300+iteration) |
def get_ifrost_color(val):
"""Which color to use"""
if val is None or val == -1:
return 'none'
colors = ['#EEEEEE', 'r']
try:
return colors[val]
except Exception as _exp:
return 'none' |
def arrow_to_dot(input_dict):
"""
Converts arrows ('->') in dict keys to dots '.' recursively.
Allows for storing MongoDB neseted document queries in MongoDB.
Args:
input_dict (dict)
Returns:
dict
"""
if not isinstance(input_dict, dict):
return input_dict
else:
... |
def get_locale_dir_variable_name(domain):
"""Build environment variable name for local dir.
Convert a translation domain name to a variable for specifying
a separate locale dir.
"""
return domain.upper().replace('.', '_').replace('-', '_') + '_LOCALEDIR' |
def conv_ls(N):
"""convert a number in a list of integers"""
a = list(str(N))
return list(map(lambda i: int(i), a)) |
def reduction(metadata, indices):
"""Apply dimensionality reduction to indices.
Returns reduced indices.
"""
reduction_indices = []
for k in range(len(metadata['reduction_shape'])):
reduction_shape = metadata['reduction_shapes'][k]
reduction_strides = metadata['reduction_strides'][k... |
def productExceptSelf(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
p = 1
n = len(nums)
output = []
for i in range(0,n):
output.append(p)
p = p * nums[i]
p = 1
for i in range(n-1,-1,-1):
output[i] = output[i] * p
p = p * nums[i]
re... |
def zerocase(case):
"""Check if the binary string is all zeroes"""
if int(case, 2) == 0:
return True
else:
return False |
def intersection_count_to_boundary_weight(intersection_count: int) -> int:
"""
Get actual weight factor for boundary intersection count.
>>> intersection_count_to_boundary_weight(2)
0
>>> intersection_count_to_boundary_weight(0)
1
>>> intersection_count_to_boundary_weight(1)
2
"""
... |
def get_cn_description(cn):
"""
Writes a verbal description of the coordination number/polyhedra based on a given coordination number
:param cn: (integer) rounded coordination number
:return: (String) verbal description of coordination number/polyhedra
"""
rounded_cn = round(cn)
description ... |
def later_booster(data, need_to_boost_by=None, **kwargs):
"""Example post-processing function. Interprets keyword set by boost_later"""
if need_to_boost_by is not None:
data = data + need_to_boost_by
return data |
def ll_intersection(A, B, P, Q):
"""Compute intersection of two segments formed by four points."""
denominator = (A[0]-B[0]) * (P[1]-Q[1]) - (A[1]-B[1]) * (P[0]-Q[0])
if denominator == 0:
return 0.0, 0.0
numerator_x = (A[0]*B[1]-B[0]*A[1]) * (P[0]-Q[0]) - (A[0]-B[0]) * (P[0]*Q[1]-Q[0]*P[1])
... |
def parse_repr(repr_):
"""Parse the string representation of the individual.
Arguments:
repr_ -- String representation of the individual.
"""
functions = set(['+', '-', '*', "AQ"])
labels = {}
edges = []
repr_ = repr_.replace('(', '')
repr_ = repr_.split()
n = 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.