content stringlengths 42 6.51k |
|---|
def normalize_float(v: float, lower_bound: float, upper_bound: float) -> float:
"""Normalizes ``v`` between ``lower_bound`` and ``upper_bound``
Assumes (and will not check) that `lower_bound <= v <= upper_bound`
:param v: the value to be normalized
:param lower_bound: the supposedly lowest possible va... |
def is_bin_log(reg_type):
"""
Checks whether a regression type is binomial.
"""
return reg_type == "binomial" |
def _num_items_2_heatmap_square_figsize(n):
""" uses linear regression model to infer adequate figsize
from the number of items
Data used for training:
X = [4, 8, 9, 10, 11, 15, 22, 26]
y = [[4,4],[5,5],[5,5],[6,6],[8,8],[8,8],[10,10],[11,11]]
Parameters
----------
n : int
... |
def merge_dict(*sources, dest=None):
"""Merge `sources` into `dest`.
`dest` is altered in place.
"""
if dest is None:
dest = {}
for source in sources:
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
n... |
def get_metrics_by_name(metrics, names):
"""
Function:
get_metrics_by_name
Description:
Return metrics that match the selected names.
Input:
- metrics,list: List of Metric objects
- names,list: List of metric names
Output:
L... |
def _gbd(n):
"""Compute second greatest base-2 divisor"""
i = 1
if n <= 0: return 0
while not n % i:
i <<= 1
return i >> 2 |
def is_palindrome(num):
"""Check if palindrome."""
# Skip single-digit inputs
if num // 10 == 0:
return False
temp = num
reversed_num = 0
while temp != 0:
reversed_num = (reversed_num * 10) + (temp % 10)
temp = temp // 10
if num == reversed_num:
return num |
def set_key(context, key):
"""populates variable into a context"""
if key:
context['key'] = key
else:
context['key'] = ''
return '' |
def binary_search(alist, item):
"""
Iterative Binary Search.
O(log(n)) time complexity.
:type alist ordered values.
:type the item to find.
:rtype True or False if item is in list.
"""
left = 0
right = len(alist) - 1
# iterate while left index isn't
# greater than the right index.
while left <=... |
def _must_be_false(values):
"""Root validator to be added to ChildModel."""
assert not values.get("field_a")
return values |
def get_incoming_value( incoming, key, default ):
"""
Fetch value from incoming dict directly or check special nginx upload
created variants of this key.
"""
if "__" + key + "__is_composite" in incoming:
composite_keys = incoming["__" + key + "__keys"].split()
value = dict()
... |
def caption_fmt(caption):
""" Format a caption """
if caption:
return "\n== {} ==\n".format(caption)
return "" |
def improve(update, close, guess=1):
"""When a higher order function as this is called, it first creates the frame with the function and assign
the name of arguments with the actual functions are called.
Then in this case, resolve each of the assigned functions first before doing the computations ins... |
def get_most_often_item(items=[]):
"""
:param items: item list to find out the most frequently occurred
:return: one object from the item list
"""
if len(items) == 0:
return 'Not existed'
from collections import Counter
item_counter = Counter(items)
most_popular = item_counter.... |
def lcfirst(string):
"""
Convert the first character of a string to lowercase.
"""
return string[:1].lower() + string[1:] |
def outer_product(A, B):
"""
Returns `outer_product` from a pair of vectors wherein
`B` is transposed into a row vector and `A` is a column vector.
Parameters
----------
A : list
The given left-hand side matrix.
B : list
The given right-hand side transposed matrix.
Ret... |
def string_words_reverse(string) -> str:
"""This function put string words in opposite direction."""
return ' '.join(reversed(string.split())) |
def url_params(url):
"""
Gets the URL query paramters.
:param url:
:type url: str
:returns: The url paramters.
:rtype: str
"""
query_params = {}
if "?" in url:
params_str = url[url.find("?") + 1:]
if "&" in params_str:
params = params_str.split("&")
... |
def rescale(val, lims):
"""function takes a value between 0 and 1 and normalizes it between the limits in lims"""
new_val = (val*(lims[1]-lims[0])) + lims[0]
return new_val |
def norm_float(string):
"""Normalize a float value."""
if string.lower().endswith(('e-', 'e+', 'e')):
string += '0'
return float(string) |
def is_unique(l):
"""Check if all the elements in list l are unique."""
assert isinstance(l, list), "Type %s is not list!" % type(l)
return len(l) == len(set(l)) |
def evaluate(ranks, expects, pos):
""" Evaluate the ranking algorithms seeing the expected place_id in the
rank higher than given pos
@arg ranks list() of ranks returned by ranke()
@arg expects list() of expected labels
@arg pos the given position seen as length of system return... |
def array_merger(list1, list2):
""" Variables to iterate through the lists """
i = j = 0
merged_list = []
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
... |
def sort_words(string_in):
"""
:param string_in:
:return list_string:
Takes a string and returns a sorted list of the string's contents
If the input string is empty it returns an empty list
"""
if string_in == '':
return []
split_string = string_in.split(' ', string_in.count('... |
def validate(compression):
"""
Validate the compression string.
Parameters
----------
compression : str, bytes or None
Returns
-------
compression : str or None
In canonical form.
Raises
------
ValueError
"""
if not compression or compression == b'\0\0\0\0'... |
def convert_data_integer(data):
"""
convert data to integer
"""
if data is not None:
return data.astype(int)
else:
return data |
def _fix_user_options(options):
"""
This is for Python 2.x and 3.x compatibility. distutils expects Command
options to all be byte strings on Python 2 and Unicode strings on Python 3.
"""
def to_str_or_none(x):
if x is None:
return None
return str(x)
return [tuple(... |
def first_and_last(sequence):
"""Returns the first and last elements of a sequence"""
return sequence[0], sequence[-1] |
def in_range(x, a1, a2):
"""Check if (modulo 360) x is in the range a1...a2. a1 must be < a2."""
a1 %= 360.
a2 %= 360.
if a1 <= a2: # "normal" range (not including 0)
return a1 <= x <= a2
# "jumping" range (around 0)
return a1 <= x or x <= a2 |
def gettext(node):
"""
Get node text
"""
if node is None:
return None
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
return child.data
return None |
def get_max_elements_in_row(row: list) -> int:
"""
Loops through the dataset and gets the max elements in a list if
one is found in the list or 1 if all strings.
"""
max_array_count = 0
# get the max height of the cells.
for item in row:
if isinstance(item, list) and len(item) > max... |
def apply_policy(policy, r, name, sub):
"""
Apply the list of policies to name.r,sub
Parameters
----------
policy
List of functions that map a L{Variable} to a string,
or a single such function.
r: L{Variable}
Returns
-------
object
C{policy[0](r) + policy[1... |
def concatenateToken(tokens):
"""
Concatenate the n-grams into a single string taking
into account the number of occurrences.
It is needed because the models works on String only.
:param tokens: Map of n-grams occurrences
:type tokens: {Int:{String:Int}}
:return: Co... |
def _GetStrippedPath(bin_path):
"""Finds the stripped version of the binary |bin_path| in the build
output directory."""
return bin_path.replace('lib.unstripped/', 'lib/').replace(
'exe.unstripped/', '') |
def RK2(diffeq, y0, t, h):
""" RK2 method for ODEs:
Given y0 at t, returns y1 at t+h """
k1 = h*diffeq(y0, t) # get dy/dt at t first
k2 = h*diffeq(y0+0.5*k1, t + h/2) # get dy/dt at t+h/2,
return y0 + k2 # calc. y1 = y(t+h) |
def catalan_dp(n):
"""
dynamic programming based function
O(n**2)
"""
if n < 2:
return 1
catalan = [0 for _ in range(n + 1)]
catalan[0], catalan[1] = 1, 1
for i in range(2, n + 1):
catalan[i] = 0
for j in range(i):
catalan[i] = catalan[i] + catalan[j] ... |
def lengths_to_volume(width, height, depth):
"""Compute volume from linear measurements of a box"""
# included for demonstration purposes
return width * height * depth |
def mean(data):
"""
function to calculate mean of data
"""
size = len(data)
mean = sum(data)/size
return mean |
def insert_aux(seq):
"""
Auxiliary function for insert_at_junctions
Returns the first element encountered
"""
list_insert = ["GGCAT", "GCAT", "CAT"]
for insert in list_insert:
if insert in seq:
return insert
return "-" |
def _validate_extension(data):
"""Detect if a package is an extension using its metadata.
Returns any problems it finds.
"""
jlab = data.get('jupyterlab', None)
if jlab is None:
return ['No `jupyterlab` key']
if not isinstance(jlab, dict):
return ['The `jupyterlab` key must be a... |
def sanitize_string(string):
"""Sanitizes a string for it to be between U+0000 and U+FFFF"""
if string:
return ''.join(c for c in string if ord(c) <= 0xFFFF).strip() |
def compute_deviated_angles_color_aberration(eta, zeta, color, error):
"""
Implementation of chromatic aberration
:param eta:
:param zeta:
:param color:
:param error:
:returns:
* eta deviated by the aberration
* zeta deviated by the aberration
"""
parameter = 1/10
... |
def isCallable( obj ):
"""
Returns a boolean whether or not 'obj' is callable (read as function
or method).
"""
# PY3k Note: Python 3.0/3.1 don't have callable() but it's back in 3.2
return callable( obj ) |
def sanitize_id(int_id):
"""
Return int_id as either an integer or None, if it is not convertible.
For use with model find function where either integer or None is acceptable, but
input from the controller is either a string representation of the integer or None.
This handles the conversion and swa... |
def primary_cat(catstr):
"""Return the primary category from a rider cat list."""
ret = u''
cv = catstr.split()
if cv:
ret = cv[0].upper()
return ret |
def vis7(n): # DONE
"""
OOO OO OO
OOO OO
OOO
Number of Os:
3 5 7"""
result = ''
for i in range(n - 1):
result += 'OO\n'
result += 'OOO\n'
return result |
def smoothstep(a, b, x):
""" Returns a smooth transition between 0.0 and 1.0 using Hermite interpolation (cubic spline),
where x is a number between a and b. The return value will ease (slow down) as x nears a or b.
For x smaller than a, returns 0.0. For x bigger than b, returns 1.0.
"""
if ... |
def toGraphicsObjectIfPossible(item):
"""Return the item as a QGraphicsObject if possible.
This function is intended as a workaround for a problem with older
versions of PyQt (< 4.9), where methods returning 'QGraphicsItem *'
lose the type of the QGraphicsObject subclasses and instead return
generi... |
def generate_solution(x: int, n: int) -> int:
"""This is the "naive" way to compute the solution, for testing purposes.
In this one, we actually run through each element.
"""
counter = 0
for i in range(1, n + 1):
for j in range(1, n + 1):
if i * j == x:
counter +... |
def ceildiv(a, b):
"""Divides with ceil.
E.g., `5 / 2 = 2.5`, `ceildiv(5, 2) = 3`.
Args:
a (int): Dividend integer.
b (int): Divisor integer.
Returns:
int: Ceil quotient.
"""
return -(-a // b) |
def distance_calc(s1, s2):
"""
Calculate Levenshtein distance between two words.
:param s1: first string
:type s1 : str
:param s2: second string
:type s2 : str
:return: distance between two string
References :
1- https://stackoverflow.com/questions/2460177/edit-distance-in-python
... |
def _list_fieldnames(task, excluded):
"""
Lists all fields on given "task" Model object,
getting rid of those listed in "excluded", if any.
Parameters:
excluded: a string containing a (possibly empty) list of fieldnames to be excluded, separated by ','
Returs:
a list of fieldnames
... |
def reverse_digit(x):
"""
Reverses the digits of an integer.
Parameters
----------
x : int
Digit to be reversed.
Returns
-------
rev_x : int
`x` with it's digits reversed.
"""
# Initialisations
if x < 0:
neg = True
else:
neg ... |
def snake_to_camel(text):
"""Convert string in snake_case to camelCase."""
text_parts = text.split('_')
return ''.join(word.capitalize() for word in text_parts) |
def text2caesar(text,shift = 3):
"""
Returns the encrypted text after encrypting the text with the given shift
Parameters:
text (str): The text that needs to be encrypted in Caesar's cipher
shift (int): The shift that should be used to encrypt the text
Returns:
result (str): The encrypted text
"""
... |
def list_inventory(inventory):
"""
:param inventory: dict - an inventory dictionary.
:return: list of tuples - list of key, value pairs from the inventory
dictionary.
"""
return [(key, val) for key, val in inventory.items() if val > 0] |
def log2(num):
"""
Integer-valued logarigthm with base 2.
If ``n`` is not a power of 2, the result is rounded to the smallest number.
"""
pos = 0
for pow_ in [16, 8, 4, 2, 1]:
if num >= 2 ** pow_:
num //= (2 ** pow_)
pos += pow_
return pos |
def OR(*expressions):
"""
Evaluates one or more expressions and returns true if any of the expressions are true.
See https://docs.mongodb.com/manual/reference/operator/aggregation/or/
for more details
:param expressions: An array of expressions
:return: Aggregation operator
"""
return {'... |
def find_largest_digit_helper(n, greater):
"""
This function is the helper of find_largest_digit(n)
:param n: int, the input number
:param greater: int, the greater number within n
:return: return greater
"""
if n != 0:
if n % 10 > greater:
greater = n % 10
return find_largest_digit_helper(n//10, greater)... |
def get_float_advanced(v, multiplier=1):
""" Gets float value converting K,M,B into numerical values
multiplier allows additional transformation
"""
try:
if v is None:
return None
sign = 1
if v.startswith('(') and v.endswith(')'):
sign = -1
v... |
def _is_bst(root, min_value=float('-inf'), max_value=float('inf')):
"""Check if the binary tree is a BST (binary search tree).
:param root: Root node of the binary tree.
:type root: binarytree.Node | None
:param min_value: Minimum node value seen.
:type min_value: int | float
:param max_value: ... |
def list_sorted(words):
""" Check if a Tuple of words are Anagrams using Sorted
:param words: Tuple
:return: bool
"""
word_one, word_two = words
return sorted(word_one) == sorted(word_two) |
def check(spotList, occupied, width, height):
"""
_Purpose:
takes a move coord and returns a score (max 4) based on how many free spaces are directly around the move
_Parameters:
spotList (list): xy tuples of positions to score
occupied (list): xy coords all occupied spaces on board
width (int): width of board... |
def is_operand(c):
"""
Return True if the given char c is an operand, e.g. it is a number
>>> is_operand("1")
True
>>> is_operand("+")
False
"""
return c.isdigit() |
def is_name_private(name, public=None):
"""
Answers whether the name is considered private, by checking the leading underscore.
A ist of public names can be provided which would override the normal check
"""
if public and name in public:
return False
return name.startswith('_') |
def count_gender_subj_obj(tree):
"""
This function takes in a tree of dependency triples for a list of sentence and counts female
and male subject and object occurrences
We have chosen not to include indirect object positions because whether or not they represent
passivity (at least, compared to be... |
def _diff_attribute_values(old_value, new_value):
"""Returns True if the attribute values are different."""
are_different = len(old_value) != len(new_value)
if not are_different:
old_value_dict = dict.fromkeys(old_value)
new_value_dict = dict.fromkeys(new_value)
for value in old_valu... |
def quadratic_ease_out(p):
"""Modeled after the parabola y = -x^2 + 2x"""
return -(p * (p - 2)) |
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korea... |
def _str_to_bool(s):
"""
Convert a string value to a boolean.
True values are "y", "yes", "t", "true", "on" and "1", regardless of capitalization.
False values are "n", "no", "f", "false", "off" and "0", regardless of capitalization.
"""
trueVals = ["y", "yes", "t", "true", "on", "1"]
falseVals = ["n", "... |
def check_nearly_equal(value1, value2, dE=1e-5):
"""
Check that two values are nearly equivalent by abs(val1-val2) < abs(dE*val1)
"""
if (abs(value1 - value2) <= abs(dE * value1) or
abs(value1 - value2) <= abs(dE * value2) or
abs(value1 - value2) <= dE):
return True
... |
def parse_packet(line):
""" Input: message in packet payload
Returns:
"""
# Assumes message structure:
# "Id & RSSI,%d %d %d\n"
# If any part was unsuccessfully parsed, return None
(tmote_ID, rssi) = (None, None)
# Split the message
line_list = line.split(",")
if (len(line_list) == 2):
data = line_list[1... |
def bodyContainsKeyword(body, keywords):
"""
Returns a keyword if any word in the body matches a word from the
keywrods set.
"""
body_words = body.split()
for word in body_words:
if word in keywords:
return word
return '' |
def _find_channels(ch_names, ch_type='EOG'):
"""Find EOG channel."""
substrings = (ch_type,)
substrings = [s.upper() for s in substrings]
if ch_type == 'EOG':
substrings = ('EOG', 'EYE')
eog_idx = [idx for idx, ch in enumerate(ch_names) if
any(substring in ch.upper() for subst... |
def max_min_median(array: list) -> tuple:
"""Calculate a max, a min, and a median
using only if, for, else"""
ordered_array = []
if len(array) < 2:
ordered_array = array
median = ordered_array[0]
else:
# Sort an array
for i, element in enumerate(array):
... |
def is_special_method(name):
"""
Test if callable name is a special Python method.
:param name: Callable name
:type name: string
:rtype: boolean
"""
return name.startswith("__") |
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
h... |
def get_opponent_player_index(active_player_index):
"""
get_opponent_player_index: Gets the env.Players Enum value of the non active player.
:param active_player_index: env.Players Enum of the active player
:return: The env.Players Enum of the inactive player.
"""
if active_player_index:
... |
def _create_notif_data_was_deleted(assessments_ids):
"""Create data in format applicable for template rendering
for asmnts, deleted during bulk operation."""
result = [
{"id": assessments_id} for assessments_id in assessments_ids
]
return result |
def idslist(data):
"""
Returns list of user id's of all users.
"""
return [u['id'] for u in data['users']] |
def IF_NULL(expression, _else):
"""
Evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value.
See https://docs.mongodb.com/manual/reference/operator/aggregation/ifNull/
for more details
:param expression: expression that will be evaluated
:p... |
def _normalize_media_type(s):
"""Strip out the white space between parameters; doesn't need to fully
parse the types because it's applied to values of _raw (or to input that'll
eventually be compared to them and fail)"""
return s.replace('; ', ';') |
def resultsToLine(seed,
est,
hasMet, tau, nStep, nXstep,
timeTaken):
"""
Convert estimation results to string, taking 8 digits after decimal.
Input:
est: (M,) list or array, estimates for hFunction
tau: scalar, meeting time
n... |
def setWithDefault(dict, key, default):
""" Return value for the specified key set via the config file. Use the default when the
value is blank or doesn't exist """
value = dict.get(key, default)
if value != None and value != '':
return value
return default |
def decode(string):
"""Ensure that `string` is in unicode format."""
if hasattr(string, "decode"):
return string.decode("utf-8")
return string |
def get_eso_file_version(raw_version):
"""Return eso file version as an integer (i.e.: 860, 890)."""
version = raw_version.strip()
start = version.index(" ")
return int(version[(start + 1) : (start + 6)].replace(".", "")) |
def _GetProcStatusPath(pid):
"""Returns the path for a PID's proc status file.
@type pid: int
@param pid: Process ID
@rtype: string
"""
return "/proc/%d/status" % pid |
def repr2(x):
"""Analogous to repr(),
but will suppress 'u' prefix when repr-ing a unicode string."""
s = repr(x)
if len(s) >= 2 and s[0] == "u" and (s[1] == "'" or s[1] == '"'):
s = s[1:]
return s |
def has_method(obj, name):
""" Returns true if the object has a method and false otherwise. """
return callable(getattr(obj, name, None)) |
def textops_rawtexttolines(text, linedelimiter="\n"):
"""
<Purpose>
Converts raw text (a string) into lines that can be processed by the
functions in this module.
<Arguments>
text:
The text to convert into lines (basically, a sequence of strings).
linedelimiter (optional, defaults to... |
def lr_schedule(epoch):
"""Learning Rate Schedule
Learning rate is scheduled to be reduced after 30, 60, 90, 120 epochs.
Called automatically every epoch as part of callbacks during training.
# Arguments
epoch (int): The number of epochs
# Returns
lr (float32): learning rate
"... |
def level_from_xp(exp: int):
"""Returns the level for the specified amount of EXP.
Parameters
----------
exp: int
The amount of EXP to find the level foor.
Returns
-------
int:
The level for the specified amount of EXP.
"""
level = int(((exp + 1) * 2) ** (1 / 3))
... |
def generate_gitignore(artifacts):
"""Generates a .gitignore file that excludes nonlocal artifacts."""
return '\n'.join('/' + artifact['path'] for artifact in artifacts
if 'local' not in artifact or not artifact['local']
or artifact.get('gitignore', False)) |
def cal_sort_key(cal):
"""
Sort key for the list of calendars: primary calendar first,
then other selected calendars, then unselected calendars.
(" " sorts before "X", and tuples are compared piecewise)
"""
if cal["selected"]:
selected_key = " "
else:
selected_key = "X"
... |
def _intersect_items(baselist, comparelist):
"""Return matching items in both lists."""
return list(set(baselist) & set(comparelist)) |
def name_from_metal(metal, namedict, sep=None):
"""
Returns a funciton 'beautify names' that generates names
according to: beautify_names(oldname) -> newname_oldname
:param namedict:
:return:
"""
if sep is None:
sep = '_'
newname = sep.join([namedict.get(metal, metal), metal])
... |
def convert_macaddr(addr):
"""Convert mac address to unique format."""
return addr.replace(':', '').lower() |
def _hex_to_int(hexstring: str) -> int:
"""Converts a hex string representation of an integer to an integer.
"""
return int(hexstring, 16) |
def sort_dict(src_dict):
"""
Sort given dictionary
:param src_dict: source dict
:return: sorted dictionary
"""
sorted_dict = {k: src_dict[k] for k in sorted(src_dict.keys())}
return sorted_dict |
def clean_list(self, repeats_list):
"""
Removes all values in a list that equal '' or 'endrepeat':
If there are nested lists, it recursively calls itself to search those
too.
"""
for j, item in reversed(list(enumerate(repeats_list))):
if isinstance(item, list):
item =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.