content stringlengths 42 6.51k |
|---|
def lr_schedule(epoch):
"""Learning Rate Schedule
Learning rate is scheduled to be reduced after 30, 60, 90, 120 epochs.
Called automatically every epoch as part of callbacks during training.
# Arguments
epoch (int): The number of epochs
# Returns
lr (float32): learning rate
"... |
def lowercase_words(text):
"""
Method used to transform text to lowercase"
Parameters:
-----------------
text (string): Text to clean
Returns:
-----------------
text (string): Text after transforming to lowercase.
"""
text = text.lower()
return text |
def euler(faces, edges, verticies):
"""
Calculate the value of Euler's formula of a shape.
:type faces: integer
:param faces: The faces of the shape
:type edges: integer
:param edges: The edges of the shape
:type verticies: integer
:param verticies: The verticies of the shape
:re... |
def _get_value(data, tag):
"""
Returns first value of field `tag`
"""
# data['v880'][0]['_']
if len(tag) < 4:
tag = "v" + tag[1:].zfill(3)
try:
return data[tag][0]['_']
except (KeyError, IndexError):
return None |
def warn_only(flag):
"""Expression constraint mutator/wrapper:
When flag is True, the wrapped expression was satisifed, so return True
signaling a passed validator expression.
If the flag is False, the expression evaluated successfully but was not
satisified. Return the value "W" signaling that ... |
def get_viewed_text_actions(viewed_text_keystrokes):
""" Examine FURNITURE_CLICK keystrokes and determine which are potential
actions by the assistant where they viewed the text descriptions of items.
Args:
viewes_text_keystrokes: list of FURNITURE_CLICK keystrokes
Returns:
list of 'po... |
def remove_adjacent_dups(xs):
""" Return a new list in which all adjacent
duplicates from xs have been removed.
"""
result = []
most_recent_elem = None
for e in xs:
if e != most_recent_elem:
result.append(e)
most_recent_elem = e
return result |
def minhash(str_a, str_b):
"""
:param str_a: str
:param str_b: str
:Sentences: should be tokenized in string
str_a = u"There is"
str_b = u"There was"
Thanks to Pulkit Kathuria(@kevincobain2000) for the definition of the function.
The function make... |
def collapsed_faint(file_name, guard):
"""Returns the include-guard with a double FAINT_-prefix reduced to
one.
This allow include guards for files named "faint-" to start with
a single "FAINT_" prefix."""
if file_name.startswith("faint-") and guard.startswith("FAINT_FAINT_"):
ret... |
def TabToRecord(tab):
"""
output the string for a graphviz record label for the
list of transcripts tab
"""
return ["[label = \"{" + " | ".join(tr) + "}\"]" for tr in tab] |
def get_header(json_list):
"""
Return a list of header strings for the give list of dictionaries.
Args:
json_list (list): list of dictionaries produced by an API request
Returns:
list: fieldnames used in the data.
"""
header = set()
for dict in json_list:
header.upd... |
def gen_qrel_str(query_id, doc_id, rel_grade):
"""Produces a string representing one QREL entry
:param query_id: question/query ID
:param doc_id: relevanet document/answer ID
:param rel_grade: relevance grade
:return: a string representing one QREL entry
"""
return f'{query_id} 0 {d... |
def divide_branch(branch):
"""
Split work into two
"""
model_name, explore_name, fields, starting_field_count = branch
left_fields = fields[:len(fields)//2]
right_fields = fields[len(fields)//2:]
return [[model_name, explore_name, left_fields, starting_field_count],
[model_name, ... |
def sp_vidx(i):
"""Computes the index of the optimal (p_vars) in the optimal solution of the Exponential Cone Programming
Args:
i: int
Returns:
int
"""
return 3*i+1 |
def distance(seq1, seq2):
""" Calculate the Hamming difference between two DNA strands """
if len(seq1) != len(seq2):
raise ValueError("Unequal sequence lengths:", seq1, seq2)
return sum(1 for i, j in zip(seq1, seq2) if i != j) |
def assign_group(subject_row, task):
""" Define which group this subject belongs to """
controls = {401, 402, 403, 404, 405, 418}
shams = {751, 753, 755, 758, 762, 763, 764, 768, 769}
treat = {752, 754, 756, 757, 759, 760, 761, 766, 767}
# check for set membership to determine where subject belong... |
def get_lalapps_commandline_from_SFTDescriptor(descriptor):
"""Extract a lalapps commandline from the 'comment' entry of a SFT descriptor.
Most SFT creation tools save their commandline into that entry,
so we can extract it and reuse it to reproduce that data.
Parameters
----------
descriptor:... |
def getnameextensions(name):
"""get extensionof the name"""
a = name.rfind('.')
return name[a:]
return |
def get_var_name(var) -> str:
"""Get an appropriate, plain variable name for a variable."""
return str(getattr(var, "name", var)) |
def R_curv(deltaT_sub, r_min, radius, Q_drop):
""" thermal resistance due drop curvature
Parameters
----------
deltaT_sub: float
temperature difference to the cooled wall in K
r_min: float
minimum droplet radius in m
radius: float
... |
def UpdateDict(Dict, key, info):
"""Update dictionary by adding new values to existing.
USAGE:
UpdateDict(Dict,key,info)
"""
if key in Dict:
dinfo = Dict[key]
for n in range(len(dinfo)):
dinfo[n] = info[n] + dinfo[n]
else:
dinfo = info[:] # Make a copy of info list
Dict[key] = dinf... |
def get_closure(rel, v):
"""
Return transitive closure of values v1 such that "v rel v1",
given a dictionary of direct relations.
Termination depends on directed relation; i.e.
v1 in rel(v) => v not in get_closure(rel, v1)
Thus the get_closure recursive call can never include v, as
al... |
def valid_XML_char_ordinal(i):
"""
Is the character i an allowed XML character
:param i: the character
:return: True if allowed, False if not
"""
return ( # conditions ordered by presumed frequency
0x20 <= i <= 0xD7FF
or i in (0x9, 0xA, 0xD)
or 0xE000 <= i <= 0xFFFD
... |
def viscosity_dynamic(ro_st, T_pr, p_pr):
"""
:param ro_st: (float) Density of the natural gas at standard parameters, kg/m3
:param T_pr: (float) Reduced temperature of the natural gas at standard parameters, dimensionless
:param p_pr: (float) Reduced pressure of the natural gas at standard parameters, ... |
def listify(item_or_list):
"""
This function converts single items into single-item lists.
"""
return item_or_list if isinstance(item_or_list, list) else [item_or_list] |
def minor(release):
"""Add a suffix to release, making 'X.Y' become 'X.Y.Z'."""
return release + ".1" |
def search_types(results: dict):
"""
Convert Elasticsearch results into RPC results conforming to the
"search_types" method.
"""
# Convert the ES result format into the API format
search_time = results['search_time']
type_counts = results['aggregations']['type_count']['counts']
type_to_c... |
def S_id(v):
"""Fingerprints a potential value to a string identifier."""
# This mostly "trims" the cosmological constant (so we can
# always disambiguate by just adding more digits and keeping
# substring identity), but nevertheless makes e.g.
# 11.99999999999972 ==> S1200000.
return 'S{:07d}'.format(int(-... |
def from_rgb(r,g,b):
"""
return #colorstring from r,g,b integers
"""
# hex() produces "0x08", we want just "08"
rgb = [hex(i)[2:].zfill(2) for i in map(int, [r,g,b])]
return "#" + "".join(rgb) |
def get_padding_for_kernel_size(kernel_size):
"""Compute padding size given kernel size."""
if kernel_size == 7:
return (3, 3)
elif kernel_size == 3:
return (1, 1)
else:
raise ValueError('Padding for kernel size {} not known.'.format(
kernel_size)) |
def get_link_for_filename(filename, paths_or_urls):
"""
Return a link for `filename` found in the `links` list of URLs or paths. Raise an
exception if no link is found or if there are more than one link for that
file name.
"""
path_or_url = [l for l in paths_or_urls if l.endswith(f'/{filename}')... |
def add_word_continuation_tags(tags):
"""In place, add a continuation tag to each word:
<cc/> -continues current utt and the next word will also continue it
<ct/> -continues current utt and will end it
<tc/> -starts a new utt and the next word will continue it
<tt/> -starts and ends utt (single word... |
def tab(num):
"""
Get tab indentation.
Parameters
----------
num : int
indentation depth
"""
return num * 4 * " " |
def streamprint(iterator, filehandle, bufferlength=10000, sep='\n'):
"""Given an iterator of lines and a filehandle, prints the content of the
iterator to the file in a memory-efficient way.
Return the number of iterator-given strings processed."""
buffer = list()
operations = 0
f... |
def listType(l):
"""
If the type of every element of the list l is the same, this function
returns that type, else it returns None. If l is not a list, this function
will raise a ValueError.
"""
if not isinstance(l, list):
raise ValueError("l is not a list.")
if len(l) == 0:
... |
def color_distance(rgb1, rgb2):
""" Compute absolute difference between 3-channels. """
r1, g1, b1 = rgb1
r2, g2, b2 = rgb2
return abs(r2-r1) + abs(g2-g1) + abs(b2-b1) |
def load_for_user(user):
"""
Load record for user
"""
return [{"test": "test", "expiry": "2100-01-01 00:00:00"}] |
def get_axis_vector(axis_name, offset = 1):
"""
Convenience. Good for multiplying against a matrix.
Args:
axis_name (str): 'X' or 'Y' or 'Z'
Returns:
tuple: vector eg. (1,0,0) for 'X', (0,1,0) for 'Y' and (0,0,1) for 'Z'
"""
if axis_name == 'X':
r... |
def is_isogram(string) -> bool:
"""
Determine if a word or phrase is an isogram.
An isogram (also known as a "nonpattern word") is a word
or phrase without a repeating letter,
however spaces and hyphens are allowed to appear multiple times.
Examples of isograms:
lumberjacks
bac... |
def reverse_map_path(rev_map, path, interfaces = False):
"""Returns list of nodes in path
interfaces selects whether to return only nodes, or interfaces
e.g. eth0.r1 or just r1
"""
result = []
for hop in path:
if hop in rev_map['infra_interfaces']:
iface = rev_map['infra_int... |
def get_op_bbox(frame):
"""
Arguments:
frame: dictionary of joint indices to normalized coords [x, y, conf]. ie {0: [.5, .5, .98]}
Returns:
4 normalized bounding box coordinates x1, x2, y1, y2
"""
x1 = 1
x2 = 0
y1 = 1
y2 = 0
for key in frame:
joint = frame[ke... |
def _ensure_tuples(list):
""" Ensures that an iterable is a list of position tuples. """
return [tuple(item) for item in list] |
def nohighlight(nick):
"""add a ZWNJ to nick to prevent highlight"""
return nick[0] + "\u200c" + nick[1:] |
def rgb(r, g, b):
"""."""
col = [max(min(x, 255), 0) for x in [r, g, b]]
return ''.join([hex(i)[2:].upper() if i > 16 else "0" + hex(i)[2:] for i in col]) |
def count_helices(d):
"""Return the helix count from structure freq data."""
return d.get('H', 0) + d.get('G', 0) + d.get('I', 0) |
def rewrite_event_to_message(logger, name, event_dict):
"""
Rewrite the default structlog `event` to a `message`.
"""
event = event_dict.pop('event', None)
if event is not None:
event_dict['message'] = event
return event_dict |
def collatz(number):
"""iterative"""
result = [number]
while number != 1:
if number % 2 == 0:
number //= 2
else:
number = 3 * number + 1
result.append(number)
return result |
def readable_string(input_string: str) -> str:
"""Remove multiple whitespaces and \n to make a long string more readable"""
return " ".join(input_string.replace("\n", "").split()) |
def topological_sort(dag):
"""Sort the nodes in a DAG in a topological order.
The algorithm is from :footcite:`kahn:1962`.
"""
names = set(range(len(dag)))
edges = set((u, f[0]) for f in dag for u in f[1])
l = list()
s = set(names)
for pnode in names:
for cnode in names:
... |
def _split_and_clean_args(args):
"""
Given a string of arguments from a ctypesgen-generated wrapper, parse
them into a list of something we can use later.
"""
args = args.replace('[', '').replace(']', '')
args = args.split(',')
args = [arg.strip().rstrip() for arg in args]
for i in ... |
def parse_anything(text, match=None, match_start=0):
"""
Provides a generic type converter that accepts anything and returns
the text (unchanged).
:param text: Text to convert (as string).
:return: Same text (as string).
"""
# pylint: disable=unused-argument
return text |
def uri_leaf(uri):
"""
Get the "leaf" - fragment id or last segment - of a URI. Useful e.g. for
getting a term from a "namespace like" URI.
>>> uri_leaf("http://purl.org/dc/terms/title") == 'title'
True
>>> uri_leaf("http://www.w3.org/2004/02/skos/core#Concept") == 'Concept'
True
>>> ur... |
def PopulateExpectations(all_expectations):
"""Accepts Expectations and parses out the storyname and disabled platforms.
Args:
all_expectations = {
story_name: [[conditions], reason]}
conditions: list of disabled platforms for story_name
reason: Bug referencing why the test is disabled on the p... |
def __valid_svm_params(params):
"""Whether supplied params are valid for an SVM classifier
Args:
params (dict): Dictionary of parameters and its values.
Returns:
Whether supplied params are valid or not.
"""
# valid svm params
svm_params = ['kernel', 'C', 'gamma']
# the ... |
def d_x_diffr_dy(x, y):
"""
derivative of d(x/r)/dy
:param x:
:param y:
:return:
"""
return -x*y / (x**2 + y**2)**(3/2.) |
def category_choice(choice=None):
"""
This method will receive one optional parameter from the specified choice string and return the user selection
if it's an available and empty string if it's not and if nothing passed it will return all available category
choices as a tuple
: pa... |
def tone_filter_color_assigner(color_list: list) -> list:
"""
Author: Jeremy Trendoff
Returns the RGB values of the colors selected in the
two, three tone filters.
Accepts a list of colors inputed by the user and assigns the related RGB
value to the coorisponding position in a list.
... |
def get_column_letter(n: int) -> str:
"""
This function converts the column index to column letter
1 to A,
5 to E, etc
:param n:
:return:
"""
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string |
def buscarValor(matriz, valor):
"""Busca en la matriz pasada como argumento el valor dado. Solo devuelve
la posicion del primer valor coincidente. En el caso de no encontrar
ninguno, devuelve (-1,-1) """
res = (-1, -1)
for y in range(len(matriz)):
aux = matriz[y]
for x in r... |
def check_if_two_nodes_in_same_building(i, j, nf):
"""
:param i: node id 1
:param j: node id 2
:param nf: number of floors in each building
:return: True, if they are in same building, else False
"""
s1 = int(i/nf)
s2 = int(j/nf)
if s1 == s2:
return True
else... |
def str2dict(string):
"""
transform string "-a b " or "--a b" to dict {"a": "b"}
:param string:
:return:
"""
assert isinstance(string, str)
r = {}
param = ""
value = []
for p in string.split():
if not p:
continue
if p.startswith("-"):
if... |
def recv_all(s, limit=4196):
"""
receive all data from a socket
Args:
s: python socket
limit: limit size to get response
Returns:
response or b""
"""
response = ""
while len(response) < limit:
try:
r = s.recv(1)
if r != b"":
... |
def differentiate_polynomial(coefficients):
"""
Calculates the derivative of a polynomial and returns
the corresponding coefficients.
"""
new_coeffs = []
for deg, prev_coef in enumerate(coefficients[1:]):
new_coeffs.append((deg + 1) * prev_coef)
return new_coeffs |
def doc_summary(lines):
"""Extract summary of docs."""
summary = []
for line in lines:
stripped = line.strip().lower()
if (stripped.startswith('to use this normalizer') or
stripped.startswith('use ``method')):
continue
if (line.startswith('Parameters') or ... |
def _get_folder(filepath):
"""
Handles adding a / or \\ to the end of a directory path.
Args:
filepath: string
Returns:
string
"""
if '/' in filepath:
folder = filepath if filepath[-1] == '/' else filepath + '/'
elif '\\' in filepath:
folder = filepath if f... |
def getMaxKeyValuePPI(dict_values_freq:dict):
"""
get the maximum key value in a dictionary
:param dict_values_freq: dictionary with the PPI scores
:type dict_values_freq: dictionary[int:array]
:return: max value of PPI score
:rtype: int
"""
max_value_ppi = max(dict_values_freq, key... |
def factors(number):
"""
This method will return the factors
"""
values = []
for index in range(2,(number//2)+1):
if number%index == 0:
values.append(index)
return values |
def get_upload_folder_structure(file_name):
"""
Return the structure in the upload folder used for storing and
retrieving uploaded files.
Two folder levels are created based on the filename (UUID). The
first level consists of the first two characters, the second level
consists of the third char... |
def convert_interval(s_in, s_op, func):
"""Return range of kmers or filtering ratios.
"""
msg = "bad {}: {} {}"
try:
s = list(map(func, s_in.split(":")))
except:
raise Exception(msg.format("value", s_op, s_in))
if len(s) == 1:
return s
if len(s) == 3:
beg, en... |
def get_full_path_file_name(folder_name, file_name):
""" Build full path to file given folder and file name """
full_path_file_name = ''
if folder_name > '':
full_path_file_name = folder_name + '/'
full_path_file_name += file_name
return full_path_file_name |
def unwrap_list(something):
"""
Single things don't need to be in lists for some purposes
"""
if (isinstance(something, list)) and (len(something) == 1):
return something[0]
else:
return something |
def determine_fields(obj_list):
"""
Returns the set of all possible keys in the object list
"""
fields = []
for obj in obj_list:
for key in obj.keys():
if key not in fields:
fields.append(key)
return fields |
def linker_flag_for_sdk_dylib(dylib):
"""Returns a linker flag suitable for linking the given `sdk_dylib` value.
As does Bazel core, we strip a leading `lib` if it is present in the name
of the library.
Args:
dylib: The name of the library, as specified in the `sdk_dylib`
attribute... |
def check_luci_path(Luci_path):
"""
Functionality to check that the user has included the trailing "/" to Luci_path.
If they have not, we add it.
"""
if not Luci_path.endswith('/'):
Luci_path = Luci_path + '/'
print("We have added a trailing '/' to your Luci_path variable.\n")
... |
def get_plea_type(context_data):
"""
Determine if pleas for a submission are
all guilty - returns "guilty"
all not guilty - returns "not_guilty"
or mixed - returns "mixed"
"""
guilty_count = len([plea for plea in context_data["plea"]["data"]
if plea["gui... |
def stringTransform(mathData):
"""Transform data back into string form with ',' delimiter"""
stringData = []
for i in range(0, len(mathData)):
line = ""
for j in range(0, len(mathData[i])):
line += str(mathData[i][j]) + "," # Add each float term to the string with the deli... |
def convert_rules(rules):
"""
Converts a list of rule files to a dict of rule files.
Keyword arguments:
rules -- list of rule files as fully qualified paths
Argparse returns a list of files, use this to convert it
to a dictionary in the format of:
{'RuleFile0' : '/path/to/first', 'RuleFile... |
def bin_search(query, data):
""" Query is a coordinate interval. Binary search for the query in sorted data,
which is a list of coordinates. Finishes when an overlapping value of query and
data exists and returns the index in data. """
i = int(round(len(data)/2)) # binary search prep
lower, upper = 0, len(... |
def url_method_key(url: str, method: str) -> str:
"""
Generate a fake key based on url and method
:param url: str -> The url
:param method: str -> The method
:return: str
"""
return f"{method.lower()}-{url}" |
def get_candidates(postings, le):
"""
Gets the possible document candidates from the postings list
returned in get_posts(). If a document is seen in a postings list,
it is added to a dictionary, along with the word(or words) it is
associated with and the term frequencies of those wo... |
def num_half_weekends(x, wkend_type):
"""
Compute number of full weekends (both days) worked in a given weekends worked pattern.
:param x: list of 2-tuples representing weekend days worked. Each list
element is one week. The tuple of binary values represent the
first and second day ... |
def filter_affirmative(answers):
"""Create a set of affirmative answers"""
return set(answers.replace("\n", "")) |
def solve_part_two(sequence: list) -> int:
"""
Calculates the first frequency that occurs twice
:param sequence: Python list of integer frequency changes
:return: First repeated frequency
"""
frequencies = {0}
counter = 0
current = 0
while True:
current += sequence[counter]
... |
def mergeStatements(statements, allow_none=False):
""" Helper function that merges nested statement sequences. """
merged_statements = []
for statement in statements:
if statement is None and allow_none:
pass
elif type(statement) in (tuple, list):
merged_statements +... |
def choose_key(dictionnary: dict):
"""return one random key from a dictionnary."""
import random
keys = [k for k in dictionnary.keys()]
return random.choice(keys) |
def tile_to_screen(pos, dims, off, p, screen_height=None):
"""Take tile coords and convert to screen coords
by default converts into bottom-left screen coords,
but with height attribute supplied converts to top-left
returns the bottom-left position of the tile on the screen"""
offx, offy = off
... |
def CRRA(cons, gamma):
"""
CRRA utility function.
:params: cons: consumption level.
:params: gamma: relative risk aversion.
:return: util: utility level.
"""
import math
if not gamma == 1:
util = cons**(1-gamma)/(1-gamma)
else:
util = math.log(cons)
... |
def _get_pad_left_right(small, large):
""" Compute left and right padding values.
Here we use the convention that if the padding
size is odd, we pad the odd part to the right
and the even part to the left.
Parameters
----------
small : int
Old size of original 1D array
... |
def get_chunk_type(tok, idx_to_tag):
"""
Args:
tok: id of token, ex 4
idx_to_tag: dictionary {4: "B-PER", ...}
Returns:
tuple: "B", "PER"
"""
tag_name = idx_to_tag[tok]
tag_class = tag_name.split('-')[0]
tag_type = tag_name.split('-')[-1]
return tag_class, tag_typ... |
def find_word_in_a_sentence(word, sentense):
"""find a word in a sentense"""
status = True
word = word.replace(' ', '').lower()
sentense = sentense.replace(' ', '').lower()
for char_in_word in word:
lst = [pos for pos, char in enumerate(sentense) if char == char_in_word]
if len(lst) ... |
def has_ship(data, coordinates):
"""
(data, tuple) -> (bool)
A function based on read data and cell coordinates (for example ("J", 1) or
("A", 10)) determines whether a ship is in this cell.
"""
let_num = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7,
"I": 8, "J... |
def sorted_by_key(x, i, reverse=False):
"""For a list of lists/tuples, return list sorted by the ith
component of the list/tuple, E.g.
Sort on first entry of tuple:
> sorted_by_key([(1, 2), (5, 1]), 0)
>>> [(1, 2), (5, 1)]
Sort on second entry of tuple:
> sorted_by_key([(1, 2), (5,... |
def build_profile(first, last, **user_info):
"""Build a dictionnary countaining everything we know about a user."""
profile = {}
profile['first name'] = first
profile['last name'] = last
for key, value in user_info.items():
profile[key] = value
return profile |
def _2d_translate(position1, position2):
"""add two 2d vectors"""
return (position1[0] + position2[0], position1[1] + position2[1]) |
def a_function(x=0):
"""This regular docstring does not conflicts with the above markdoc"""
return f'Hello {x}' |
def end_of_game(player_pouch, comp_pouch, deck):
"""
This function determines who wins after the game ends.
"""
if len(player_pouch) == 0:
print("You Win!")
return 1
elif len(comp_pouch) == 0:
print("You Lose!")
return 2
elif len(deck) == 0:
if len(player_... |
def get_sum2(a: int, b: int) -> int:
"""
My second version, that is just a more concise version of the first one.
"""
return a if a == b else sum([i for i in range(min(a, b), max(a, b)+1)]) |
def build_MD_analysis_script(in_simulation_name:str, in_folder:str, in_topology_path: str,
out_dir:str, out_script_path:str,
in_ene_ana_lib:str, gromosPP_path:str):
"""
BAD FUNCTION! HISTORIC RELICT
Parameters
----------
in_simulation_nam... |
def get_sm_from_descriptor(descr):
"""
This method returns a list of specific managers based on
a received desriptor
"""
sm_dict = {}
if "service_specific_managers" in descr:
sm_dict = {}
for ssm in descr["service_specific_managers"]:
for option in ssm["options"]:
... |
def summa(f, k, p):
"""Return the sum of f(i) from i=k, k+1, ... till p(i) holds true or 0.
This is a tail recursive implementation."""
return 0 if not p(k) else f(k) + summa(f, k+1, p) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.