content stringlengths 42 6.51k |
|---|
def removeInvoiceObject(account_data: dict, order_reference: str) -> dict:
"""
example: https://wiki.wayforpay.com/view/852521
param: account_data: dict
merchant_account: str
merchant_password: str
param: order_reference: str
"""
return {
"requ... |
def infer_distribution_parameters(data, distribution, params=None):
"""Convenience method for determining the shape parameters of a given distribution
Args:
data (list-like): The data to build shape parameters from.
distribution (string): Scipy distribution, determines which parameters to build... |
def list_len( data=[]):
""" find the list length """
i = 0
for d in data:
i += 1
return i |
def parse_sync_agent_forwarder_id(json):
"""
Extract the sync agent forwarder id from the get response of LearningLocker.
:param json: JSON statement from the get response.
:type json: dict(str, list(dict(str, str))
:return: The statement forwarder id from the sync agent.
:rtype: str
"""
... |
def attributes_to_str (attributes, name):
"""
helper function for dot format
turns dictionary into a=b, c=d...
"""
# remove ugly __main__. qualifier
name = name.replace("__main__.", "")
# if a label is specified, that overrides the node name
if "label" not in attributes:
attrib... |
def generate_bands(low, high, increment):
"""Returns a list of bands within low-high based on the increment.
If low is not at an even increment (e.g., 1378), the first band is between
low and the next even increment, e.g., [1378, 1500].
If low is 0, it will be used as is. Otherwise, 1 will be added to... |
def clean_sequence(sequence: str) -> str:
"""
Replace all multiple whitespaces, tabs, linebreaks etc. with single whitespaces.
:param sequence: string
:return: cleaned string
"""
return " ".join(sequence.strip().split()) |
def eval_poly(vec, poly):
"""
Evaluates value of a polynomial at a given point
:param vec: The given point :float
:param poly: The polynomial :ndarray[3,]
:return: value of polynomial at given point :float
"""
return vec ** 2 * poly[0] + vec * poly[1] + poly[2] |
def player_1_win_check (original_state,end_of_round_check,score,player_symbol):
"""
This function is used to iterate through each index of the list and check whether the player has entered an 'X' or 'O' in the following combination of indexes:
[0,1,2] OR [3,4,5] OR [6,7,8] OR [0,3,6] OR [... |
def extract_prime_power(a, p):
"""
Return s, t such that a = p**s * t, t % p = 0
"""
s = 0
if p > 2:
while a and a % p == 0:
s += 1
a //= p
elif p == 2:
while a and a & 1 == 0:
s += 1
a >>= 1
else:
raise ValueError("Nu... |
def stats( ls ) :
"""
Calculate the mean and variance in a list.
Returns mean, variance
"""
if len(ls) <= 0 :
return [0.0, 0.0]
from math import sqrt
avg = 1.0 * sum(ls) / len(ls)
if len(ls) == 1 :
return [avg, 0.0]
s = sqrt(1.0*sum( [ (x - avg)**2 for x in ls... |
def calculatePointsWon(difficulty_level, word):
"""
Returns the difficulty_level multiplied by the length of the word.
Returns an integer.
"""
return difficulty_level * len(word) |
def sizeCheck(testInput, minSize = None, maxSize = None):
"""
Helper method for enforceInt, enforceFloat, enforceStringFormat
Args:
testInput: input to test for size
minSize: minimum size for testInput
maxSize: maximum size for testInput
Returns:
Error message if invalid... |
def string2dict(s):
"""
turn a string like "a=2,b=3.5" into a dict
"""
# strval = re.compile(r"^\w+$")
d = {}
for stmt in s.split(","):
if stmt:
(key,valstr) = stmt.split("=")
try:
val = eval(valstr)
d[key] = val
except ... |
def unescape_double_quote(content: str) -> str:
"""
Replace escaped double quote in content by removing the backslash.
>>> unescape_double_quote(r'UTF\"-8')
'UTF"-8'
>>> unescape_double_quote(r'UTF"-8')
'UTF"-8'
"""
return content.replace(r"\"", '"') |
def cat2axis(cat):
"""
Axis is the dimension to sum (the pythonic way). Cat is the dimension that
remains at the end (the Keops way).
:param cat: 0 or 1
:return: axis: 1 or 0
"""
if cat in [0, 1]:
return (cat + 1) % 2
else:
raise ValueError("Category should be Vi or Vj.") |
def _escape_cmd_arg(arg):
"""quote/escape and argument for a command line call so that it can
be safely used even if it has special charaters"""
arg = str(arg)
if ' ' in arg or '"' in arg:
return '"' + arg.replace('"', '""') + '"'
return arg |
def get_tag_span(tag):
"""Returns the start and end character offsets of a given tag as a 2-tuple
(start, end)."""
return (tag['start'], tag['end']) |
def clean(s: str):
"""Removes unnecessary characters from a given string.
Arguments:
s {str} -- String that should be cleaned
Returns:
s {str} -- Cleaned string
"""
s = s.replace('\n', '')
return s |
def get_text_hv(angle):
"""Returns (ha, va) text horizontal and vertical alignment for line label.
This makes the line label text inside its area, assuming areas closed CW.
Args:
angle (float): line normal vector in degrees, between 180 and -180
"""
horiz, vert = ('', '')
if abs(angle)... |
def get_long_season_name(short_name):
"""Convert short season name of format 1718 to long name like 2017-18."""
return "20" + short_name[:2] + "-" + short_name[2:] |
def format_ordinal(n):
"""
Format an ordinal, like 1st, 2nd, 3rd...
Not tested with large numbers of negative numbers!
"""
if 10 <= n % 100 < 20:
return str(n) + 'th'
else:
return str(n) + {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, "th") |
def validate(input_value, lower_bound, upper_bound, l_inclusive = True, u_inclusive = True, convert_to_integer = False):
"""Check if value is within allowable range.
:param input_value: Input value to validate
:type input_value: String
:param lower_bound: Lowest acceptable value.
:type lower_bo... |
def transpose_list(input):
"""
INPUT:
- ``input`` -- a list of lists, each list of the same
length
OUTPUT:
- ``output`` -- a list of lists such that output[i][j]
= input[j][i]
EXAMPLES::
sage: from sage.schemes.hyperelliptic_curves.monsky_washnitzer import transpose_li... |
def add_colors_to_graph(struct, colors):
"""
Change the colors in the structure graph. Colors should be a dictionary-fied
json object containing the following entries:
[{'name': '1Y26_X', 'nucleotide':15, 'color':'black'}]
@param struct: The structure returned by fasta_to_json
@param color... |
def rank_naive(s, a, i):
"""
rank_a(S, i) returns the number of occurrences of symbol a in S[1, i].
"""
return s[:i].count(a) |
def get_top_n_recommendations(predictions, n=10):
"""
Return the top N recommendations (book ids) from a list of predictions
made for the user.
Parameters:
predictions : list of Prediction objects
Predictions, as returned by the test method of an algorithm.
n : int, default 10
... |
def drop_table_clause(table_name):
""" Create a drop table if exists clause string for SQL.
Args:
table_name: The table to be dropped.
Returns:
A string with the crafted clause.
"""
return 'DROP TABLE IF EXISTS {}'.format(table_name) |
def get_average_scores(directors):
"""Iterate through the directors dict (returned by get_movies_by_director),
return a list of tuples (director, average_score) ordered by highest
score in descending order. Only take directors into account
with >= MIN_MOVIES"""
director_del = []
for di... |
def format_filename(prefix, suffix, uncased=False):
"""docs."""
if not uncased:
case_str = ""
else:
case_str = "uncased."
file_name = "{}.{}{}".format(
prefix, case_str, suffix)
return file_name |
def indexOf(a, b):
"""Return the first index of b in a."""
for i, j in enumerate(a):
if j == b:
return i
else:
raise ValueError('sequence.index(x): x not in sequence') |
def pad_sents(sents, pad_token):
""" Pad list of sentences according to the longest sentence in the batch.
@param sents (list[list[int]]): list of sentences, where each sentence
is represented as a list of words
@param pad_token (int): padding token
@returns sents_pad... |
def buy_size_switch(value):
"""enable/disable buy size amount"""
if "buysize" in value:
return False, False
return True, True |
def get_x_and_y_coords_for_a_square(square_array):
"""
For a given array, return x and y coordinates
:param square_array: array with coordinates of one square (from find_squares)
:return: x1,y1,x2,y2,x3,y3,x4,y4
"""
x1 = square_array[0][0]
y1 = square_array[0][1]
x2 = square_array[1][0]
... |
def add_api_config_to_queries(generated_query_strings, search_engines):
"""
Merges the two parameters and returns a list of dicts that include the
api config.
If only 1 API key is provided, it is assumed this is valid for many searches and is used for all queries
If more than 1 is p... |
def insertion_sort(input_list):
"""Insertion sort."""
if not isinstance(input_list, (list, tuple)):
raise ValueError('input takes list/tuple only')
if isinstance(input_list, (tuple)):
input_list = list(input_list)
if not all(isinstance(val, (int, float)) for val in input_list):
... |
def sol(s):
"""
Update rules as per the statement
"""
ba = 1
n = len(s)
i = 0
t = 4
while i < n:
if t < ba:
return -1
if s[i] == "W":
t = t + ba
ba = 1
else:
t = t - ba
ba = 2*ba
i+=1
return t |
def get_transfer_volume(source_conc, target_conc, target_vol, dil_factor=None):
"""
Helper function determine the transfer volume (uncorrected) for a set of
values.
"""
if dil_factor is None:
dil_factor = source_conc / float(target_conc)
if dil_factor < 1:
msg = 'A dilution facto... |
def mapQids(qids):
"""Maps qids to running numbering starting from zero, and partitions
the training data indices so that each partition corresponds to one
query"""
qid_dict = {}
folds = {}
counter = 0
for index, qid in enumerate(qids):
if not qid in qid_dict:
qid_dict[qi... |
def remove_surrogates(s, errors='replace'):
"""Replace surrogates generated by fsdecode with '?'"""
return s.encode('utf-8', errors).decode('utf-8') |
def netdna_cdn( path ):
"""
Returns a link to the named NetDNA-hosted CSS resource.
"""
return '<link href="//netdna.bootstrapcdn.com/%s" rel="stylesheet">' % path |
def parse_length(text):
""" Parses a file length
>>> parse_length(None)
-1
>>> parse_length('0')
-1
>>> parse_length('unknown')
-1
>>> parse_length('100')
100
"""
if text is None:
return -1
try:
return int(text.strip()) or -1
except ValueError:
... |
def _replace_param_type(param):
"""Replace param to a new param type
:param param: parameter value
:return: tuple with replaced value and boolean to know if replacement has been done
"""
param_types = {
'[MISSING_PARAM]': None,
'[TRUE]': True,
'[FALSE]': False,
'[NUL... |
def fill_matrix_holes(mat):
"""matrix may have blanks. Sometimes the tail end of some rows will not have elements.
Make sure all rows have the same length as the first row.
Also remove cells if the row is longer than the first row"""
numcols = len(mat[0])
for i, row in enumerate(mat[1:]):
mo... |
def predict_classification(tree, labels, test):
"""Predict the classification for a test."""
if isinstance(tree, dict):
node, node_choices = tree.popitem()
feature = node_choices[test[labels.index(node)]]
result = predict_classification(feature, labels, test)
else:
result = t... |
def rotate_vec(input_vec, n):
"""
rotate an input vec by n places, wrapping around.
"""
output_vec = []
for i in range(len(input_vec)):
output_vec.append(input_vec[(i-n)%len(input_vec)])
return output_vec |
def add_suffix(txt, suffix):
"""add the given to every element in given comma separated list.
adds suffix before -.
Example:
add_suffix("hello,john", "ga:") -> "ga:hello,ga:john"
"""
if txt is None:
return None
elements = txt.split(",")
elements = ["-" + suffix + e[1:] if ... |
def format_weather_data(data_str):
""" Take weather data in weewx format and transform to param/value dict"""
## Data sample direct from weewx (shortened)
# "altimeter: 72.317316, ... maxSolarRad: None, ... windGustDir: 359.99994, windSpeed: 5.1645e-09"
# Replace "None" values with 0's
data_str =... |
def _input_V_calcs(input_V, A2, rho_amp):
"""Get the effective preamp input noise current (ENI) and the output
noise voltage from the noise voltage at the preamp input.
:return: output voltage, effective input current (ENI)
"""
output_V = A2 * input_V
eni = input_V / rho_amp
return output_... |
def gen_label(x):
"""[summary]
Args:
x ([type]): [description]
Returns:
[type]: [description]
"""
if 1 <= x <= 10:
return 2
if 11 <= x <= 100:
return 1
return 0 |
def _normalize_states(states):
"""Normalize states by inheriting parameters explicitly.
The TMHMM file format allows parameters to be tied to the parameters of
some other state. This basically means that a state inherits the parameters
from another state.
The normalization performed by this functi... |
def computeLPSArray(pattern):
"""
Utility function to calculate the LPS (Longest Proper Prefix that is also a Suffix) array.
Args:
pattern (str): pattern
Raises:
Exception: pattern not of type string
Returns:
array: the LPS array
"""
if isinstance(pattern, str) == ... |
def jaccard_distance(label1, label2):
"""Distance metric comparing set-similarity.
"""
return (len(label1.union(label2)) - len(label1.intersection(label2)))/len(label1.union(label2)) |
def ror(x, n, p=1):
"""Bitwise rotation right"""
return (x >> p) + ((x & ((1 << p) - 1)) << (n - p)) |
def _noise_dict_update(noise_dict):
"""
Update the noise dictionary parameters with default values, in case any
were missing
Parameters
----------
noise_dict : dict
A dictionary specifying the types of noise in this experiment. The
noise types interact in important ways. First,... |
def find_root(func, low_val, high_val):
"""Bisection algorithm for finding the root of an equation.
low_val is the left bracket, func(low_val) < 0
high_val is the right bracket, func(high_val) > 0
func is a function that takes a single argument and returns a
single floating point val... |
def daysInMonth(month: int, year: int) -> int:
"""
return number of days in the month
"""
def leapYear(year) -> bool:
"""
returns True if leap year
"""
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 40... |
def update_tok_lists(all_tokens, list_to_check):
"""
Function to separate a list into two lists: one containing all the
words in another input list, and another to contain all the remaining
words.
input:
all_tokens (list): list of all tokens to update
list_to... |
def _is_notify_empty(notify_db):
"""
notify_db is considered to be empty if notify_db is None and neither
of on_complete, on_success and on_failure have values.
"""
if not notify_db:
return True
return not (notify_db.on_complete or notify_db.on_success or notify_db.on_failure) |
def add_leading_padding(s, c=' ', target_length=-1):
"""
>>> add_leading_padding(s='hi')
'hi'
>>> add_leading_padding(s='hi', target_length=10)
' hi'
>>> add_leading_padding(s='hi', c='-', target_length=3)
'-hi'
>>> add_leading_padding(s=900)
'900'
>>> ... |
def unlist(list_in):
"""
transform possible chain list into one-dim list
:param list_in:
:return:
"""
list_out = list()
for ele in list_in:
if type(ele) is list:
list_out.extend(ele)
else:
if ele != '':
list_out.append(ele)
... |
def retrieveSolutionByIDs(solved_model, var_ids):
"""
Retreive MILP solution by variable ids
solver_model: gurobi solved model
ids: aray of variable ids
"""
x = []
for var_id in var_ids:
x.append(solved_model.getVarByName(var_id).x)
return x |
def monomial_max(*monoms):
"""
Returns maximal degree for each variable in a set of monomials.
Examples
========
Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`.
We wish to find out what is the maximal degree for each of `x`, `y`
and `z` variables::
>>> from sym... |
def _safe_format(s, **keys):
"""Like str.format, but doesn't mind missing arguments.
This function is used to replace strings like '{SomeKey}' in
the template with the arguments given as keys. For example,
_safe_format('{SomeKey} {SomeOtherKey}', SomeKey='Hello', SomeMissingKey='Bla')
returns ... |
def map_value(value, in_start, in_stop, out_start, out_stop):
"""
Map a value from an input range to an output range
:param value:
:param in_start:
:param in_stop:
:param out_start:
:param out_stop:
:return:
"""
return out_start + (out_stop - out_start) * ((value - in_start) / (i... |
def get_n_first_elements(py_list, n_elements):
"""Get the first `n` elements of a list.
Args:
py_list (list): A list of elements.
n_elements (int): The number of elements.
Returns:
sub_list (list): A list with the first `n` elements of `py_list`.
Examples:
>>> py_list = [... |
def int_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval .
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
An int that resu... |
def is_verb(string):
"""
Check if a predstring is for a verb or a noun
"""
return string.split('_')[-2] == 'v' |
def is_empty(any_structure):
"""
Check if any container is empty.
Parameters
----------
any_structure : TYPE Any data container.
DESCRIPTION.
Returns
-------
bool
DESCRIPTION. True if container is empty. False if contains any data.
"""
if any_structure:
... |
def parse_content_range(content_range):
"""Extract units, start, stop, and length from a content range header like "bytes 0-846981/846982".
Assumes a properly formatted content-range header from S3.
See werkzeug.http.parse_content_range_header for a more robust version.
Parameters
----------
c... |
def combine_moby(list_ipa):
"""Turns an IPA list into an IPA string."""
return "".join(list_ipa) |
def create_message_context_properties(message_type, message_id, source, identifier, is_cloud_event_format) -> dict:
"""Create message context properties dict from input param values."""
return {
'type': message_type,
'message_id': message_id,
'source': source,
'identifier': ident... |
def get_intersection_area(box1, box2):
"""
compute intersection area of box1 and box2 (both are 4 dim box coordinates in [x1, y1, x2, y2] format)
"""
xmin1, ymin1, xmax1, ymax1 = box1
xmin2, ymin2, xmax2, ymax2 = box2
x_overlap = max(0, min(xmax1, xmax2) - max(xmin1, xmin2))
y_overlap =... |
def get_occurrences(track):
"""
Get indices of occurrences of each unique element in two-level nested list (track)
Returns 0 if it only occurs once, returns the distance between the last two occurrences if element occurs more
than twice 0 if only occurs once
:param track: two-level nested list (as... |
def get_thread_id_from_suggestion_id(suggestion_id):
"""Gets the thread_id from the suggestion_id.
Args:
suggestion_id: str. The ID of the suggestion.
Returns:
str. The thread ID linked to the suggestion.
"""
return suggestion_id[suggestion_id.find('.') + 1:] |
def _merge_multi_value(raw_list):
"""
If there are values with the same key value, they are merged into a List.
"""
d = {}
for k, v in raw_list:
if k not in d:
d[k] = v
continue
if isinstance(d[k], list):
d[k].append(v)
else:
d[... |
def isblank(string):
"""Is this whitespace or an empty string?"""
if string == '':
return True
return string.isspace() |
def mapped_ipv6_to_ipv4(hex):
"""
For converting ipv4 addresses mapped to ipv6 back to ipv4
:param hex: ipv6 address without the '00000000:00000000:0000FFFF:' prefix
:return: String containing the ipv4 address
"""
grouped = [hex[i:i + 2] for i in range(0, len(hex), 2)]
return '.'.join(list(m... |
def is_csar(file):
"""Check if file is a CSAR multi-file ADT"""
return file.casefold().endswith("csar".casefold()) |
def integral_insert_realignment(insert_alignment, insert_length):
"""
Check whether insert realigned without gaps to the reference.
Inserts are only considered as ITDs if they realign to the reference
in one piece (to their respective second tandem).
Args:
insert_alignment (str): Alignment... |
def AST(string):
"""Returns an abstract syntax tree for a Lisp expression.
Expects first and last characters of `string` to be parens.
Valid atoms/values are symbols without spaces or non-negative integers.
"""
assert(len(string) > 0)
assert(string[0] == '(' and string[-1] == ')')
# tokeni... |
def form_a_day(day):
"""
Makes a one-digit number into a one-digit number
with a '0' in front
@type day: string
@param day: some number to be converted
@rtype: string
@return: returns the converted number in str type
"""
day = int(day)
if day in range(1, 10):
d... |
def chord( x, y0, y1):
"""
; ---------------------------------------------------------------------------
; Function Chord( x, y0, y1 )
;
; Compute the area of a triangle defined by the origin and two points,
; (x,y0) and (x,y1). This is a signed area. If y1 > y0 then the area
; will be pos... |
def _get_attribute_properties(attribute_string):
"""
Returns the properties of the attribute from a dumped sting
:param str attribute_string: the string from a class dump containing an
attribute
:return: a string containing the parsed properties of an attribute
"""
known_attributes = {
... |
def configure_csv_output(new_d,output_csv):
"""
"""
idx = [i for i,d in enumerate(new_d['batch']['batchstep']) if 'CSVExportModule' in d['@method']][0]
idx2 = [i for i,d in enumerate(new_d['batch']['batchstep'][idx]['parameter']) if 'Filename' in d['@name']][0]
new_d['batch']['batchstep'][idx]['par... |
def build_file_to_experiment_data_mapping(experiment_data_dict):
"""Build a file-to-experiment lookup mapping.
Args:
experiment_data_dict: dict that contains experiment metadata.
Returns:
Lookup mapping with keys of format '/files/<file_accession>',
and a dict
{
'ex... |
def cat_charsets(cs):
"""Combine a set into an alphabetically sorted list in written English,
using commas and 'and'. """
d = sorted(cs)
if len(d) > 2:
d[-1] = "and " + d[-1]
d = ", ".join(d)
else:
d = " and ".join(d)
return d |
def expandPower( expression ):
"""Expands out variables which are multiplied by an integer value
For example x^2 = (x*x) and x^4 = (x*x*x*x)
"""
start = 0
while start < len(expression):
l = expression[start:].find('*')
if l == -1: l = expression[start:].find('/')
if l == -1: l = len(expression)
... |
def __get_length_str(secs):
"""Convert seconds to human readable string"""
lengthstr = []
hours, minutes, seconds = secs // 3600, secs // 60 % 60, secs % 60
if hours > 0:
lengthstr.append("%dh" % hours)
if minutes > 0:
lengthstr.append("%dm" % minutes)
if seconds > 0:
le... |
def match_title(event_title):
"""
Match bill title against the following possible titles
"""
bill_titles = [
"bill amended and passed by ncop",
"bill passed and amended by ncop",
"bill passed and amended by the ncop",
"bill passed and referred to the ncop",
"bill ... |
def convert_to_string(input_value):
"""
:param input_value:
:return:
"""
return input_value.__str__() |
def max_or_zero(*args, **kwargs):
"""returns max(*args) or zero if given an empty sequence (in which case max() would throw an error)"""
if not args:
return 0
if not args[0]:
return 0
else:
return max(*args, **kwargs) |
def get_locations(annotation, frame='key'):
"""
This method returns location of specified frame
"""
assert frame in ['key', 'start', 'end']
key = {
'key': 'pnr_frame_sec',
'start': 'parent_start_sec',
'end': 'parent_end_sec'
}
locations = list()
for ann in annotat... |
def invert_dictionary(dictionary):
"""Invert a dictionary
.. note::
If the dictionary has unique keys and unique values, the inversion would be perfect. However, if there are
repeated values, the inversion can take different keys
Args:
dictionary (dict): A dictionary
Returns:... |
def count_violations_lead_like(molecular_weight, slogp, num_rotatable_bonds):
"""http://zinc.docking.org/browse/subsets/
Teague, Davis, Leeson, Oprea, Angew Chem Int Ed Engl. 1999 Dec 16;38(24):3743-3748.
"""
n = 0
if molecular_weight < 250 or molecular_weight > 350:
n += 1
if slogp > 3... |
def IOU(box1, box2):
"""
Params
box1 - [x1,y1,x2,y2] which are the coordinates of the top left and bottom right corners of a box
box2 - [x1,y1,x2,y2] which are the coordinates of the top left and bottom right corners of a box
Returns - Intersection over union of the two bounding boxes... |
def dms2dec (dms, delimiter=":") :
""" Transform deg:min:sec format angle to decimal format
args:
dms: sexagesimal angle string, format +/-dd:mm:ss.xxx
delimiter: char seperate deg, min and sec, default is ":"
returns:
decimal angle in degree
"""
pp = dms.split(delimiter)
... |
def victoire_colonne(plateau, joueur):
"""
Teste si le plateau admet une victoire en colonne pour le joueur.
"""
for j in range(3):
if all(plateau[i][j] == joueur for i in range(3)):
return True
return False |
def create_tuple(n):
"""
>>> create_tuple(10)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
"""
return tuple(range(n)) |
def get_position_from_periods(iteration, cumulative_periods):
"""Get the position from a period list.
It will return the index of the right-closest number in the period list.
For example, the cumulative_periods = [100, 200, 300, 400],
if iteration == 50, return 0;
if iteration == 210, return 2;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.