content stringlengths 42 6.51k |
|---|
def isUniqueWithSet (str):
"""Given a string, checks if the string has unique charachters"""
return len(set(str)) == len(str) |
def shape_is_known(shape):
"""Check whether a shape is completely known with or without np semantics.
Please see the doc of is_np_shape for more details.
"""
if shape is None:
return False
unknown_dim_size = -1
if len(shape) == 0:
return unknown_dim_size == -1
for dim_size in... |
def kelvin(therm: float) -> float:
"""
Pyccd converts (and scales) the thermal values into Celsius, this converts
them back to kelvin.
Args:
therm: thermal value in degrees Celsius
Returns:
thermal value in kelvin
"""
return therm / 10 + 27315 |
def adjust_epochs(train_epochs, width_scale, update_frequency,
start_iteration, n_growth_steps, steps_per_epoch):
"""Adjust the epochs such as the total FLOPs are same as big-baseline."""
# Here we extend training according to the FLOP saved by starting with
# a smaller width.
saved_fraction =... |
def closest_point(l1, l2, point):
"""
compute the coordinate of point on the line l1l2 closest to the given point, reference: https://en.wikipedia.org/wiki/Cramer%27s_rule
:param l1: start pos
:param l2: end pos
:param point:
:return:
"""
A1 = l2[1] - l1[1]
B1 = l1[0] - l2[0]
C1 ... |
def sorting(items):
"""sort the items"""
items.sort()
return items |
def _gen_perm(order, mode):
"""
Generate the specified permutation by the given mode.
Parameters
----------
order : int
the length of permutation
mode : int
the mode of specific permutation
Returns
-------
list
the axis order, according to Kold... |
def get_candidates(row_no, col_no,
row_candidates, col_candidates, square_candidates):
"""
Gets possible candidates for a square with 3-way set intersection of its
row, col and encompassing square sets
"""
candidates = row_candidates[row_no] & col_candidates[col_no] & ... |
def check_collision(board, shape, offset):
"""
See if the matrix stored in the shape will intersect anything
on the board based on the offset. Offset is an (x, y) coordinate.
"""
off_x, off_y = offset
for cy, row in enumerate(shape):
for cx, cell in enumerate(row):
if cell an... |
def obter_pos_c(pos):
"""
obter_pos_c: posicao -> str
Recebe uma posicao e devolve a componente coluna da posicao.
"""
return pos['c'] |
def get_pf_index(sib, paging):
"""
Calculates paging frame index based on SIB2 configuration and incoming S1AP paging.
Complexity: O(1)
:rtype: int
"""
t = min(sib['defaultPagingCycle'], paging['PagingDRX'])
n = min(t, int(sib['nB'] * t))
return int((t / n) * (paging['UEIdentityIndexVal... |
def nmea2deg(nmea):
""" convert nmea angle (dddmm.mm) to degree """
w = float(nmea) / 100.0
d = int(w)
return d + (w-d) * 100 / 60.0 |
def modal_form(title='', modal_id='id_modal_form', form_tag_id='id_modal_form_tag'):
"""
Return a modal bootstrap html,
with custom code for manipulate form submition
"""
return {
'modal_id': modal_id,
'title': title,
'form_tag_id': form_tag_id,
} |
def _pad_list(given_list, desired_length, padding=None):
"""
Pads a list to be of the desired_length.
"""
while len(given_list) < desired_length:
given_list.append(padding)
return given_list |
def wrap_braces_if_not_exist(value):
"""Wrap with braces if they don't exist."""
if '{{' in value and '}}' in value:
# Already templated
return value
return '{{' + value + '}}' |
def conv_kwargs_helper(norm: bool, activation: bool):
"""
Helper to force disable normalization and activation in layers
which have those by default
Args:
norm: en-/disable normalization layer
activation: en-/disable activation layer
Returns:
dict: keyword arguments to pass... |
def auc_helper(relationships, run_rules, run_confidences):
"""
Calculates auc-roc measuring the recall and precision of learned rules relative to a set of existing relationships
"""
targets = []
scores = []
for head, body in relationships.items():
targets.append(1.0)
if [hea... |
def sumall(*args):
"""Write a function called sumall that takes any number of arguments and returns their sum."""
total = 0
for elem in args:
total += elem
return total |
def ProtocolNameToNumber(protocols, proto_to_num, name_to_num_map):
"""Convert a protocol name to a numeric value.
Args:
protocols: list of protocol names to inspect
proto_to_num: list of protocol names that should be converted to numbers
name_to_num_map: map of protocol names to protocol numbers
Re... |
def modinv(a, m):
""" The multiplicitive inverse of a in the integers modulo m.
Return b when a * b == 1 mod m
"""
# Extended GCD
lastrem, rem = abs(a), abs(m)
x, lastx, y, lasty = 0, 1, 1, 0
while rem:
lastrem, (quotient, rem) = rem, divmod(lastrem, rem)
x, lastx = lastx - quotient*x, x
y, l... |
def _make_attrs(annotation, annotation_dict, export_names, index):
"""Create a list with attribute-value strings for a structural element."""
attrs = []
for name, annot in annotation_dict[annotation].items():
export_name = export_names.get(":".join([annotation, name]), name)
annotation_name ... |
def download_content(username, project_name, resource_id, data, files, is_project):
"""
Recursive function to extract all files from a given project.
Parameters
----------
username: str
The user's Gitlab username
project_name: str
The name of the project being downloaded
res... |
def make_good_bad(cameras, car_id):
"""
make a list of cars of interest, and a list of other
cameras(list(list(chips))): list of the cameras with the cars in each cameras
car_id(): the id of the car of interest
"""
goodlist = list()
bad_list = list()
for camera in cameras:
for c... |
def mySdeCoeffsFunc(xList, u, r, mu, sig):
"""
@param[in] ### xList ### list of length one containing state values
@param[in] ### u ### control value in the interval [0, 1]
@param[in] ### r ### interest rate of the riskless asset
@param[in] ### mu ### interest rate of the risky asset
@param[in] ### sig ### v... |
def dict_lookup(d, value):
"""
Template filter that looks up a value from a dict.
"""
return d.get(value) |
def nextDWord(offset):
"""
Align `offset` to the next 4-byte boundary.
"""
return ((offset + 3) >> 2) << 2 |
def split_dictionary(output_dict):
"""Splits a dictionary into two lists for IDs and its full file paths
Parameters
----------
output_dict : dictionary
A dictionary with keys: 'id_llamado' and 'fullpath'
Returns
-------
Two lists
Two lists of 'id_llamado' and 'fullp... |
def pythrule(first, second):
"""
Calculate the area of a right angled trangle based on Pythagoras' Theorem
:type first: number
:param first: The length of the first axis (x or y)
:type second: number
:param second: The length of the second axis (x or y)
"""
return (first * second) / 2 |
def day_lags(lags):
"""Translate day lags into 15-minute lags"""
return [l * 96 for l in lags] |
def is_string(val):
"""
Return whether a value is a ``str``.
"""
return isinstance(val, str) |
def _iteritems(d):
"""Like d.iteritems, but accepts any collections.Mapping."""
return d.iteritems() if hasattr(d, "iteritems") else d.items() |
def makeDestName(fileName):
"""
Determine the name of the file as it will appear after being moved into the
directory for the class. Currently this follows a set pattern, where the data
files are forum.mongo, and then .sql files for users, profiles, student modules,
course enrollment, and certifica... |
def tab(text, n=1):
"""
Indent generated code by `n` 4-space indents.
"""
lines = text.split('\n')
lines = [(' ' * n) + line for line in lines]
return '\n'.join(lines) |
def inputoptions(datatype, item):
"""Home made match function"""
if datatype == "invested_and_value":
return [
{
"date": item["date"],
"value": item["total_value"],
"category": "Value",
},
{
"date": item[... |
def get_thresholds(bins=1,interval=(0.5,0.5)):
"""
:param bins: the number of the threshold
:param interval: give the min number and max number for a interval
:return: the list that meet the conditions
"""
max_iter = interval[1]-interval[0]
each_iter = float(max_iter)/bins
threshold = in... |
def turn_to_words(word):
"""Split on non-alphanumeric characters, if any."""
res = []
subword = ""
for char in list(word):
if char.isalnum():
subword = subword + char
else:
if subword:
res.append(subword)
subword = ""
res.append(sub... |
def _include_exclude_list(include, exclude):
"""
create the list of queries that would be checked for include or exclude
"""
keys = []
if include:
for item in include:
keys.append((item, 'included'))
if exclude:
for item in exclude:
keys.append((item, 'exc... |
def _flatten(list_of_lists):
"""Transform a list of lists into a single list, preserving relative order."""
return [item for sublist in list_of_lists for item in sublist] |
def percent_invert(value, total):
"""
Convert avail and total values to percent
"""
if total:
v = (float(total) - float(value)) * 100.0 / float(total)
if v >= 0.0:
return v
return 100.0 |
def human_readable_time(delta, terms=1):
"""Convert hours to human readable string
Arguments:
delta: time in seconds
terms: how many word terms to use, to describe the timestep
Returns
str: Human readable string
"""
# Inspired by http://stackoverflow.com/questions/26164671/c... |
def class_name_to_slug(name):
"""Strip Directive and turn name into slug
Example:
Hands_OnDirective --> hands-on
"""
return name.split('Directive')[0].lower().replace('_', '-') |
def number_of_cigarette(packCig) :
"""
Function that allow to count the number of cigarette into the packet
:param packCig [] : packet of cigarettes
:returns nb_cig : int : number of cigarette
"""
nb_cig = (len(packCig[0]), len(packCig[1]), len(packCig[2]))
if nb_cig[0] == nb_cig[1] and nb_... |
def _NodeLabel(data):
"""Helper callback to set default node labels."""
node_type = data.get("type", "statement")
if node_type == "statement":
return data.get("text", "")
elif node_type == "identifier":
return data.get("name", "")
elif node_type == "magic":
return data.get("name", "")
else:
... |
def lineSegment(lineWidth, x1, y1, x2, y2, idField):
"""Draw a line segment."""
return ('<line stroke="black" stroke-width="{}"\n'
' x1="{}" y1="{}" x2="{}" y2="{}"'
' id="{}" />\n').format(lineWidth,
x1, y1, x2, y2,
... |
def busca_sentinela(list_to_search, value):
"""
Implementacao de um algoritmo de busca sentinela.
Argumentos:
value: Any. Valor a ser buscado na lista
list_to_search: list. lista na qual o valor sera buscado
Retorna o indice do valor em "list_to_search" ou -1 caso nao exista nela.
"""
... |
def verifyItExists(asset: str, available_assets: list) -> bool:
"""
Check if in the balances of the account an asset like that alredy exists to establish a trustline
"""
asset_name = asset.split(':')[0]
asset_issuer = asset.split(':')[1]
for elem in available_assets:
if elem["asset_code"... |
def is_leap(year):
"""Determine whether a year is a leap year."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) |
def octal_to_string(octal):
"""The octal_to_string function converts a permission in octal format into a
string format."""
result = ""
value_letters = [(4,"r"),(2,"w"),(1,"x")]
for digit in [int(n) for n in str(octal)]:
for value, letter in value_letters:
if digit >= value:
... |
def norm3(vec3):
"""
Quick convenient function to get the norm of a 3-element vector
norm3: 475 ns | np.linalg.norm: 4.31 us
"""
a, b, c = vec3
return (a*a + b*b + c*c)**0.5 |
def convertMac(macAddress):
""" Performs conversion of Mac Address format to the colon type and return as string """
# Reference: https://forums.freebsd.org/threads/python-inserting-a-sign-after-every-n-th-character.26881/
# Convert to CAPS
stdMac = str(macAddress).upper()
# Checks if contains '-' ch... |
def str_to_list(string):
"""remove [] and whitespace, then create list of integers to return"""
string = string[1:-1].replace(' ', '').split(',')
return [int(str_id) for str_id in string] |
def count_run(lst, s_run):
"""Count the length of one run, returns starting/ending indices,
a boolean value to present increasing/decreasing run,
and the length of the run"""
increasing = True
# If count_run started at the final position of the array
if s_run == len(lst) - 1:
return [s_... |
def untokenize(tokens):
"""Return inverse of the Adeft word tokenizer
The inverse is inexact. For simplicity, all white space characters are
replaced with a space. An exact inverse is not necessary for adeft's
purposes.
Parameters
----------
tokens : list of tuple
List of tuples of... |
def remove_selected_from_list(the_list, selected_indexes):
"""
Removes selected elements from the list.
:param the_list:
:param selected_indexes: list of indexes to be removed from the list
:return: processed list
"""
doc_len = len(the_list)
tmp = []
for i in range(0, doc_len):
... |
def polygonal_number(sides: int, n: int) -> int:
"""
Returns the n-th polygonal number for a given number of sides.
A polygonal number is a number represented as dots or pebbles arranged in the shape of a regular polygon.
:param sides: The number of sides of the polygon
:param n: A positive number
... |
def _linspace(start, stop, num):
"""Returns `num` uniformly spaced floats between `start` and `stop`."""
if num == 1:
return [start]
return [start + (stop - start) * i / (num - 1.0) for i in range(num)] |
def Sphere(name,radius=1.0,res=0, pos = [0.,0.,0.]):
"""
Create a hostobject of type sphere.
@type name: string
@param name: name of the sphere
@type radius: float
@param radius: the radius of the sphere
@type res: float
@param res: the resolution/quality of the sphere
@type ... |
def straight(start, dice):
"""
Score the dice based on rules for LITTLE_STRAIGHT or BIG_STRAIGHT.
"""
dice.sort()
for die in dice:
if die != start:
return 0
start += 1
return 30 |
def RPL_USERS(sender, receipient, message):
""" Reply Code 393 """
return "<" + sender + ">: " + message |
def path(start, end):
"""
>>> path((1,1), (1,1))
[]
>>> path((0,0), (2,2))
[(1, 1)]
>>> path((1,2), (7,5))
[(3, 3), (5, 4)]
>>> path((9, 10), (6, 10))
[(8, 10), (7, 10)]
>>> path((10, 9), (10, 6))
[(10, 8), (10, 7)]
>>> path((1,1), (3,8))
[]
>>> path((4, 2), (4, 4... |
def has_dupes(sequence, target):
"""Given a sequence and search object, return True if there's more
than one, False if zero or one of them.
"""
# compare to .index version below, this version introduces less function
# overhead and is usually the same speed. At 15000 items (way bigger than
# ... |
def maximum_digital_sum(a: int, b: int) -> int:
"""
Considering natural numbers of the form, a**b, where a, b < 100,
what is the maximum digital sum?
:param a:
:param b:
:return:
>>> maximum_digital_sum(10,10)
45
>>> maximum_digital_sum(100,100)
... |
def power(a,b):
"""
Computes a to the power of b using recursion
"""
if b == 0:
return 1
if b == 1:
return a
return a * power(a,b-1) |
def difference(v1, v2):
""" compute the difference between two vectors """
return [x1 - x2 for x1, x2 in zip(v1, v2)] |
def confusion_matrix(y_true, y_pred, pos_label=1):
"""
Function to return a confusion matrix given a set of predictions
and ground truths.
Args:
y_true : List of ground truths
y_pred : List of predictions
pos_label : value to consider as positive. Default: 1
Returns:
... |
def left_pad(string, size):
"""Add zeros to the front of a string to reach a certain length."""
return string.zfill(size) |
def parseCoords(s):
"""Parse a string of the form chr:start-end and return the three components as a tuple."""
p1 = s.find(":")
p2 = s.find("-")
return (s[:p1], s[p1+1:p2], s[p2+1:]) |
def _check_axis_in_range(axis, ndim):
"""Checks axes are with the bounds of ndim"""
if not isinstance(axis, int):
raise TypeError(f'axes should be integers, not {type(axis)}')
if not -ndim <= axis < ndim:
raise ValueError(f'axis {axis} is out of bounds for array of dimension {ndim}')
ret... |
def osiris_url(course_code, calendar_year) -> str:
"""
A template tag which resolves the params into a Osiris URL.
Calendar Year is understood as Academic year which started in that year
E.g. 2018 is understood as September 2018/ July 2019
:param course_code: The course-code you are looking for. [... |
def correct_vgene(v, chain='B'):
"""Makes sure that the given v gene is in correct format,
handles a different few formats."""
if chain is 'B':
v = v.replace('TCR','TR').replace('TRBV0','TRBV').replace('-0','-')
elif chain is 'A':
v = v.replace('TCR','TR').replace('TRAV0','TRAV').replace... |
def get_binary_column_type(column_type):
"""Return an appropriate binary column type for the input one, cf. https://codex.wordpress.org/Converting_Database_Character_Sets."""
try:
return {
'char': 'binary',
'text': 'blob',
'tinytext': 'tinyblob',
'mediumte... |
def enable_squash(input):
"""
Convert long specific enable strings to 'enabled'
Takes in a dictionary of parsed output, iterates over the keys and looks
for key names containing the string "enabled" at the end of the key name.
Specifically the end of the key name is matched for safety. Replaces th... |
def from_datastore(entity):
"""Translates Datastore results into the format expected by the
application.
Datastore typically returns:
[Entity{key: (kind, id), prop: val, ...}]
This returns:
[ name, email, date, message ]
where name, email, and message are Python strings
and whe... |
def sigmoid_backward(dout, cache):
"""
backward of sigmoid function, dx = x(x-1)
:param dout: grad of outputs
:param cache: cache stored before
:return: dx
"""
x = cache
return x * (x - 1) * dout |
def out_first_order(triples):
"""
Sort a list of triples so outward (true) edges appear first.
"""
return sorted(triples, key=lambda t: t.inverted) |
def same_shape(t1: tuple, t2: tuple) -> bool:
"""
Returns True if t1 and t2 are the same shape.
False, otherwise."""
if t1 and t2:
return len(t1) == len(t2)
return False |
def calculate_plane_coords(coords_list, infile_dims):
"""Calculate the coordinates of the triangular plane spanning from roughly
around the participant's nose, down to roughly below the rear of the neck.
:type coords_list: list
:param coords_list: A list of lists, describing the three coordinate
... |
def countHits(hitMap):
"""
bin counts by hit and find total
return map from assignments to number of reads
"""
total = 0
counts = {}
if isinstance(hitMap, dict):
hitIter = hitMap.items()
else:
hitIter = hitMap
for (read, hit) in hitIter:
total += 1
if ... |
def merge_dict_list(merged, x):
""" merge x into merged recursively.
x is either a dict or a list
"""
if type(x) is list:
return merged + x
for key in x.keys():
if key not in merged.keys():
merged[key] = x[key]
elif x[key] is not None:
merged[key... |
def unique_cluster_indices(cluster_indx):
"""
Return a unique list of cluster indices
:param cluster_indx: Cluster index list of ClusterExpansionSetting
"""
unique_indx = []
for symmgroup in cluster_indx:
for sizegroup in symmgroup:
for cluster in sizegroup:
... |
def jaccard(list1,list2):
"""
Berechnet Jaccard-Koeffizienten
:param list1: tokenliste 1
:param list2: tokenliste 2
:return: Jaccard-Koeffizient
"""
s1 = set(list1)
s2 = set(list2)
return (len(s1.intersection(s2)) / len(s1.union(s2))) |
def PF_op_pw(u, df, inverses, x):
"""
PERRON-FROBENIUS OPERATOR POINTWISE
Arguments:
- <u> a function with one argument
- <df> a function: the derivative of the dynamical system function f
(should take one arg)
- <inverses> a list of functions, each taking one argument, that find the
... |
def where(condition, x=None, y=None):
"""
where(condition, [x, y])
Return elements chosen from `x` or `y` depending on `condition`.
.. note::
When only `condition` is provided, this function is a shorthand for
``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
... |
def alignmentTo1(alignment):
"""Converts an alignment to one-level by ignoring lower level."""
return [ (startTime, endTime, label, None)
for startTime, endTime, label, subAlignment in alignment ] |
def updata_data_dict(key_name, data_key, data_value, data_dict={}):
"""
updates the data dictionary
:param key_name:
:param data_key:
:param data_value:
:return:
"""
if data_key not in data_dict[key_name]:
data_dict[key_name][data_key] = ()
data_dict[key_name][data_key] = dat... |
def repr_tree_defs(data, indent_str=None):
"""return a string which represents imports as a tree"""
lines = []
nodes = data.items()
for i, (mod, (sub, files)) in enumerate(sorted(nodes, key=lambda x: x[0])):
if not files:
files = ''
else:
files = '(%s)' % ','.join... |
def set_nested_item(d, list_of_keys, value):
"""Sets the item from a nested dictionary. Each key in list_of_keys is
accessed in order and last item is the one set. If value is None, item is
removed.
Args:
d: dictionary
list_of_keys: list of keys
value: new value
Returns: d ... |
def _get_memo_name(city, prov):
"""Create composite key of format 'City, Province' for memoization."""
return '{0}, {1}'.format(city, prov) |
def remove_end_chars(text: str, char: str) -> str:
"""
Recursively remove a specific trailing character until none are left.
Args:
text (str): text to be modified
char (str): character to remove
Returns:
str: the original text with all of the characters removed from the end
... |
def get_image_count(image_urls):
"""
:param image_urls: A string that contains image urls separated by the | symbol
:return: the amout of image urls in the string
"""
return image_urls.count("|") + 1 |
def dehumanize(size):
"""converts humanized size to bytes
>>> dehumanize(20K)
20480
>>> dehumanize(2000)
2000
>>> dehumanize(2M)
2097152
>>> dehumanize(1G)
1 * (1024 ** 3)
"""
if size.isdigit(): return float(size)
eq = {'K': 1024, 'M':1024 ** 2, 'G':1024 ** 3}
value,... |
def combine_similarity_and_feedback_score(feedback_score, similarity_score, alpha=0.5):
"""
Compute the combination of embedding similarity and feedback score
Input: feedback_score: feedback score computed by compute_feedback_score, if no feedbacks, default to (1 - alpha)
similarity_score: si... |
def correct_gravity(sg, temp, cal_temp):
"""Correct a specific gravity reading to the specified calibration temperature
Args:
sg (float): Measured specific gravity
temp (float): Measurement temperature in degrees Fahrenheit
cal_temp (float): Hydrometer calibration temperature in degrees... |
def oc_sched(row):
"""Create opencast schedule for an event"""
sched = {
"agent_id": row["location"],
"start": row["startTime"],
"end": row["stopTime"],
"inputs": ["camera", "screen", "AudioSource"],
}
return sched |
def _simplify(str_):
"""Simplify source line"""
return str_.strip() |
def get_cut_limbs(life):
"""Returns list of cut limbs."""
_cut = []
for limb in life['body']:
if life['body'][limb]['cut']:
_cut.append(limb)
return _cut |
def add_extension(name, extension):
"""Adds an extension to the name if necessary
Example:
>>> add_extension('myfile', '.csv')
>>> 'myfile.csv'
"""
return name if name.endswith(extension) else name + extension |
def updateBounds(bounds, p, min=min, max=max):
"""Return the bounding recangle of rectangle bounds and point (x, y)."""
(x, y) = p
xMin, yMin, xMax, yMax = bounds
return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y) |
def is_float(x):
"""Is a string a float?. Return a bool."""
try:
float(x)
return True
except ValueError:
return False |
def is_unique_no_additional_ds(s: str):
"""
Since we cannot modify a string, I've had to create a list from the string.
If we are provided a mutable string, we could sort in place.
Time: O(n log(n)), Space: O(1)
"""
l = list(sorted(s))
for i, c in enumerate(l):
if i < len(l) - 2:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.