content stringlengths 42 6.51k |
|---|
def deriv_sigmoid(s):
"""Derivative of the sigmoid given the output s of the sigmoid"""
return s * (1 - s) |
def escape_schema_name(name):
""" Escape system names for PostgreSQL. Should do the trick. """
return name.replace('"', '""') |
def create_ngram_set(input_list, ngram_value=2):
"""
Extract a set of n-grams from a list of integers.
>>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2)
{(4, 9), (4, 1), (1, 4), (9, 4)}
>>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3)
[(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)]
... |
def potencia(c):
"""Calcula y devuelve el conjunto potencia del
conjunto c.
Devuelve todas las combinaciones en una lista
"""
if len(c) == 0:
return [[]]
r = potencia(c[:-1])
return r + [s + [c[-1]] for s in r] |
def is_unique_with_set(s: str):
"""
Time: O(n), Space: O(n)
"""
char_set = set()
for char in s:
if char in char_set:
return False
char_set.add(char)
return True |
def decode_string(value):
"""
Decode special character, \t \n
"""
value = str.replace(value, '\\t', '\t')
value = str.replace(value, '\\n', '\n')
return value |
def k_previous_obs(observations_dict, cur_age, k):
"""
@param observations_dict:
@param cur_age:
@param k:
"""
if len(observations_dict) == 0:
return [-1, -1, -1, -1, -1]
## ----- if found observation from k previous time steps
for i in range(k):
dt = k - i # 3, 2, 1
... |
def reformat(val):
"""
Pick string and give it format
:param val: string value
:return: int, float or string
"""
try:
x = int(val)
except:
try:
x = float(val)
except:
x = val
return x |
def sortedSquaredArray(array):
"""
### Description
sortedSquaredArray takes an array and squares every number in and returns a
new list sorted in ascending order.
### Parameters
- array: The collection of numbers.
### Returns
A new sorted list in an ascendi... |
def torch_dot_eye_gen_explicit_map(_, args_pt):
"""
Generate explicit_map for torch.eye.
Args:
args_pt (dict): Args for APIPt.
Returns:
dict, map between frames.
"""
explicit_map = {'t': 'mindspore.int32'}
if args_pt.get('m'):
explicit_map.update({'m': args_pt.get('... |
def idx2coords(i, shape):
""" i --> (x,y) such that coords2idx((x,y), shape) == i """
assert type(i) == int
cols = shape[1]
return (i // cols, i % cols) |
def distance(rgb1, rgb2):
"""Return quasi-distance in 3D space of RGB colors."""
return (rgb1[0]-rgb2[0])**2 + (rgb1[1]-rgb2[1])**2 + (rgb1[2]-rgb2[2])**2 |
def remove(s1,s2):
"""
Returns a copy of s, with all characters in s2 removed.
Examples:
remove('abc','ab') returns 'c'
remove('abc','xy') returns 'abc'
remove('hello world','ol') returns 'he wrd'
Parameter s1: the string to copy
Precondition: s1 is a string
... |
def split_full_name(string: str) -> list:
"""Takes a full name and splits it into first and last.
Parameters
----------
string : str
The full name to be parsed.
Returns
-------
list
The first and the last name.
"""
return string.split(" ") |
def somme_digit_puissance_2(N):
"""
This function returns the sum of digit inside the number 2**N
"""
str_nb = str(2**N)
somme = 0
for elt in str_nb:
somme += int(elt)
return somme |
def fact(n):
"""Returns factorial of the n using recursion."""
if n == 0 or n == 1:
return 1
else: return n*fact(n-1) |
def inc_pointer(array: list, current_ptr: int) -> int:
"""Increment the pointer"""
while len(array) <= current_ptr + 1:
array.append(0)
return current_ptr + 1 |
def arrays_avg(values_array, weights_array=None):
"""
Computes the mean of the elements of the array.
Parameters
----------
values_array : array like of numerical values.
Represents the set of values to compute the operation.
weights_array : array, optional, default None.
Used t... |
def nint(v):
"""Nullable int"""
return int(v) if v is not None else None |
def translate_marker_and_linestyle_to_Plotly_mode(marker, linestyle):
"""<marker> and <linestyle> are each one and only one of the valid
options for each object."""
if marker is None and linestyle != 'none':
mode = 'lines'
elif marker is not None and linestyle != 'none':
mode = 'lines+markers'
elif marker is n... |
def get_p2p_scatter_over_mad(model):
"""Get ratio of variability of folded and unfolded models."""
return model['scatter_over_mad'] |
def r_rotate(lst, i):
""" RIGHTROTATE """
return lst[-i:] + lst[:-i] |
def clean_latex(ltx):
"""
Clean a latex string to facilitate
the creation of a unicode string
"""
latex_to_replace = [
("$", ""),
(r"\left", ""),
(r"\right", ""),
(r"\log", "log"),
(r"\sin", "sin"),
(r"\cos", "cos"),
(r"\tan", "tan"),
... |
def _clean_info(obj):
""" stringtify and replace space"""
return str(obj).strip().replace(" ", "_") |
def is_number(s):
"""
Check if str can be can be made into float/int
"""
try:
float(s) # for int, long and float
return True
except ValueError:
try:
complex(s) # for complex
return True
except ValueError:
return False
except Typ... |
def pick_wm_class_0(tissue_class_files):
"""Returns the csf tissue class file from the list of segmented tissue class files
Parameters
----------
tissue_class_files : list (string)
List of tissue class files
Returns
-------
file : string
Path to segment_seg_0.nii.gz is re... |
def verify_string_combos(word, string):
"""
Finds all possible indices of a word in a given string
"""
if type(word) is not str or type(string) is not str:
return None
if len(word) > len(string):
return []
indices = []
def isWordPresent(stringSlice):
tracker = word[... |
def version_1_43_5(model_dict):
"""Implement changes in a Model dict to make it compatible with version 1.43.5."""
if 'radiance' in model_dict['properties']:
if 'modifiers' in model_dict['properties']['radiance']:
for mod in model_dict['properties']['radiance']['modifiers']:
... |
def __check_if_alive(processes):
"""
Quickly check if at least one of the list of processes is alive.
Returns True if at least one process is still running.
"""
c = set([x.exitcode for x in processes])
return None in c |
def get_unique_tasks(*task_groups):
"""
Compare input JSON objects containing tasks and return a unique set
:param json_objects: lists of task objects
:type json_objects: list
:rtype: list
"""
# Combine all sub-json objects into a single group
unique_tasks = []
# Get a list of ta... |
def lerp(val, low, high):
"""Linear interpolation"""
return low + (high - low) * val |
def hschain_q(sql):
"""append prefix that signals hschain query to driver"""
return "PRAGMA HSCHAIN QUERY;"+sql |
def count(value, sub, start=None, end=None):
"""
Return the number of non-overlapping occurrences of substring sub in the range [start, end].
Optional arguments start and end are interpreted as in slice notation.
"""
return value.count(sub, start, end) |
def byte_size(num, suffix='B'):
"""
Return a formatted string indicating the size in bytes, with the proper
unit, e.g. KB, MB, GB, TB, etc.
:arg num: The number of byte
:arg suffix: An arbitrary suffix, like `Bytes`
:rtype: float
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
... |
def _isa_helper_get_field(fields, key):
"""Helper for easily obtaining value from an ISA-tab field."""
return ";".join(fields.get(key, ())) |
def sub_max(arr,k):
"""[returns the max subarray sum of size k]
Args:
arr ([arr]): [list to operate on]
k ([int]): [subarray size]
Returns:
[int]: [max subarray sum]
"""
if not arr:
return 0
max_sum, window_sum = 0, 0
window_start = 0
for window_end in ... |
def is_boundary(horizon, x):
"""
Function which marks displacement boundary constrained particles
2 is no boundary condition (the number here is an arbitrary choice)
-1 is displacement loaded IN -ve direction
1 is displacement loaded IN +ve direction
0 is clamped boundary
"""
# Does not ... |
def interrupted_bubble_sort(items, interruptor):
"""Accept a list of positive ints, return a partially sorted list.
Using the bubble sort algorithm, this function will iterate over
the list as many times as indicated by the interruptor var. It will
return the state of the list at the point of the inter... |
def get_label_index(labels):
"""
Labeling family name with an index.
:param labels: list of strings
:return: dict with key is the label and value is the index.
"""
fam_index_dict = dict()
for i in range(len(labels)):
fam_index_dict[labels[i]] = i
return fam_index_dict |
def _big_integer_callback(element, compiler, **kw):
"""Changes INTEGER to integer."""
# The keywords include one called type_expression, which is the column
# specification. This should tell us whether the type is a primary key,
# but that's False, even when the type is a primary key. However,
# sql... |
def get_active_agents(statements):
"""
Takes a list of statements and returns a reference users list.
Arguments
---------
nodes: list[statements]
List of statements
Returns
-------
users_list: list[str]
List of users
"""
return {s['actor'] for s in statements} |
def gcd(a, b):
"""
:param a:
:param b:
:return:
"""
# --- version 1 ---
# if a == b:
# return a
# elif a > b:
# return gcd(a - b, b)
# else: # a < b
# return gcd(a, b - a)
# --- version 2 ---
# if b == 0:
# return a
# else: # a < b
... |
def interval_to_milliseconds(interval):
"""Convert a Binance interval string to milliseconds
:param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
None if unit not one of m, h, d or w
None if string not in correc... |
def is_api_disabled(config, api_name):
"""Check if api_name is disabled in the config.
Args:
config (dict): GCP API client configuration.
api_name (str): The name of the GCP api to check.
Returns:
bool: True if the API is disabled in the configuration, else False.
"""
retur... |
def consecutive(span):
"""
Check if a span of indices is consecutive
:param span: the span of indices
:return: whether the span of indices is consecutive
"""
return [i - span[0] for i in span] == range(span[-1] - span[0] + 1) |
def merge_masked_payload_with_payload(masked_payload, payload, payload_bitmap):
"""
Merges a masked payload with a normal payload using the bitmap that masked the masked payload.
:param payload_bitmap: Bitmap that specifies what (hex) bits need to be used in the new payload. A 0 is a mask.
:param maske... |
def incremental_mean(x, prev_mean, k):
"""Compute a mean incrementally over a dataset of num items
This is useful when we might run out of memory storing all the individual components of the mean
Args:
x (any): The current (k-th) datapoint
prev_mean (any): The previous datapoint. If set to... |
def order_to_degree(order):
"""Compute the degree given the order of a B-spline."""
return int(order) - 1 |
def dumb_unix2dos(in_str):
"""In-efficient but simple unix2dos string conversion
convert '\x0A' --> '\x0D\x0A'
"""
return in_str.replace('\x0A', '\x0D\x0A') |
def translate_sim_name(sim_name):
"""
Translates the simulator name from its abbreviation to the full name.
"""
if sim_name == 'lv':
return 'lotka_volterra'
elif sim_name == 'hh':
return 'hodgkin_huxley'
else:
return sim_name |
def flatten(lst):
"""
this is the fastest implementation
>>> flatten([[1, 2, 3], [2, 4, 6], [4, 6, 8]])
[1, 2, 3, 2, 4, 6, 4, 6, 8]
"""
out = []
for sublist in lst:
out.extend(sublist)
return out |
def PNT2TidalOcto_Pv18(XA,chiA=0,chiB=0,AqmA=0,AqmB=0,beta0PNT=0,beta1PNT=0, \
beta2PNT=0):
""" TaylorT2 2PN Octopolar Tidal Coefficient, v^18 Phasing Term.
XA = mass fraction of object
chiA = aligned spin-orbit component of object
chiB = aligned spin-orbit component of companion object
AqmA = d... |
def _sum(seq):
"""
_sum(seq)
arguments:
seq -- a sequence of numbers (NOT strings) or lists of numbers
if sequence of numbers is provided returns the result of the Python's
built-in sum function. If a sequence of lists of numbers is provided
returns the sum of the resulted zipped list ... |
def get_remote_browsers(settings):
"""Return the defined remote browsers in settings."""
remote_browsers = {}
if 'remote_browsers' in settings:
remote_browsers = settings['remote_browsers']
return remote_browsers |
def _new_object(cls):
"""Helper function for pickle"""
return cls.__new__(cls) |
def return_as_dict(data, description):
"""
:param data: return value of cursor.execute.fetchone (single row only!)
example:
('355e8...0a', datetime.datetime(2020, 10, 24, 22, 54), \
'message', 100, 0, '[]', 0, '[]', 0, '[]', 0, 41825)
:param description: value of cursor.description
... |
def _get_objective_info(num_classes):
"""Provide information on classifier objective.
:param num_classes: integer greater than 1; number of classes
:return: dict with information on objective and evaluation metric for XGBoost
"""
if num_classes == 2:
return {"objective": "binary:logi... |
def calc_pad(pad, in_siz, out_siz, stride, ksize):
"""Calculate padding width.
Args:
pad: padding method, "SAME", "VALID", or manually speicified.
ksize: kernel size [I, J].
Returns:
pad_: Actual padding width.
"""
if pad == 'SAME':
return (out_siz - 1) * stride + ksi... |
def get_text_value(node):
"""
:type node: dict
:rtype: unicode
"""
return node.get('#text') if node else None |
def int_scale(val, val_range, out_range):
"""
Scale val in the range [0, val_range-1] to an integer in the range
[0, out_range-1]. This implementation uses the "round-half-up" rounding
method.
>>> "%x" % int_scale(0x7, 0x10, 0x10000)
'7777'
>>> "%x" % int_scale(0x5f, 0x100, 0x10)
'6'... |
def get_exception_type_string(exception):
"""Returns the full path of the exception."""
exception_type_string = str(type(exception))
# This is expected to look something like
# "<class 'google.auth.exceptions.RefreshError'>"
if exception_type_string.startswith(
"<class '") and exception_type_string.end... |
def _add_commas(s, sep=','):
"""Add commas to output counts.
From: http://code.activestate.com/recipes/498181
"""
if len(s) <= 3:
return s
return _add_commas(s[:-3], sep) + sep + s[-3:] |
def indent_all_lines(text, number_of_spaces=3):
"""Indent all lines in a string by a certain number of spaces"""
return "\n".join(number_of_spaces * " " + line for line in text.split("\n")) |
def three_sum(numbers):
"""
Parameters
----------
numbers : list
A list of integers
Returns
-------
list
containing triplets
"""
list_size = len(numbers)
if list_size < 3:
return []
triplets = set()
# sort list
# for each item to n - 2
... |
def dictrepr(d):
"""
a sort-safe version of pyramid_debugtoolbar.utils.dictrepr`
from pyramid_debugtoolbar.utils import dictrepr
consider migrating to the upstream library when fixed
this will require version pinning.
"""
out = {}
for val in d:
try:
out[val] = re... |
def byteify(input):
""" convert the unicode string in json into string
"""
if isinstance(input, dict):
return {byteify(key): byteify(value)
for key, value in input.items()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(in... |
def inSameSlice(start_idx, end_idx, slice_end_indices):
"""[check if (start_idx, end_indx) is in the same slice provied by slice_end_indices]
Arguments:
start_idx {[type]} -- [state start index]
end_idx {[type]} -- [state end index]
slice_end_indices {[type]} -- [end state tuples]
... |
def number_of_cards(deck):
"""The number of cards in a deck."""
count = 0
for card in deck:
print(repr(card))
card_count = int(card['card_count'])
count += card_count
return count |
def get_avg(tuple_list):
"""
This function will get the average of the tuplelist that is passed in
to it.
"""
the_val = 0
# getting the avg of the tuple by doing a loop
for tup in tuple_list:
the_val += tup[0] # getting the price out of the tuple
ans = the_val/len(tuple_list)
... |
def get_percent(part, total):
"""
Return the percentage that part is of total and multiply by 100
If total is 0, return 0
"""
return (part / total) * 100 if part and total else 0 |
def check_existence_4way(elist, edge):
"""
prevent double check in four-way migration
:param elist: changeedge4
:param edge: edge to be examined
:return:
"""
for x in elist:
if edge == x[1]:
return True
return False |
def setbits(word, bits, value):
"""Map each bit of a value over a list of bit locations in a word"""
# Make sure that value is expressible with bits given
assert 1 << len(bits) > value
for i, bit in enumerate(bits):
if value & 1 << i:
word |= 1 << bit
else:
word &... |
def insert_bigvul_comments(diff: str):
"""Insert comment lines in place of + and - in git diff patch."""
lines = []
for li in diff.splitlines():
if len(li) == 0:
continue
if li[0] == "-":
lines.append("//flaw_line_below:")
li = li[1:]
if li[0] == "... |
def str2pair(x):
"""
Recibe una cadena como '4,5' y retorna una tupla (4, 5)
"""
nums = x.split(',')
return int(nums[0]), float(nums[1]) |
def generateQueriesAsStrings(d, f, m, Dq, Dr):
"""Function that returns all possible queries required for generating recommendations.
The number of combinations returned follows the formula --> 2 x f x d x m.
Args:
d: list of dimension attributes.
f: list of aggregate functions.
m: ... |
def _find_disconnected_subgraphs(inputs, output):
"""
Finds disconnected subgraphs in the given list of inputs. Inputs are
connected if they share summation indices. Note: Disconnected subgraphs
can be contracted independently before forming outer products.
Parameters
----------
inputs : li... |
def response_plain_text(output, endsession):
""" create a simple json plain text response """
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'shouldEndSession': endsession
} |
def earlier_name(name1, name2):
""" (str, str) -> str
Return the name, name1 or name2, that comes first alphabetically.
>>> earlier_name('Jen', 'Paul')
'Jen'
>>> earlier_name('Colin', 'Colin')
'Colin'
"""
if name1 < name2:
return name1
else:
return name2 |
def merge(a, b):
"""
function makes arr of a-size with minimal elems
a, b - arrays
a[i][0] is info, a[i][1] is distance (b the same)
array a may be longer, not the opposite!"""
ai = bi = 0
n, nb = len(a), len(b)
arr = [0] * n
for i in range(n):
if bi == nb:
arr[i]... |
def get_year_str_from_date_str(date_str):
"""
Get the year string from the date string.
Parameters
----------
date_str : str
A string of dates. e.g., '2019-01-01'.
Returns
-------
year_str : str
A string of years. e.g., '2019'.
"""
year_str = date_... |
def snake_to_upper_camel(snake: str) -> str:
"""Convert snake to upper camel, ignoring start/end underscores."""
if not snake:
return snake
snake = snake.lower()
camel = ''
lift = True
for s in snake:
if s == '_':
lift = True
continue
if lift:
... |
def ipath(i: int) -> str:
"""Returns path names '/test 1', '/test 2', ..."""
return f"/test {i}" |
def valid(x, y, n, m):
"""Check if the coordinates are in bounds.
:param x:
:param y:
:param n:
:param m:
:return:
"""
return 0 <= x < n and 0 <= y < m |
def is_palindromic_number(numb: int) -> bool:
"""
Returns whether on not numb
is a palindromic number
https://oeis.org/A002113
"""
return numb == int(str(numb)[::-1]) |
def get_main(heads ):
"""Returns the indices of the tokens of the head of the sentence, or None if the sentence has 0 or several heads
Not in use for now, but could be useful to design tasks"""
r = []
s1 = False
for i,h in enumerate(heads.split(" ")):
l = int(h.strip("&;~"))
if l == ... |
def check_box(iou, difficult, crowd, order, matched_ind, iou_threshold, mpolicy="greedy"):
""" Check box for tp/fp/ignore.
Arguments:
iou (torch.tensor): iou between predicted box and gt boxes.
difficult (torch.tensor): difficult of gt boxes.
order (torch.tensor): sorted order of iou's.
... |
def create_sum_stat(loc: str = '', returncode: int = 0):
"""
Create a summary statistics dictionary, as returned by the
`ExternalModel`.
Can be used to encode the measured summary statistics, or
also create a dummy summary statistic.
Parameters
----------
loc: str, optional (default = ... |
def LogFilters(job_id, task_name=None):
"""Returns filters for log fetcher to use.
Args:
job_id: String id of job.
task_name: String name of task.
Returns:
A list of filters to be passed to the logging API.
"""
filters = [
'(resource.type="ml_job" OR resource.type="cloudml_job")',
'r... |
def modify_range(val):
"""
Modify value from range 0,1 -> -1,1 and preserve ratio
:param val:
:return: value in rage -1,1
"""
return (val * 2) - 1 |
def strip_over_cont(text):
"""
:param text:
:return:
"""
# remove junk headers that concatenate multiple notes
sents = []
skip = False
for line in text.split('\n'):
if line.strip() == '(Over)':
skip = True
elif line.strip() == '(Cont)':
skip = Fal... |
def get_job_name(table_name: str, incremental_load: bool) -> str:
"""Creates the job name for the beam pipeline.
Pipelines with the same name cannot run simultaneously.
Args:
table_name: a dataset.table name like 'base.scan_echo'
incremental_load: boolean. whether the job is incremental.
Returns:
... |
def center_position(low_bound, high_bound, low_limit, high_limit, space):
"""
Center bounds within available space.
:param low_bound: current lower bound
:param high_bound: current upper bound
:param low_limit: minimum allowed bound
:param high_limit: maximum allowed bound
:param space: avai... |
def get_currency_statistic(past_data):
"""Calculate high, low, average, and trend from the past currency data
Currency data is taken from exchangeratesapi.io
Author: KvinTanaka"""
lowest_rates = past_data[0]['rates']
highest_rates = past_data[0]['rates']
average_rates = 0
# Trend ... |
def str_to_bool(str): # lint-amnesty, pylint: disable=redefined-builtin
"""
Converts "true" (case-insensitive) to the boolean True.
Everything else will return False (including None).
An error will be thrown for non-string input (besides None).
"""
return False if str is None else str.lower() ... |
def index_to_factoradic(value, num_elem=None):
""" Convert the int:index to a factoradic representation in a list, indexed 0 to n-1
Args"
value: the integer to convert to mixed radix format
num_elem: Ignored. For API compatability with `factoradic_to_permutation`.
Returns:
"""
remai... |
def on_in(query_name, host_key, schema_key):
"""\
@brief Constructs an on/in snippet (for running named queries)
from a schema name and two keys referencing values stored in
indra.xml.
@param query_name Name of the query.
@param host_key Logical name of destination host. Will be
looked... |
def string_to_mtext(s):
"""Returns string in Autocad multitext format
Replaces newllines `\\\\n` with `\\\\P`, etc.
"""
return s.replace('\\', '\\\\').replace(u'\n', u'\P') |
def b_2_d(x):
"""
Convert byte list to decimal
:param x: byte list
:return: decimal
"""
s = 0
for i in range(0, len(x)):
s += x[i]*2**i
return s |
def validate_dicts(ground_truth: dict, predicted: dict) -> bool:
"""
Validate GT and pred dictionaries by comparing keys
Args:
ground_truth (dict): mapping from (track_id + timestamp) to an element returned from our csv utils
predicted (dict): mapping from (track_id + timestamp) to an eleme... |
def move_path(path, row):
""" Moves to the next path in a tree. """
# Base case: If the row is 0, we can't move that one since its the top.
# Should mean iteration is over.
if row == 0:
return False
elif path[row] == path[row - 1]:
path[row] += 1
# Make sure all sub rows mat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.