content stringlengths 42 6.51k |
|---|
def has_colours(stream):
"""Determine if an output stream supports colours.
Args:
stream: the output stream to check
Returns:
True if more than 2 colours are supported; else False
"""
if hasattr(stream, 'isatty') and stream.isatty():
try:
import curses
... |
def calc_amount_p(fraction_bound, l, kdax):
""" Calculate amount of protein for a given fraction bound and KD"""
return (-(kdax*fraction_bound) - l*fraction_bound + l*fraction_bound*fraction_bound)/(-1 + fraction_bound) |
def lr_gamma(initial_lr=1e-5, last_lr=1e-3, total=50, step=5, mode="log10"):
"""
Compute the gamma of learning rate to be stepped, where gamma can be
larger or equal than 1 or less than 1.
"""
num_step = (total // step) - 1
assert num_step > 0
gamma = (last_lr / initial_lr) ** (1/num_st... |
def maybe_parentheses(obj, operator: str = " ") -> str:
"""
Wrap the string (or object's string representation) in parentheses, but only if required.
:param obj:
The object to (potentially) wrap up in parentheses. If it is not a string, it is converted
to a string first.
:param operator:... |
def get_instances_invited(game, player):
""" Return the instance ids of instances that player has been invited to.
Args:
game: The parent Game database model to query for instances.
player: The email address of the player to look for in instances.
Returns:
An empty list if game is None. Else, return... |
def index_to_coord(index):
"""Returns relative chunk coodinates (x,y,z) given a chunk index.
Args:
index (int): Index of a chunk location.
"""
y = index // 256
z = (index - y * 256) // 16
x = index - y * 256 - z * 16
return x, y, z |
def read_binary_file(filepath):
"""Read the contents of a binary file."""
with open(filepath, 'rb') as file_handle:
data = file_handle.read()
return data |
def undo(rovar):
"""Translates rovarspraket into english"""
for low, upper in zip("bcdfghjklmnpqrstvwxyz", "BCDFGHJKLMNPQRSTVWXYZ"):
rovar = f"{upper}".join(f"{low}".join(rovar.split(f"{low}o{low}")).split(f"{upper}o{low}"))
return rovar |
def isPerfect(x):
"""Returns whether or not the given number x is perfect.
A number is said to be perfect if it is equal to the sum of all its
factors (for obvious reasons the list of factors being considered does
not include the number itself).
Example: 6 = 3 + 2 + 1, hence 6 is perfect.
Exam... |
def intToBin(i):
""" Integer to two bytes """
# divide in two parts (bytes)
i1 = i % 256
i2 = int( i/256)
# make string (little endian)
return i.to_bytes(2,byteorder='little') |
def calc_iou_wh(box1_wh, box2_wh):
"""
param box1_wh (list, tuple): Width and height of a box
param box2_wh (list, tuple): Width and height of a box
return (float): iou
"""
min_w = min(box1_wh[0], box2_wh[0])
min_h = min(box1_wh[1], box2_wh[1])
area_r1 = box1_wh[0] * box1_wh[1]
area_... |
def normalise_U(U):
"""
This de-fuzzifies the U, at the end of the clustering. It would assume that the point is a member of the cluster whoes membership is maximum.
"""
for i in range(0,len(U)):
maximum = max(U[i])
for j in range(0,len(U[0])):
if U[i][j] != maximum:
U[i][j] = 0
else:
U[i][j] = 1
... |
def to_uint8_bytes(val: int) -> bytes:
"""Convert an integer to uint8."""
return val.to_bytes(1, byteorder="little") |
def _footer(settings):
"""
Return the footer of the Latex document.
Returns:
tex_footer_str (string): Latex document footer.
"""
return "\n\n\end{tikzpicture}\n\end{document}" |
def chunkify(lst, n):
"""
Splits a list into roughly n equal parts.
http://stackoverflow.com/questions/2130016/splitting-a-list-of-arbitrary-size-into-only-roughly-n-equal-parts
"""
return [lst[i::n] for i in range(n)] |
def get_indices_pattern(lines, pattern, num_lines, offset):
"""Processes the output file of the QM software used to
find the first occurence of a specifie pattern. Useful
if this block will be in the file only once and if there
is no line that explicitly indicates the end of the block.
Args:
... |
def wrap(obj, start_angle, range_angle):
"""
Wrap obj between start_angle and (start_angle + range_angle).
:param obj: number or array to be wrapped
:param start_angle: start angle of the range
:param range_angle: range
:return: wrapped angle in [start_angle, start_angle+range[
"""
retu... |
def ceillog( n ) : ## ceil( log_2 ( n )) [Used by LZ.py]
"""
>>> print(ceillog(3), ceillog(4), ceillog(5))
2 2 3
"""
assert n>=1
c = 0
while 2**c<n :
c += 1
return c |
def _resort_categorical_level(col_mapping):
"""
Resort the levels in the categorical encoders if all levels can be converted
to numbers (integer or float).
Args:
col_mapping: the dictionary that maps level string to int
Returns:
New col_mapping if all levels can be converted to num... |
def get_lines(stdout_text):
"""Assumes your console uses utf-8"""
return stdout_text.strip().decode('utf-8').split('\n') |
def greatest_sum_of_subarrays(nums):
"""
:param nums: array
:return: max sum of subarray
"""
max = sub_sum = float('-inf')
for n in nums:
if sub_sum + n <= n:
sub_sum = n
else:
sub_sum += n
if sub_sum > max:
max = sub_sum
return max |
def clear(keyword):
"""``clear`` property validation."""
return keyword in ('left', 'right', 'both', 'none') |
def build_url(tail, variation, base_url):
"""
Takes the passed parameters and builds a URL to query the OMA database
Args:
tail(str): The path and REST parameters that returns the desired info
variation(list): A list of strings that contain the parameters unique
to the query
... |
def _check_if_searching(search_form):
"""
Presentation logic for showing 'clear search' and the adv. form.
Needed to check that the form fields have non-empty value and to say
that searching on 'text_query' only should not show adv. form.
"""
searching = False
adv_searching = False
if no... |
def findIndexes(text, subString):
"""
Returns a set of all indexes of subString in text.
"""
indexes = set()
lastFoundIndex = 0
while True:
foundIndex = text.find(subString, lastFoundIndex)
if foundIndex == -1:
break
indexes.add(foundIndex)
lastFou... |
def _eth(dst, src, data):
"""Builds an Ethernet frame with and IP packet as payload"""
packet = (
dst + # dst
src + # src
b'' + # vlan
b'\x08\x00' # type
) + data
return packet |
def lower(input_string: str) -> str:
"""Convert the complete string to lowercase."""
return input_string.lower() |
def create_dt_hparams(max_depth=None, min_samples_split=2):
"""
Creates hparam dict for input into create_DNN_model or other similar functions. Contain Hyperparameter info
:return: hparam dict
"""
names = ['max_depth','min_samples_split']
values = [max_depth, min_samples_split]
hparams = dic... |
def item_brand(item, attributes_dict, attribute_values_dict):
"""Return an item brand.
This field is required.
Read more:
https://support.google.com/merchants/answer/6324351?hl=en&ref_topic=6324338
"""
brand = None
brand_attribute_pk = attributes_dict.get('brand')
publisher_attribute_pk... |
def jaccardIndexFaces(face1, face2):
"""Compute the Jaccard index between two faces"""
face1Set = set(face1)
face2Set = set(face2)
inter = len(face1Set.intersection(face2Set))
union = len(face1Set.union(face2Set))
if union == 0:
return 1
else:
return float(inter) / float(unio... |
def get_switchport_config_commands(interface, existing, proposed):
"""Gets commands required to config a given switchport interface
"""
proposed_mode = proposed.get('mode')
existing_mode = existing.get('mode')
commands = []
command = None
if proposed_mode != existing_mode:
if propo... |
def mergeDict(dict1, dict2):
""" Merge dictionaries and keep values of common keys in list"""
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[key] = [value, dict1[key]]
return dict3 |
def get_camera_kapture_id_from_colmap_id(camera_id_colmap) -> str:
"""
Create a deterministic kapture camera identifier from the colmap camera identifier:
sensor_id = "cam_xxxxx" where "xxxxx" is the colmap ID.
:param camera_id_colmap: colmap camera identifier
:return: kapture camera identifier.
... |
def set_results(to, from_):
"""
sets the main results dict.
:param to:
:param from_:
:return:
"""
to["url"].append(from_["url"])
to["description"].append(from_["description"])
to["price"].append(from_["price"])
to["site"].append(from_["site"])
return to |
def equip_sensors(worldmap, sensors):
"""
Args:
worldmap (str): a string that describes the initial state of the world.
sensors (dict) a map from robot character representation (e.g. 'r') to a
string that describes its sensor (e.g. 'laser fov=90 min_range=1 max_range=5
angle_increm... |
def csv_list(csv_str):
"""
Parser function to turn a string of comma-separated values into a list.
"""
return [int(i) for i in csv_str.split(",")] |
def isDeployed(item):
""" query a SNIPEIT asset about its deployment status """
return (item['status_label']['status_meta']=='deployed') |
def empirical_fpr(n_fp, n_nt):
"""Compute empirical false positive rate (FPR).
Input arguments:
================
n_fp : int
The observed number of false positives.
n_nt : int
The number of hypotheses for which the null is true.
Output arguments:
=================
fpr :... |
def is_symbol (c):
""" Checks whether a character is a symbol.
A symbol is defined as any character that is neither a lowercase letter, uppercase letter or digit.
Args:
c (char): The character to check.
Returns:
bool: True if the character is a symbol, otherwise false.
"""
ret... |
def To2(x, n):
"""
:param x: the value you want to convert
:param n: keep n bits
:return: binary value
"""
X = x
N = n
m = bin(X)
m = m.lstrip('0b')
a = []
L = []
if len(m) < N:
for i in range(N - len(m)):
a.append('0')
a = ''.join(a)
... |
def pad_line(line):
# borrowed from from pdb-tools (:
"""Helper function to pad line to 80 characters in case it is shorter"""
size_of_line = len(line)
if size_of_line < 80:
padding = 80 - size_of_line + 1
line = line.strip('\n') + ' ' * padding + '\n'
return line[:81] |
def print_xml(i, s, m, v, com, d):
"""Create gazebo xml code for the given joint properties"""
# Convert joint properties to xml code
# NOTE: https://www.physicsforums.com/threads/how-does-the-moment-of-inertia-scale.703101/ # noqa: E501
v = v / s ** 3
com = [x / s for x in com]
for key in d.key... |
def get_human_readable(duration):
"""
Blatenly stole from:
https://github.com/s16h/py-must-watch/blob/master/add_youtube_durations.py
"""
hours = duration[0]
minutes = duration[1]
seconds = duration[2]
output = ''
if hours == '':
output += '00'
else:
output += '0... |
def searchList(sNeedle, aHaystack):
"""Get the index of element in a list or return false"""
try:
return aHaystack.index(sNeedle)
except ValueError:
return False |
def parse_file_string(filestring):
"""
>>> parse_file_string("File 123: ABC (X, Y) Z")
('ABC (X, Y) Z', '')
>>> parse_file_string("File 123: ABC (X) Y (Z)")
('ABC (X) Y', 'Z')
>>> parse_file_string("File: ABC")
('ABC', '')
>>> parse_file_string("File 2: A, B, 1-2")
('A, B, 1-2', '')
... |
def formatSize(sizeBytes):
"""
Format a size in bytes into a human-readable string with metric unit
prefixes.
:param sizeBytes: the size in bytes to format.
:returns: the formatted size string.
"""
suffixes = ['B', 'kB', 'MB', 'GB', 'TB']
if sizeBytes < 20000:
return '%d %s' % (... |
def find_true_link(s):
"""
Sometimes Google wraps our links inside sneaky tracking links, which often fail and slow us down
so remove them.
"""
# Convert "/url?q=<real_url>" to "<real_url>".
if s and s.startswith('/') and 'http' in s:
s = s[s.find('http'):]
return s |
def has_flush(h):
"""
Flush: All cards of the same suit.
return: (hand value, remaining cards) or None
"""
suits = {suit for _, suit in h}
if len(suits) == 1:
return max([value for value, _ in h]), []
else:
return None |
def _get_mean_runtime(data: list):
"""
Calculates the average runtime/image for clustering from prior training c-means.
-----------------------------------------------------------------------------------
!!! For statistical evaluation !!!
------------------------------------------------------------... |
def make_toc(state, cls, sections):
"""
Create the class TOC.
"""
n = []
for section_cls in sections:
section = section_cls(state, cls)
section.check()
n += section.format()
return n |
def cria_peca(char):
"""
Devolve a peca correspondente ah string inserida
:param char: string
:return: peca
Recebe uma string e devolve a peca correspondente a essa string.
Caso o argumento seja invalido e nao corresponda a nenhum peca, a funcao gera um erro
"""
if char not ... |
def chmax(dp, i, x):
"""chmax; same as:
dp[i] = max(dp[i], x)
ref: https://twitter.com/cs_c_r_5/status/1266610488210681857
Args:
dp (list): one dimensional list
i (int): index of dp
x (int): value to be compared with
Returns:
bool: True if update is done
ex:... |
def trapezoid_score_function(x, lower_bound, upper_bound, softness=0.5):
"""
Compute a score on a scale from 0 to 1 that indicate whether values from x belong
to the interval (lbound, ubound) with a softened boundary.
If a point lies inside the interval, its score is equal to 1.
If the point is furt... |
def TimeToSeconds(time):
"""
Converts a timestamp to just seconds elapsed
@param time: HH:MM:SS.SSS timestamp
@type time: tuple<int, int, int, int>
@return: seconds equivalence
@rtype: float
"""
return 3600 * time[0] + 60 * time[1] + time[2] + 0.001 * time[3] |
def parse_colon_dict(data):
"""
Parse colon seperated values into a dictionary, treating lines
lacking a colon as continutation lines.
Any leading lines without a colon will be associated with the key
``None``.
This is the format output by ``rpm --query`` and ``dpkg --info``.
:param bytes... |
def group_seqs_by_length(seqs_info):
"""group sequences by their length
Args:
seqs_info: dictionary comprsing info about the sequences
it has this form {seq_id:{T:length of sequence}}
.. note::
sequences that are with uniqu... |
def ptime(s: float) -> str:
"""
Pretty print a time in the format H:M:S.ms. Empty leading fields are disgarded with the
exception of times under 60 seconds which show 0 minutes.
>>> ptime(234.2)
'3:54.200'
>>> ptime(23275.24)
'6:27:55.240'
>>> ptime(51)
'0:51'
>>> ptime(325)
'5:25'
"""
m, s = divmod(s, 60... |
def is_visible(lat, lon, domain_boundaries, cross_dateline) -> bool:
"""Check if a point (city) is inside the domain.
Args:
lat float latitude of city
lon float longitude of city
domain_boundaries list lon/lat range of domain
cro... |
def make_qs(listname: list) -> str:
"""Create a list of '?'s for use in a query string.
This is a convenience function that will take a list and return a string
composed of len(list) queston marks joined by commas for use in an sql
VALUES() clause.
Args:
listname: The... |
def test_columns(data_frame):
"""
Checks that the dataframe has the required columns.
:params dataframe data_frame:
:returns bool:
"""
required_columns = True
cols = list(data_frame)
for col in cols:
if col not in ['Draw Date', 'Winning Numbers', 'Mega Ball', 'Multiplier']:
... |
def transform_init_state_cause(cause, message):
"""
Transforms the init failure cause to a user-friendly message.
:param cause: cause of failure
:param message: failure message
:return: transformed message
"""
return {
'credentials': 'No or invalid credentials provided',
'to... |
def reduce_powers(element, powers, exponent=2):
"""
>>> reduce_powers((2, 2), [[], [], []])
((), True)
>>> reduce_powers((), [[], [], []])
((), False)
>>> reduce_powers((2, 1, 0), [[], [], []])
((2, 1, 0), False)
"""
l = []
current = None
count = 0
... |
def wrap_with_license(block, view, frag, context): # pylint: disable=unused-argument
"""
In the LMS, display the custom license underneath the XBlock.
"""
license = getattr(block, "license", None) # pylint: disable=redefined-builtin
if license:
context = {"license": license}
frag.c... |
def get_methods(object, include_special=True):
"""Returns a list of methods (functions) within object"""
if include_special:
return [method_name for method_name in dir(object) if callable(getattr(object, method_name))]
return [method_name for method_name in dir(object) if callable(getattr(object, me... |
def parse_key_id(key_id):
"""validate the key_id and break it into segments
:arg key_id: The key_id as supplied by the user. A valid key_id will be
8, 16, or more hexadecimal chars with an optional leading ``0x``.
:returns: The portion of key_id suitable for apt-key del, the portion
suitab... |
def get_available_resources(threshold, usage, total):
"""Get a map of the available resource capacity.
:param threshold: A threshold on the maximum allowed resource usage.
:param usage: A map of hosts to the resource usage.
:param total: A map of hosts to the total resource capacity.
:return: A map... |
def pipe_grav_dp(m_dot=10.0, rho=115.0, z=950.0):
"""
:param m_dot: mass flow [kg/s], (+) injection, (-) withdrawl
:param rho: density [kg/m^3]
:param z: depth/length [m]
:return delta_p: pressure loss [MPa]
"""
# gravitational constant
g = 9.81 # [m/s^2]
if m_dot > 0.0: # injec... |
def _byte_to_keys(keys_as_byte: bytes, num_keys=6) -> list:
"""Return a list of key (bit) numbers for each 1 in keys_as_byte."""
keys_as_int = int.from_bytes(keys_as_byte, 'little')
return [
key
for key in range(num_keys)
if keys_as_int & (1 << key)
] |
def first_and_last(l: list) -> list:
"""Return first and last elements takes list.
::param l: list of integers
::type l: list
::rtype: list of integers
"""
return l[0::len(l) - 1 if len(l) > 1 else None] |
def get_raw_pdb_filename_from_interim_filename(interim_filename, raw_pdb_dir):
"""Get raw pdb filename from interim filename."""
pdb_name = interim_filename
slash_tokens = pdb_name.split('/')
slash_dot_tokens = slash_tokens[-1].split(".")
raw_pdb_filename = raw_pdb_dir + '/' + slash_tokens[-2] + '/'... |
def humanize_seconds(seconds: int):
"""Convert seconds to readable format."""
seconds = int(seconds)
days = seconds // 86400
hours = (seconds - days * 86400) // 3600
minutes = (seconds - days * 86400 - hours * 3600) // 60
seconds = seconds - days * 86400 - hours * 3600 - minutes * 60
result ... |
def bondTyping(bondType, aromatic):
"""Returns type of bond based on given bondType and whether it was marked aromatic.
:param bondType:
:type bondType: :py:class:`str`
:param aromatic:
:type aromatic: :py:class:`str`
:return: bondType
:rtype: :py:class:`str`
"""
return bondType if... |
def conj(x):
"""Return conjugate of x."""
return x.conjugate() |
def get_bad_messages(rules, task):
"""
Get the bad messages for a certain task.
:param task: the name of the task
:return: a list of signatures of bad messages.
"""
if task == "service_architecture_workloads":
return ["posix_fallocate failed"]
return rules['bad_messages'] |
def _normalize_jwst_id_part(part):
"""Converts jw88600071001_02101_00001_nrs1 --> jw88600071001_02101_00001.nrs. The former is
common notation for most dataset usages, the latter is the official form for the web API to
the archive parameter service for JWST.
"""
if "_" in part and "." not in par... |
def remove_session_message_padding(data: bytes):
"""Removes the custom padding that Session may have added. Returns the unpadded data."""
# Except sometimes it isn't padded, so if we find something other than 0x00 or 0x80 *or* we
# strip off all the 0x00's and then find something that isn't 0x80, then we'... |
def temp_to_hex(value: float) -> str:
"""Convert a float to a 2's complement 4-byte hex string."""
assert (
not value or -(2 ** 7) <= value < 2 ** 7
), f"temp_to_hex({value}): is out of 2's complement range"
if value is None:
return "7FFF" # or: "31FF"?
if value is False:
re... |
def insert_after(list, new, key):
"""
Return a list with the new item inserted after the first occurrence
of the key (if any).
"""
if list == ():
return ()
else:
head, tail = list
if head == key:
return (head, (new, tail))
else:
return (hea... |
def configurationString(N_1,N_2):
"""This functions returns the filename for the given configuration N_1, N_2."""
string = str(max(N_1,N_2)) + "x" + str(min(N_1,N_2))
return string |
def fibonacci2(num):
"""Permette di calcolare il num-esimo numero di fibonacci.
L'algoritmo proposto e' quello ricorsivo."""
if num == 0:
return 0
elif num <=2:
return 1
else:
return fibonacci2(num-1) + fibonacci2(num-2) |
def _dash_escape(args):
"""Escape all elements of *args* that need escaping.
*args* may be any sequence and is not modified by this function.
Return a new list where every element that needs escaping has been
escaped.
An element needs escaping when it starts with two ASCII hyphens
(``--``). Es... |
def add_needed_ingredients(f_raw_materials, d_raw_materials, f_secret_points):
""" Check for missing ingredients and add them in.
Params:
f_raw_materials: dict
d_raw_materials: dict
f_secret_points: int
Returns:
str, int
"""
f_secret_points -= 1
for f_raw_materi... |
def convert_number_to_letter(number: int) -> str:
"""
This function receives a number, and converts it to its respective alphabet letter in ascending order,
for example:
1 - A
2 - B
3 - C
4 - D
:param int number: The number to be converted.
:rtype: str
"""
return chr(ord('@'... |
def get_column_unit(column_name):
"""Return the unit name of an ivium column, i.e what follows the first '/'."""
if "/" in column_name:
return column_name.split("/", 1)[1] |
def unit_size(size):
""" Convert Byte size to KB/MB/GB/TB.
"""
units = ['KB', 'MB', 'GB', 'TB']
i = 0
size = size / 1024
while size >= 1024 and i<(len(units)-1):
i = i + 1
size = size / 1024
return '%.2f %s'%(size, units[i]) |
def is_same_class(obj, a_class):
"""Returns True if obj is same instance, else False
"""
if type(obj) is a_class:
return True
else:
return False |
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new ha... |
def get_LA_GeoJson(LA_cd):
"""
returns a link to LSOA geojson file within LA passed from https://github.com/martinjc/UK-GeoJSON/
"""
link_base = 'https://raw.githubusercontent.com/martinjc/UK-GeoJSON/master/json/statistical/eng/lsoa_by_lad/'
new_link = link_base+str(LA_cd)+'.json'
return new_... |
def params_to_string(num_params, units=None, precision=2):
"""Convert parameter number into a string.
Args:
num_params (float): Parameter number to be converted.
units (str | None): Converted FLOPs units. Options are None, 'M',
'K' and ''. If set to None, it will automatically choose... |
def fmt(x, empty="-", role=None):
"""
Format element to a humanized form.
"""
if x is None:
return empty
return str(x) |
def generate_graph_with_template(data, title, yaxis_title, xaxi_title):
"""
This common layout can be used to create Plotly graph layout.
INPUT:
data - a graph required JSON data i.e list
title - a tile of the chart
yaxis_title - Y title
xaxix_title - X title
OUTPUT:
... |
def _format_ptk_style_name(name):
"""Format PTK style name to be able to include it in a pygments style"""
parts = name.split("-")
return "".join(part.capitalize() for part in parts) |
def trailing_zeros(phenome):
"""The bare-bones trailing-zeros function."""
ret = 0
i = len(phenome) - 1
while i >= 0 and phenome[i] == 0:
ret += 1
i -= 1
return ret |
def precut(layers, links, all_terms, user_info):
"""
This function cuts terms in layers if they do not exist inside
the accuracy file of model 1.
It also cuts all links if one of the terms inside does not exist
inside the accuracy file of model 1.
Finaly it cuts all terms taht do not exist insid... |
def _number_power(n, c=0):
"""
This is an odd one, for sure. Given a number, we return a tuple that tells us
the numerical format to use. It makes a little more sense if you think of
the second number in the tuple as a pointer into the list:
('', 'hundred', 'thousand', 'million', ...)
...s... |
def get_index(node):
"""
returns a key value for a given node
node: a list of two integers representing current state of the jugs
"""
return pow(7, node[0]) * pow(5, node[1]) |
def sort_list_using_sort(lst):
"""
The sort() method sorts the list ascending by default.
While sorting via this method the actual content of the tuple is changed
"""
lst.sort(key=lambda x:x[1])
return lst |
def one_cycle_schedule(step, total_steps, warmup_steps=None, hold_max_steps=0, lr_start=1e-4, lr_max=1e-3):
""" Create a schedule with a learning rate that decreases linearly after
linearly increasing during a warmup period.
"""
if warmup_steps is None:
warmup_steps = (total_steps - hold_max_steps... |
def join_range(r):
"""Converts (1, 2) -> "1:2"
"""
return ":".join(map(str, r)) if r else None |
def layer2namespace(layer):
"""
converts the name of a layer into the name of its namespace, e.g.
'mmax:token' --> 'mmax'
"""
return layer.split(':')[0] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.