content stringlengths 42 6.51k |
|---|
def clean_text(word, old_method=True):
"""Quote normalization; replace u2014 and u2212."""
if old_method:
# NOTE(thangluong): this version doesn't work as intended in Python 2.
# '\u2014' is different than the Unicode symbol u'\u2014'
# docqa code might have worked in Python 3
# https://github.c... |
def build_config(anisotropic, coupled_sym):
"""
Gets training configuration.
Args:
anisotropic (bool): if True, use an anisotropic graph manifold.
coupled_sym (bool): if True, use coupled symmetric layers.
cnn (bool): if True, use a convolutional neural network.
Returns:
... |
def vertexHoplength(toplexes, vertices, maxHoplength=None):
"""Compute the edge hoplength distance to a set of vertices within the complex. Returns the list of tuples (vertex,distance)"""
vertslist = list(set([v for s in toplexes for v in s if v not in vertices]))
outlist = [(v, 0) for v in vertices] # Pr... |
def str2bool(v:str):
"""Converts string to boolean"""
return v.lower() in ('yes', 'true', 't', '1') |
def linesort(a):
"""
Define the order of attributes for the line.
"""
order = ['line', 'tag', 'span_id', 'lang_name', 'lang_code', 'fonts']
return order.index(a) if a in order else len(order) |
def band_matrix_trace(a, b, size, gram=True):
"""
Computes the trace of band matrix based on known formula.
"""
if gram:
trace_ = a**2 + (size-1) * (a**2 + b**2)
else:
trace_ = size * a
return trace_ |
def isDmzProxySecurityLevelValid( level ):
"""Indicates whether the supplied level is valid for secure proxy security."""
if (('high' == level) or ('medium' == level) or ('low' == level)):
return True
return False |
def split_host(host, port: int = None) -> tuple:
"""Given a host:port and/or port, returns host, port."""
if ":" in host:
addr, port = host.split(":")
port = int(port)
elif port:
addr = host
port = int(port)
else:
addr = host
port = int(pytak.DEFAULT_COT_P... |
def get_travel_requests_of_timetables(timetables):
"""
Retrieve a list containing all the travel_request_documents,
which are included in a list of timetable_documents.
:param timetables: [timetable_documents]
:return: travel_requests: [travel_request_documents]
"""
travel_requests = []
... |
def parseCustomHeaders(custom: str) -> list:
"""
Parse string of semi-colon seperated custom headers in to a list
"""
if ";" in custom:
if custom.endswith(';'):
custom = custom[:-1]
return custom.split(';')
else:
return [custom] |
def findVarInFunction(function):
"""
:param function: String
:return: list
"""
resultset = set()
for char in function:
if char.isalpha():
resultset.add(char)
return list(resultset) |
def maybe_flip(value, flip):
"""Flips a control (or not).
Meant to translate controls that naturally take values close to 1
(e.g. momentum) to a space where multiplication makes sense (i.e. close to 0).
Args:
value: float or numpy array, value of the control.
flip: bool, whether to flip or not.
Ret... |
def price(x):
"""
format the coords message box
:param x: data to be formatted
:return: formatted data
"""
return '$%1.2f' % x |
def html_escape(val):
"""Wrapper around cgi.escape deprecation."""
from html import escape
return escape(val) |
def sort_words(arguments, words):
"""
Takes a dict of command line arguments and a list of words to be sorted.
Returns a sorted list based on `alphabetical`, `length` and `reverse`.
"""
if arguments.get('--alphabetical', False):
words.sort()
elif arguments.get('--length', False):
... |
def base(base_url: str) -> str:
"""
Build the base URL of our API endpoint
"""
return '/'.join([base_url, 'api', 'v1']) |
def parse_stretches(gene, stretches, info_func):
""" Extract information from stretches.
`info_func(gene, stretch)` defines what further information should be extracted
"""
# sorted stretches by length
tmp = []
for stretch in stretches:
tmp.append((
len(stretch.group()),
... |
def upvotes(pages):
"""Upvotes."""
return sum([v.value for v in p.votes].count(1) for p in pages) |
def testInteger(str_in):
"""
Tests if int inputs are correct.
"""
try:
i = int(str_in)
except:
return False
return True |
def center_reposition(center, frame):
"""Reposition center so that (0, 0) is in the middle of the frame and y is
pointing up instead of the OpenCV standard where (0, 0) is at the top left
and y is pointing down.
:param center: OpenCV center (x, y)
:param frame: Frame to reposition center within
... |
def flipvert(m):
"""
>>> flipvert([[1, 2], [3, 4]])
[[3, 4], [1, 2]]
"""
return m[::-1] |
def verify_variant_type(variants, variant_type, pos, length):
""""Helper function for checking a specific variant type.
Args:
variants: List of variants to look through.
variant_type: The type of variant to verify.
pos: Position of the variant.
length: Size of the variant.
... |
def normalize_package_style(package_style):
"""Normalizes the package style."""
if '/' in package_style:
parts = map(normalize_package_style, package_style.split('/'))
print(list(parts))
return '/'.join(parts)
return '-'.join(package_style.split('-')[0:-1]) |
def _check_not_none(value, name):
"""Checks that value is not None."""
if value is None:
raise ValueError(f"`{name}` must be specified.")
return value |
def phredToQual( qual ):
"""
Take a qual string that is phred/sanger encoded
turn it into a list of quals
"""
return [ord(x)-33 for x in list(qual)] |
def fahrenheit_from(celsius):
"""Convert Celsius to Fahrenheit degrees."""
try:
fahrenheit = float(celsius) * 9 / 5 + 32
fahrenheit = round(fahrenheit, 3) # Round to three decimal places
return str(fahrenheit)
except ValueError:
return "invalid input" |
def hex_rect_unknoll(dx, dy, rect_x, rect_y, rect_z, width, height, inc_bottom=False, inc_top=False):
"""Given a co-ordinate pair and a rectangle, reverses hex_rect_knoll"""
oy = - (dx // 2) - (dx % 2) * int(inc_bottom)
return rect_x + dx, rect_y + oy + dy, rect_z - dx - oy - dy |
def unicodify(s, encoding='utf-8', norm=None):
"""Ensure string is Unicode.
.. versionadded:: 1.31
Decode encoded strings using ``encoding`` and normalise Unicode
to form ``norm`` if specified.
Args:
s (str): String to decode. May also be Unicode.
encoding (str, optional): Encodin... |
def join_chains(low, high):
"""Join two hierarchical merkle chains in the case where the root of a lower tree is an input
to a higher level tree. The resulting chain should check out using the check functions. Use on either
hex or binary chains.
"""
return low[:-1] + high[1:] |
def sub_list(aList, bList):
"""Return the items in aList but not in bList."""
tmp = []
for a in aList:
if a not in bList:
tmp.append(a)
return tmp |
def format_speed(count, size, elapsed_time):
"""Return speed in MB/s and kilo-line count/s"""
# On windows, time.monotonic measurement seems to be of 15ms increment,
# to prevent division by zero, pick the minimum value:
elapsed_time = 0.015 if elapsed_time == 0 else elapsed_time
return "%.03fs at %... |
def insert_dummy_packets(trace, index, num_dummies=1, direction=1):
"""Insert dummy packets to the trace at a given position.
:param trace: Trace
:param index: Index before which to insert the packets
:param num_dummies: Number of dummy packets to insert
:param direction: Dummy direction, one of [+... |
def greedy_hire(lambs):
""" Pay to the henchmen as low as possible"""
# Edge case I: we can pay only to the junior.
if (lambs < 1):
print ("Greedy (special):\n [0]")
print (" -> Sum: 0")
return 0
# Edge case II: we can pay only to the first two juniors.
elif (lambs < 2):
... |
def strlist(alist):
"""List of strings, comma- or space-separated"""
if isinstance(alist, str):
for s in "()[]'"+'"':
alist = alist.replace(s, "")
alist = alist.replace(",", " ")
alist = alist.split(" ")
alist = [a for a in alist if a.strip()]
alist = sorted(alist)
... |
def join(seq):
"""Create a joined string out of a list of substrings."""
return "".join(seq) |
def _get_state_memcache_key(exploration_id, state_id):
"""Returns a memcache key for a state."""
return 'state:%s:%s' % (exploration_id, state_id) |
def search_codetree(tword,codetree):
""" Finds the word in codetree (symbol per node),
returns frequency or 0 if not found
"""
pos = 0
while True:
s = tword[pos]
if s not in codetree:
return 0
elif pos==len(tword)-1:
return codetree[s][0]
e... |
def lin_interp(x, x0, x1, y0, y1):
"""
Do a bunch of linear interpolations
"""
y = y0*(1.-(x-x0)/(x1-x0)) + y1*(x-x0)/(x1-x0)
return y |
def bad_cats(all_cats):
""" Removes any cateogry from list that has one of the following terms """
bad = ['Artworks with known accession number',
'Artworks with accession number from Wikidata',
'Artworks without Wikidata item',
'Artworks with Wikidata item',
'Unsuppor... |
def add_bias_quadratic(v):
"""
Inclui bias + quadratico no vetor de entrada
:param v: vetor de entrada
:return: matriz do vetor de entrada com bias e x^2
"""
v_bias = []
for item in v:
if not isinstance(item, list):
v_bias.append([1, item, item ** 2])
els... |
def parse_relation(fields):
"""
Assumes all relation are binary, argument names are discarded
:param fields: correspond to one Brat line seperated by tab
:return: relation id, relation name, arg1 and arg2
"""
rel, a1, a2 = fields[1].split(" ")
rel_id = fields[0]
return rel_id, rel, a1.sp... |
def _compare_dicts(dict1, dict2):
"""
Compares two dicts
:return: True if both dicts are equal else False
"""
if dict1 == None or dict2 == None:
return False
if type(dict1) is not dict or type(dict2) is not dict:
return False
shared_keys = set(dict2.keys()) & set(dict2.key... |
def is_visible(filename):
"""Determines if the file should be considered to be a non-hidden file."""
return filename[0] != '.' and filename[-1] != '~' |
def get_timestamp(year, month, day, hour, minute):
"""
Formats timestamp from time data.
"""
hour %= 24
minute %= 60
timestamp = 'TIMESTAMP \'{0}-{1}-{2} {3}:{4}:00\''.format(year, month, day, hour, minute)
return timestamp |
def function(x):
"""Evaluate partial information of a quadratic."""
z = x - 34.56789
return 4 * z ** 2 + 23.4, 8 * z |
def _variable_is_a_function(variable):
"""
Checks if a specified variable is a function by checking if it implements
the __call__ method.
This means that the object doesn't have to be a function to pass this
function, just implement __call__
@return: True if the variable is a function
@rty... |
def _remove_duplicates(lists):
"""
Remove duplicates in list
Args:
lists (list): a list which may contain duplicate elements.
Returns:
list: a list which contains only unique elements.
"""
unique_list = []
for element in lists:
if element not in unique_list:
... |
def join_list_mixed(x, sep=', '):
"""
Given a mixed list with str and list element join into a single str
:param x: list to be joined
:param sep: str to be used as separator between elements
:return: str
"""
return sep.join([sep.join(y) if isinstance(y, list) else y for y in x]) |
def check_uniqueness(digits: list) -> bool:
"""
Checks if elements in the lists are different.
>>> check_uniqueness([1, 2, 3])
True
>>> check_uniqueness([2, 4, 4])
False
"""
unique = set(digits)
if len(unique) == len(digits):
return True
return False |
def singleline_diff(line1, line2):
"""
Inputs:
line1 - first single line string
line2 - second single line string
Output:
Returns the index where the first difference between
line1 and line2 occurs.
Returns IDENTICAL if the two lines are the same.
"""
diffidx = -1
... |
def get_polynomial_coefficients(degree=5):
"""
Return a list with coefficient names,
[1 x y x^2 xy y^2 x^3 ...]
"""
names = ["1"]
for exp in range(1, degree + 1): # 0, ..., degree
for x_exp in range(exp, -1, -1):
y_exp = exp - x_exp
if x_exp == 0:
... |
def human2bytes(s):
"""Convert from a human readable string to a size in bytes.
Examples
--------
>>> human2bytes('1 MB')
1048576
>>> human2bytes('1 GB')
1073741824
"""
symbols = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
ix = -1 if s[-2].isdigit() else -2
letter... |
def parse_games_draws(r):
""" Used to parse the amount of games that ended in a draw.
"""
return int(r.get("wedGelijk", 0)) |
def find_sorted_array_median(nums):
"""
:type nums: List[int]
:rtype: float
"""
mid = len(nums) // 2
return nums[mid] if len(nums) % 2 else (nums[mid - 1] + nums[mid]) / 2.0 |
def create_dict(o):
"""Creates a dict from a object/class"""
return dict((key, value) for key, value in o.items()
if not callable(value) and not key.startswith('_')) |
def gene_components(gene_descriptors):
"""Provide possible gene component input data."""
return [
{
"component_type": "gene",
"gene_descriptor": gene_descriptors[1],
}
] |
def o_maximum(listy):
"""
Input: A list of numbers.
Output: The highest number in the list, using max function.
"""
if listy != []:
return (max(listy)) |
def get_wheels_speed(encoderValues, oldEncoderValues, delta_t):
"""Computes speed of the wheels based on encoder readings"""
#Encoder values indicate the angular position of the wheel in radians
wl = (encoderValues[0] - oldEncoderValues[0])/delta_t
wr = (encoderValues[1] - oldEncoderValues[1])/delta_t
... |
def cyclic_linear_lr(
iteration: int,
num_iterations_cycle: int,
initial_lr: float,
final_lr: float,
) -> float:
"""
Linearly cycle learning rate
Args:
iteration: current iteration
num_iterations_cycle: number of iterations per cycle
initial_lr: learning rate to ... |
def get_positive_equivalent(number):
"""
Read the 2's compliment equivalent of this number as positive.
With a 3 bit number, the positive equivalent of -2 is 5. E.g.::
-4 4 100
-3 5 101
-2 6 110
-1 7 111
0 0 000
1 1 001
2 2 010
3 3 011
... |
def task_type(inputs, include_calc_type=True):
"""
Determines the task_type
Args:
inputs (dict): inputs dict with an incar, kpoints, potcar, and poscar dictionaries
include_calc_type (bool): whether to include calculation type
in task_type such as HSE, GGA, SCAN, etc.
"""
... |
def literal(data: str) -> str:
"""Replaces ``\\n``, ``\\r`` and ``\\t`` in a string, with the real literal newline, carraige return, and tab characters."""
return str(data).replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t") |
def fib(x):
"""
assumes x an int >= 0:
returns Fibonacci of x:
"""
if x == 0 or x == 1:
return 1
else:
# return fib(x-1) + fib(x - 2)
return round(1.618*fib(x-1)) |
def round_float_and_check(a, b):
"""Helper for checking if the LAT or LON have changed. This will clamp a float to
a specific number of total digits and then compare them
a: float to compare against
b: float to round after clamping to the total number of digits in 'a'
returns: True if b once ... |
def ui_truncate(str, nchars):
"""Truncate a string to a maximum of nchars characters.
If truncation occurs, end string with three dots.
"""
if len(str) > nchars:
return str[:nchars-4] + " ..."
return str |
def hasFunction(object, methodname):
""" Test if class of ``object`` has a method called ``methodname``. """
method = getattr(object, methodname, None)
return callable(method) |
def pad(lines, delim):
"""
Right Pads text split by their delim.
:param lines:
:param delim:
:return:
"""
"""
Populates text into chunks. If the delim was & then
['12 & 344', '344 & 8', '8 & 88'] would be stored in chunks as
[['12', '344', '8'], ['344', '8', '88']]
"""
chunks = []
for i in range(len(lin... |
def calculate_average_fitness(population):
"""
Returns the average fitness in a population.
"""
fitness_length = len(population)
total_fitness = sum((fitness[1] for fitness in population))
return total_fitness/fitness_length |
def video_from_snippet(resp):
""" Convert a Youtube api snippet response into a dictionary of video info.
Contains: name, image, description, channel_id, video_id
"""
return {
'name': resp['snippet']['title'],
'image': resp['snippet']['thumbnails']['high']['url'],
'descripti... |
def decode_textfield_ncr(content):
"""
Decodes the contents for CIF textfield from Numeric Character Reference.
:param content: a string with contents
:return: decoded string
"""
import re
def match2str(m):
return chr(int(m.group(1)))
return re.sub('&#(\d+);', match2str, conte... |
def _strip_extension(name, ext):
"""
Remove trailing extension from name.
"""
ext_len = len(ext)
if name[-ext_len:] == ext:
name = name[:-ext_len]
return name |
def submit_files():
"""Specifies a list of file paths to include in results when student submits quiz."""
return ['StudentMain.cpp'] |
def pad_sents(sents, pad_token):
""" Pad list of sentences according to the longest sentence in the batch.
The paddings should be at the end of each sentence.
@param sents (list[list[str]]): list of sentences, where each sentence
is represented as a list of words
... |
def handle_result(result):
""" Handles the result string and returns a boolean if possible"""
if result == 'notapplicable':
return -1
if result == 'pass':
return 1
return 0 |
def fapply(f, args):
"""Apply a function to an iterable of arguments
:param f: function
:param args: tuple of arguments for f
:return: value
"""
return f(*args) |
def normalize_list_params(params):
"""
Normalizes parameters that could be provided as strings separated by ','.
>>> normalize_list_params(["f1,f2", "f3"])
["f1", "f2", "f3"]
:param params: Params to normalize.
:type params: list
:return: A list of normalized params.
:rtype list
"... |
def new_item(strict=True):
"""Item builder.
Return a dictionary from the provided template.
Item keys are updated from **args key-value pairs.
----------
Parameters
**args : Key-value pairs.
----------
Return
Return a dictionary with the predefined keys.
"""
... |
def to_bits(status):
"""
Convert the result from *STB? which is an int like string to bits
"""
return f"{int(status):032b}" |
def bits_between(number: int, start: int, end: int):
"""Returns bits between positions start and end from number."""
return number % (1 << end) // (1 << start) |
def part2_phase(signal):
"""Phase signal single time for the 2nd part."""
# Based on reddit
summed = 0
for index in range(len(signal) - 1, -1, -1):
summed += signal[index]
signal[index] = summed % 10
return signal |
def FirstVal( *vals ):
"""Returns the first non-None value"""
for v in vals:
if v is not None: return v
return None |
def index_move(step, session) -> list:
"""
:param step: the step (forward or rewind) that we want to take
:return: cytoscape Graph
"""
_ = session['index'] + step
if _ > len(session['graphs_list']) - 1 or _ < 0:
try:
return session['graphs_list'][session['index']]
exc... |
def normalize_key(key):
"""
Return tuple of (group, key) from key.
"""
if isinstance(key, str):
group, _, key = key.partition(".")
elif isinstance(key, tuple):
group, key = key
else:
raise TypeError(f"invalid key type: {type(key).__class__}")
return group, key or Non... |
def flip(xarr, yarr, *args):
"""Flip the x and y axes
"""
return (yarr, xarr) + args |
def thresholded(dct, threshold):
"""
Return dict ``dct`` without all values less than threshold.
>>> thresholded({'foo': 0.5, 'bar': 0.1}, 0.5)
{'foo': 0.5}
>>> thresholded({'foo': 0.5, 'bar': 0.1, 'baz': 1.0}, 0.6)
{'baz': 1.0}
>>> dct = {'foo': 0.5, 'bar': 0.1, 'baz': 1.0, 'spam': 0.0}
... |
def _ensure_cr(text):
"""Remove trailing whitespace and add carriage return.
Ensures that `text` always ends with a carriage return
"""
return text.rstrip() + '\n' |
def get_strategies(experiment: dict) -> dict:
""" Gets the strategies from an experiments file by augmenting it with the defaults """
strategy_defaults = experiment['strategy_defaults']
strategies = experiment['strategies']
for strategy in strategies:
for default in strategy_defaults:
... |
def check_for_license_texts(declared_licenses):
"""
Check if any license in `declared_licenses` is from a license text or notice.
If so, return True. Otherwise, return False.
"""
for declared_license in declared_licenses:
matched_rule = declared_license.get('matched_rule', {})
if an... |
def process_range(max_process_id, process_number=None):
"""
Creates an iterable for all the process ids, if process number is set
then an iterable containing only that number is returned.
This allows for the loss generation to be ran in different processes
rather than accross multiple cores.
:... |
def has_num(text):
""" Check if the string contains a digit """
return any(str.isdigit(c) for c in text) |
def flatten_tree(root):
""" get a flattened tree of the "paths" of all children of a tree of objects.
used in sidenav
"""
ret = []
if root["path"]: ret.append(root["path"])
for child in root["children"]:
ret = ret + flatten_tree(child)
return ret |
def is_possible_temp(temp: str) -> bool:
"""
Returns True if all characters are digits or 'M' (for minus)
"""
for char in temp:
if not (char.isdigit() or char == 'M'):
return False
return True |
def merge_configs(*configs):
"""Merge configuration dictionnaries following the given hierarchy
Suppose function is called as merge_configs(A, B, C). Then any pair (key, value) in C would
overwrite any previous value from A or B. Same apply for B over A.
If for some pair (key, value), the value is a d... |
def add_two_numbers(x, y): # function header
"""
Takes in two numbers and returns the sum
parameters
x : str
first number
y : str
second number
returns
x+y
"""
z = x + y
return z # function return |
def _replace_signature(raw_header: bytes, signature: bytes) -> bytes:
"""Replace the 'signature' field in a raw header."""
return signature + raw_header[8:] |
def compute_slowdowns(exp_times, baseline_times):
"""
Given arrays of prototype times and baseline times of the same length,
returns an array of slowdowns
"""
return [exp_times[i]/baseline_times[i] for i in range(len(exp_times))] |
def no_show_menu_my_pics(on=0):
"""Remove a Opcao "Minhas Imagens" do Menu Iniciar
DESCRIPTION
Esta restricao remove a opcao "Minhas Imagens" do menu iniciar.
COMPATIBILITY
Windows 2000/Me/XP
MODIFIED VALUES
NoSMMyPictures : dword : 00000000 = Desabilitado;
... |
def valid_client_request_body(initialize_db):
"""
A fixture for creating a valid client model.
Args:
initialize_db (None): initializes the database and drops tables when
test function finishes.
"""
return {'username': 'Leroy Jenkins', 'avatar_url': ''} |
def _flatten_image_info(sim_dict):
"""
Sim dict will have structure
{'g': {'param1': value1}, 'r': {'param1': value2} ...}
This function will change the structure to
{'param1_g': value1, 'param1_r': value2, ...}
:param sim_dict: input sim_dict for ImageGenerator class
:returns out_... |
def get_xaxis_bounds(plotnums):
""" Get longest xaxis bounds for the plot
so that all subplots have the same xaxis.
"""
lower = upper = 0
for x in plotnums:
times = plotnums[x][0]
l, u = times[0], times[-1]
if l < lower:
lower = l
if u > upper:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.