content stringlengths 42 6.51k |
|---|
def derivative_tanh(tanh_output):
""" Compute derivative of Tanh function """
return 1 - tanh_output**2 |
def collect_not_null_kwargs(**kwargs) -> dict:
"""
Collect not null key value pair from keyword arguments.
.. versionadded:: 1.0.1
"""
return {
k: v
for k, v in kwargs.items()
if v is not None
} |
def ordinal(i):
"""Returns i + the ordinal indicator for the number.
Example: ordinal(3) => '3rd'
"""
i = int(i)
if i % 100 in (11,12,13):
return '%sth' % i
ord = 'th'
test = i % 10
if test == 1:
ord = 'st'
elif test == 2:
ord = 'nd'
elif test == 3:
... |
def str_product(string):
""" Calculate the product of all digits in a string """
product = 1
for i in string:
product *= int(i)
return product |
def solution(n, array):
"""
Returns n counters after the increment and max operations coded in array.
It iterates over array once and over the counters once, thus the time complexity is O(n + m)
"""
counters = [0] * n
# Current greatest value calculated so far
max_count = 0
# Value in max when t... |
def choose(n: int, k: int) -> int:
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
... |
def _roundsf(x, n):
"""
Round to n significant digits
"""
return float('{:.{p}g}'.format(x, p=n)) |
def valid_num_brackets(expression: list) -> int and int:
"""Check the brackets in the expression.
Returns:
int and int: number of open brackets and number of close brackets.
"""
brackets = 0
for item in expression:
if item == '(':
brackets += 1
elif item == ')':
... |
def revcompSeq(seq):
"""
Get reverse complementary sequence
"""
return seq.translate(str.maketrans("ACGTN", "TGCAN"))[::-1] |
def read_values(xs, sep, *values):
"""Read values from a string.
Args:
xs (str): Values as one string.
sep (str): Separator separating the values in the string.
*values (str): Names of the values.
Returns:
dict: Naming of the values mapping to the values.
"""
xs = [... |
def strip_punctuation_space(value):
"""
Strip excess whitespace prior to punctuation
using recursion
"""
if (value == None):
return None
elif (type(value) == list):
# List, so recursively strip elements
for i in range(0, len(value)):
value[i] = strip_punctuation_space(value[i])
return value
else:
tr... |
def iob_iobes(tags):
"""
IOB -> IOBES
"""
new_tags = []
for i, tag in enumerate(tags):
if tag == "O":
new_tags.append(tag)
elif tag.split("-")[0] == "B":
if i + 1 != len(tags) and tags[i + 1].split("-")[0] == "I":
new_tags.append(tag)
... |
def _capture_callback(x):
"""Validate the passed options for capturing output."""
if x in [None, "None", "none"]:
x = None
elif x in ["fd", "no", "sys", "tee-sys"]:
pass
else:
raise ValueError("'capture' can only be one of ['fd', 'no', 'sys', 'tee-sys'].")
return x |
def mapz(function, list_of_args):
"""Just the *map* function with the *list* function applied afterwards. Ah, GwR..."""
return list(map(function, list_of_args)) |
def gen_urdf_visual(geom, material, origin):
"""
Generates (as a string) the complete urdf element sequence for a `visual` child
of a `link` element. This is essentially a string concatenation operation.
:param geom: urdf element sequence for the geometry child of a visual element, ``str``
:param m... |
def get_embedded_items(result_collection):
"""
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of embedded items with each item in the returned list
considered a result object.
'result_collection' a JSON ob... |
def get_bool(env, name, default=False):
"""Get a boolean value from the environment
If ``name`` is not found in ``env``, return ``True`` if ``default``
evaluates to ``True``, otherwise return ``False``.
The following values are considered ``False``:
* ``'False'``
* ``'false'``
... |
def cutoff(s, length):
"""Truncates a string after a certain number of characters.
:type s: str
:param s: string to be truncated
:type length: int
:param length: max number of characters
:rtype: str
:return: truncated string"""
if len(s) < length-2:
return s
return "%s.." % ... |
def getConditionInZoneConditions(zone_condition, zone_conditions_data):
"""
Parses the zone conditions definition YAML files to find the condition
that match both the zone condition passed in.
"""
condition = {}
for c in zone_conditions_data['conditions']:
if zone_condition != c['name... |
def formatColorfa(a):
"""float array to #rrggbb"""
return '#%02x%02x%02x' % (int(round(a[0]*255)),int(round(a[1]*255)),int(round(a[2]*255))) |
def ssh_cmd_container_instance(detail) -> str:
"""SSH command to access a ecs2 instance by id."""
return f"TERM=xterm ssh {detail['ec2InstanceId']}" |
def extract_user_info(client_config):
"""
Extract user info from the client config specified. Returns a dict
that includes system key information.
"""
# test if there isn't a system user or if there isn't a name for that
# user, return None
if ('system user' not in client_config or
... |
def jupyter_config_json(
package_name: str,
enabled: bool = True
) -> dict:
"""Creates a Jupyter Config JSON file with one package defined."""
return {
"NotebookApp": {
"nbserver_extensions": {
package_name: enabled
}
}
} |
def orthogonal(vector):
"""
:return: A new vector which is orthogonal to the given vector
"""
return vector[1], -vector[0] |
def SIRD_model(t, y, b, g, l, N):
"""Gives the derivative of S, I, R, and D with respect to time at some t
Parameters:
t - The time at which the derivative is to be calculated
y - Value of S, I, R, and D at t
b - Parameter beta in the ODEs
g - Parameter gamma in the ODEs
l - Parameter lambd... |
def mappingIndexItemToName(index):
"""
Return the itemCode from itemID
:param index: int
:return: string, itemCode
"""
if index == 0:
return 'R11'
elif index == 1:
return 'R12'
elif index == 2:
return 'R13'
elif index == 3:
return 'R14'
elif index... |
def bytes_to_str(s):
"""Convert bytes to str."""
if isinstance(s, bytes):
return s.decode(errors='replace')
return s |
def hard_retype(value):
"""
tries to converts value to relevant type by re-typing
:param value: value to be converted
:type value: str (unicode)
:return: re-typed value
:rtype: int, float, bool, str
"""
try:
return int(value)
except ValueError:
try:
retur... |
def remove_comments(s):
"""removes the comments starting with # in the text."""
pos = s.find("#")
if pos == -1:
return s
return s[0:pos].strip() |
def _long_to_bytes(n, length, byteorder):
"""Convert a long to a bytestring
For use in python version prior to 3.2
Source:
http://bugs.python.org/issue16580#msg177208
"""
if byteorder == 'little':
indexes = range(length)
else:
indexes = reversed(range(length))
return byte... |
def dotp(a, b):
"""Dot product of two equal-dimensioned vectors"""
return sum(aterm * bterm for aterm,bterm in zip(a, b)) |
def get_value(dict, key, default=None):
"""Set value to value of key if key found in dict, otherwise set value to
default."""
value = dict[key] if key in dict else default
return value |
def _shape_from_resolution(resolution):
"""
Calculate the shape of the global Earth relief grid given a resolution.
Parameters
----------
resolution : str
Same as the input for load_earth_relief
Returns
-------
shape : (nlat, nlon)
The calculated shape.
Examples
... |
def scaleto255(value):
"""Scale to Home-Assistant value."""
return max(0, min(255, round((value * 255.0) / 100.0))) |
def find_numbers(data):
""" Recursively find numbers in JSON data except dicts with "red" value """
if isinstance(data, int):
return [data]
numbers = []
if isinstance(data, list):
for dat in data:
numbers.extend(find_numbers(dat))
elif isinstance(data, dict):
if "... |
def find_dict_in_list_from_key_val(dicts, key, value):
""" lookup within a list of dicts. Look for the dict within the list which has the correct key, value pair
Parameters
----------
dicts: (list) list of dictionnaries
key: (str) specific key to look for in each dict
value: value to match
... |
def valid(bo, pos, num):
"""
Returns if the attempted move is valid
:param bo: 2d list of ints
:param pos: (row, col)
:param num: int
:return: bool
"""
# Check row
for i in range(0, len(bo)):
if bo[pos[0]][i] == num and pos[1] != i:
return False
... |
def pair(pairstr):
"""Convert NxN or N,N to tuple."""
return tuple(int(_s) for _s in pairstr.replace('x', ',').split(',')) |
def get_user_choice(choices, choice_type, default_value=""):
"""
A common method to take user choice from a list of choices
Args:
(list) choices - list of choices
(str) choice_type - Type of choice
(boolean) default_value - Return default value in case wrong input
Returns:
... |
def maximumProduct(nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
first_option=nums[0]*nums[1]*nums[-1]
second_option=nums[-3] * nums[-2] * nums[-1]
return first_option if first_option > second_option else second_option |
def col_shade(s):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'rgba(0,0,0,0.5)'
return 'background-color: {}'.format(color) |
def gameLogic(compChoice, userChoice):
""" This is the main game logic function which takes computers choice and user's choice as input.
This function can retrun three variables based on status of winning, losing or tie."""
#If computer chooses rock
if compChoice == 'r':
if userChoice == 'r': ... |
def fibonacci(n):
"""Compute the nth fibonacci number recursively."""
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2) |
def split_list(category_list):
"""
Split list of ranges into intervals and single char lists.
:return: List of interval starting points, interval lengths and single chars
"""
unicode_category_interval_sps = []
unicode_category_interval_lengths = []
unicode_category_chars = []
for elem... |
def get_class_methods(cls):
""" Get a list of non-private class methods. """
return [getattr(cls, func) for func in dir(cls) if not func.startswith("__") and callable(getattr(cls, func))] |
def normalise_email(email):
"""
The local part of an email address is case-sensitive, the domain part
isn't. This function lowercases the host and should be used in all email
handling.
"""
clean_email = email.strip()
if '@' in clean_email:
local, host = clean_email.rsplit('@', 1)
... |
def read_until(steg_bytes: bytes, offset: int, ending: str):
"""
Read the bytes of the steg_bytes from the offset until the ending byte sequence is found.
Return the bytes read and the offset of the ending byte sequence.
"""
# Create a variable to hold the bytes read
bytes_read = b""
... |
def text_progress_bar(iteration, num_iteration):
"""Displays a progress bar with the print function"""
return print('|' * (iteration + 1) + '.' * (num_iteration - iteration - 1) + ' %.1f %%' % ((iteration + 1) / num_iteration * 100), end='\r') |
def partition_to_color(partitions):
"""
Creates a dictionary with for every item in partition for every partition
in partitions the index of partition in partitions.
Parameters
----------
partitions: collections.abc.Sequence[collections.abc.Iterable]
As returned by :func:`make_partition... |
def build_json(image_content):
"""Builds a json string containing response from vision api."""
json_data = {
'requests': [{
'image': {
'content': image_content
},
'features': [{
'type': 'FACE_DETECTION',
'maxResults': 1,
}]
... |
def split_names(output):
"""
Designed to split up output from -o=name into a
simple list of qualified object names ['kind/name', 'kind/name', ...]
:param output: A single string containing all of the output to parse
:return: A list of qualified object names
"""
if output is None:
ret... |
def task_request_statistics(contributions):
"""
Returns a list of task requests.
"""
task_requests = []
for contribution in contributions:
# If contribution wasn't staff picked skip it
if "task" in contribution["category"]:
task_requests.append(contribution)
return {... |
def check_bbox_in_image(bbox, img_shape):
"""Ensure that all annotations are in the image and start at pixel 1 at a minimum
Args:
bbox (list) : list of [x_min, y_min, x_max, y_max]
img_shape (tup) : shape of image in the form: (y, x, channels)
Returns:
bbox (list) : list of... |
def _dec(A):
"""
>>> _dec([])
0
>>> _dec([1])
1
>>> _dec([1, 0, 1])
5
"""
sum = 0
for i, a in enumerate(A):
sum += a*(1 << i)
return sum |
def conv_time(s):
""" Convert seconds into readable format"""
one_min = 60
one_hr = 60 * 60
one_day = 24 * 60 * 60
try:
s = float(s)
except:
raise ValueError("Can't convert %s" % s)
if s < one_min:
return "%.2fs" % s
elif s < one_hr:
mins = int(s) / 60
... |
def has_palindrome(i, start, length):
"""Checks if the string representation of i has a palindrome.
i: integer
start: where in the string to start
length: length of the palindrome to check for
"""
s = str(i)[start:start+length]
return s[::-1] == s |
def is_power2(num):
""" Returns true if a number is a power of two """
return num != 0 and ((num & (num - 1)) == 0) |
def check_for_overlap(a, b):
""" Returns true if two sets are not overlaping. Used here to check if two stems share a common residue.
If they do, returns False.
"""
# https://stackoverflow.com/questions/3170055/test-if-lists-share-any-items-in-python
# return True is the is no overlap, else... |
def sort_donors(donor_dict):
"""Sort the list of donors by total amount donated.
Returns a list of only the donors' names.
"""
return sorted(list(donor_dict), key=lambda x: -sum(donor_dict[x])) |
def _get_engine_names(job_name):
"""Return the (engine display name, engine name) for the job."""
if job_name.startswith('afl_'):
return 'AFL', 'afl'
if job_name.startswith('libfuzzer_'):
return 'libFuzzer', 'libFuzzer'
return 'Unknown', 'Unknown' |
def readable_time(time_difference):
"""Convert a float measuring time difference in seconds into a tuple of (hours, minutes, seconds)"""
hours = time_difference // 3600
minutes = (time_difference // 60) % 60
seconds = time_difference % 60
return hours, minutes, seconds |
def insert_at(list_a: list, position: int, item):
"""Problem 21: Insert element at a given position into a list.
Parameters
----------
list_a : list
The input list
position : int
The position where the inserted element should be
item
The element to insert to the list
... |
def mk_var_expr(name):
"""
returns a variable expression of name NAME
where NAME is a string
"""
return {"type" : "var" ,
"name" : (name, 0)} |
def get_time_segments(sensor, segments):
"""
Function to extract the start timestamps and end timestamps sorted from early to late from a feature segment
:param sensor: sensor dimension of segment (int)
:param segments: feature segments to extract the timestamps for
:returns: starts and ends in sort... |
def strip_extension(name: str) -> str:
"""
Remove a single extension from a file name, if present.
"""
last_dot = name.rfind(".")
if last_dot > -1:
return name[:last_dot]
else:
return name |
def _send_not_success_response(status_code):
""" Function to be called when the response is not 200 """
return {
"status": status_code,
"data": None
} |
def get_ax_lim(ax_min, ax_max, base=10):
"""
Get axis limit
Parameters
----------
ax_min : float
ax_max : float
base : int, default = 10
Returns
-------
ax_min : float
ax_max : float
"""
from math import ceil, floor
ax_min = floor(ax_min * base) / base
ax_m... |
def total():
"""Returns the total number of grains on the chessboard."""
return 2**64 - 1 |
def get_video_id_by_number(number, results):
"""Get video id by its number from the list of search results generated by search_by_keyword
function call.
Videos are numbered from 1 to maxResults (optional search parameter,
set by default to 5, see https://developers.google.com/youtube/v3/docs/search/list)
as in res... |
def weighted_gap_penalty(col, seq_weights):
""" Calculate the simple gap penalty multiplier for the column. If the
sequences are weighted, the gaps, when penalized, are weighted
accordingly. """
# if the weights do not match, use equal weight
if len(seq_weights) != len(col):
seq_weights =... |
def match_candidates_by_order(images_ref, images_cand, max_neighbors):
"""Find candidate matching pairs by sequence order."""
if max_neighbors <= 0:
return set()
n = (max_neighbors + 1) // 2
pairs = set()
for i, image_ref in enumerate(images_ref):
a = max(0, i - n)
b = min(l... |
def is_valid_boolean(val):
""" Checks if given value is boolean """
values = [True, False]
return val in values |
def g_diode(f, f_diode, alpha):
"""Theoretical model for the low-pass filtering by the PSD.
See ref. 2, Eq. (11).
"""
return alpha ** 2 + (1 - alpha ** 2) / (1 + (f / f_diode) ** 2) |
def _plus(arg1, arg2):
"""int plus"""
return str(int(arg1) + int(arg2)) |
def contains(text, pattern):
"""Return a boolean indicating whether pattern occurs in text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# kind of self explanatory
if pattern in text:
retu... |
def make_window(n, k = 1000, l = 100):
"""bin n numbers into windows,
k points per window with l overlap
"""
op = [[i-l, i+k+l] for i in range(0, n, k)]
op[0][0] = 0
op[-1][1] = n
if (len(op) > 1 and op[-1][1]-op[-1][0] < k/2 + l):
op.pop()
op[-1][1] = n
return op |
def normalize_color_tuple(h :int, s:int, x:int) -> tuple:
"""
Normalize an HSV or HSL tuple.
Args:
h: `int` in {0, ..., 360} corresponding to hue.
s: `int` in {0, ..., 100} corresponding to saturation.
x: `int` in {0, ..., 100} corresponding to light or value.
Returns:l
T... |
def name_to_crate_name(name):
"""Converts a build target's name into the name of its associated crate.
Crate names cannot contain certain characters, such as -, which are allowed
in build target names. All illegal characters will be converted to
underscores.
This is a similar conversion as that wh... |
def _get_formatted_size(bytes):
"""
formats the supplied bytes
"""
if bytes < 1000:
return '%i' % bytes + ' B'
elif 1000 <= bytes < 1000000:
return '%.1f' % (bytes / 1000.0) + ' KB'
elif 1000000 <= bytes < 1000000000:
return '%.1f' % (bytes / 1000000.0) + ' MB'
elif 1000000000 <= bytes < 1000... |
def first_down(items):
"""Return True if the first item is down."""
return items[0] == '-' |
def convert_string(string, chars=None):
"""Remove certain characters from a string."""
if chars is None:
chars = [',', '.', '-', '/', ':', ' ']
for ch in chars:
if ch in string:
string = string.replace(ch, ' ')
return string |
def get_bool_param(param):
"""Return bool param value."""
if isinstance(param, bool): return param
return True if param.strip().lower() == 'true' else False |
def searchsorted(arr, x, N=-1):
"""N is length of arr
"""
if N == -1:
N = len(arr)
L = 0
R = N - 1
done = False
eq = False
m = (L + R) // 2
while not done:
xm = arr[m]
if xm < x:
L = m + 1
elif xm > x:
R = m - 1
elif xm... |
def value_to_zero_or_one(s):
"""Convert value to 1 or 0 string."""
if isinstance(s, str):
if s.lower() in ("true", "t", "yes", "y", "1"):
return "1"
if s.lower() in ("false", "f", "no", "n", "0"):
return "0"
if isinstance(s, bool):
if s:
return "1"... |
def _find_and_replace(text, start_string, end_string, replace_fn):
"""Remove everything found between instances of start_string and end_string.
Replace each such instance with replace_fn(removed_text)
e.g. _find_and_replace(u"the [[fat]] cat [[sat]]", u"[[", u"]]", lambda x: x)
= u"the fat cat sat"
Args:... |
def _methodProperties(methodDesc, schema, name):
"""Get properties of a field in a method description.
Args:
methodDesc: object, fragment of deserialized discovery document that
describes the method.
schema: object, mapping of schema names to schema descriptions.
name: string, name of top-level... |
def generate_extension_to_string_mapping(extensions):
"""Returns mapping function from extensions to corresponding strings."""
function = 'const char* ExtensionToString(Extension extension) {\n'
function += ' switch (extension) {\n'
template = ' case Extension::k{extension}:\n' \
' ... |
def helper_capitalize(text):
"""
(string) -> string
proprely capitalize course titles
"""
capitalized = ''
for char in text:
if char.isalpha():
capitalized += char.upper()
else:
capitalized += char
return capitalized |
def get_id(vmfObject, idPropName='id'):
""" Returns the ID of the given VMF object. """
return int(vmfObject[idPropName]) |
def response_creator(text, card):
"""
Builds a response with speech part and Alexa appcard contents
:param text: text to be spoken
:param card: text for the app card
:return: JSON object to be returned
"""
text_item = {"type": "PlainText", "text": text}
card_item = {"type": "Simple", "ti... |
def quality_check(data):
"""
Expects string, returns tuple with valid data
or False when data was invalid
"""
if data != False:
if "RAWMONITOR" in data:
data = data.replace("RAWMONITOR","")
data = data.split("_")
frequency = int(data[0])
temper... |
def get_headers(referer):
"""Returns the headers needed for the transfer request."""
return {
"Content-Type": "application/json; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest",
"Referer": referer
} |
def _format_probability(prob):
"""
Format prediction probability for displaying
INPUT
prob: raw model probability, float
OUTPUT
label : cleaned probability, str
"""
return f'{round(100 * prob, 2)}%' |
def get_dhm(timediff):
"""Format time in a human-readable format."""
d = int(timediff / 86400)
timediff %= 86400
h = int(timediff / 3600)
timediff %= 3600
m = int(timediff / 60)
return f"{d}`{h:02}:{m:02}" |
def segmentation_blocks_test_a(band_pass_signal_hr, sb, sh, dim):
"""THIS SECTION REMAINS FOR TESTING PURPOSES
Function used for the segmentation of the signal into smaller parts of audio (blocks). This implementation
has been modified in order to make a simpler version of the original one. After the t... |
def ensure_list(config):
"""
ensure_list
Ensure that config is a list of one-valued dictionaries. This is called
when the order of elements is important when loading the config file. (The
yaml elements MUST have hyphens '-' in front of them).
Returns config if no exception was raised. This... |
def separate_file_from_parents(full_filename):
"""Receives a full filename with parents (separated by dots)
Returns a duple, first element is the filename and second element
is the list of parents that might be empty"""
splitted = full_filename.split('.')
file = splitted.pop()
parents = splitted... |
def to_string(value):
""" Convert a boolean to on/off as a string.
"""
if value:
return "On"
else:
return "Off" |
def nbi_calci(red, nir, swir):
"""
new build-up index
"""
return (swir * red)/nir |
def _method_info_from_argv(argv=None):
"""Command-line -> method call arg processing.
- positional args:
a b -> method('a', 'b')
- intifying args:
a 123 -> method('a', 123)
- json loading args:
a '["pi", 3.14, null]' -> method('a', ['pi', 3.14, None])
- keywo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.