content stringlengths 42 6.51k |
|---|
def uint16_gt(a: int, b: int) -> bool:
"""
Return a > b.
"""
half_mod = 0x8000
return (((a < b) and ((b - a) > half_mod)) or
((a > b) and ((a - b) < half_mod))) |
def defuzz_cog(y, output_shape):
"""Defuzzification using the center of gravity
INPUTS
y - the membership value
output_shape - vector defining the output shape"""
# Read in the values of the output triangle
left = output_shape[0]
center = output_shape[1]
right = output_shape[2]
if (... |
def check_user_input(letter_guessed):
"""
letter_guessed: string, letter user have guessed
returns: boolean, True if user's input is in the correct form, otherwise False
"""
if len(letter_guessed) != 1: # check if input length is greater than 1
print('Error. Please type only one letter at a... |
def color_seq(fontcolor=None, bgcolor=None):
"""Return the str-sequence which sets the cursor to the specified colors.
The color can be a number between 0 and 255, a (r, g, b) tuple or a str as
"black", "red", "green", "yellow", "blue", "cyan", or "white"."""
if not (fontcolor is None or isinstance(fontcolo... |
def square_list1(numbers):
"""Returns a list of the squares of the numbers in the input."""
result = []
for n in numbers:
result.append(n ** 2)
return result |
def get_directions(position):
"""Returns all the possible directions of a player in the game as a list.
"""
assert 0 <= position <= 23, "illegal move"
adjacent = [
[1, 3],
[0, 2, 9],
[1, 4],
[0, 5, 11],
[2, 7, 12],
[3, 6],
[5, 7, 14],
[4, 6... |
def get_parent_dirname(label):
"""
Get the name of the parent directory of a label.
Args:
label: The label to get the parent directory of.
Returns:
The name of the parent directory.
"""
if label.startswith("//"):
label = label[2:]
return label.partition("/")[0] |
def map_float(to_float) -> float:
"""Maps value to float from a string.
Parameters
----------
to_float: various (usually str)
Value to be converted to float.
Returns
-------
mapped_float: float
Value mapped to float.
Examples
--------
>>> number_one = "1"
... |
def create_link_html(data_name: str, dataset_id: str, character_limit: int = 15) -> str:
"""Return a html hyperlink (<a>) to the dataset page,
text is shortened to `character_limit` chars."""
short_name = (
data_name
if len(data_name) <= character_limit
else f"{data_name[:character_l... |
def format_year(year):
"""Formats a year to a "yyyy" format if input is less than 100.
Args:
year: user input year
Returns:
A ValueError if the input is not a digit, or the year in yyyy format.
"""
if not(year.isdigit()):
raise ValueError
if(len(year) != 4):
... |
def isdistinct(seq):
""" All values in sequence are distinct
>>> isdistinct([1, 2, 3])
True
>>> isdistinct([1, 2, 1])
False
>>> isdistinct("Hello")
False
>>> isdistinct("World")
True
"""
if iter(seq) is seq:
seen = set()
seen_add = seen.add
for item ... |
def sort_terms_numerically(facets):
"""For terms that are all numerical, sort by numeric value. Only
applies to 'terms' type facets, and facets that contain only numbers
in their buckets."""
for facet in facets:
if facet['type'] == 'terms' and facet.get('buckets'):
try:
... |
def color_in_square(colors, color):
"""Get colors from the given pixel color count"""
# There will be some noise - but it doesn't matter, we're looking for our
# specific colors
return color in colors |
def _insert_type_to_globals(kind: type, globals: dict) -> str:
"""
Inserts the given type into the namespace
"""
name = kind.__name__
globals[name] = kind
return name |
def convert_age_to_year(age, units):
"""
age: string result for the age extracted
unit: string being either years or months (or some variation of those 2)
desc: converts string to float, months to years if unit is month
"""
if age is not None:
age = float(age)
if units is not None:
if 'm' in ... |
def average_precision(ids_for_correct_answers, predicted_answer_id_sequence, k=10):
"""
Adpated from https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py
Computes the average precision at k. This function computes the average prescision at k between two lists of
items... |
def beside_dict(x, y, previous_lst):
"""
:param x: x position in boggle
:param y: y position in boggle
:param previous_lst: to save the alphabet already use
:return: a list of position need to be explore in boggle game
"""
beside_lst = []
for i in range(-1, 2, 1):
for j in range(-1, 2, 1):
if i == 0 and j ... |
def is_direct_transfer(filespair):
# type: (dict) -> bool
"""Determine if src/dst pair for files ingress is a direct compute node
transfer
:param dict filespair: src/dst pair
:rtype: bool
:return: if ingress is direct
"""
return 'storage_account_settings' not in filespair['destination'] |
def is_limit_exceeded(html):
"""Searchs the html for limit exceeded message.
Used to distinguish empty page from temporary wait.
"""
return html.find("You have exceeded the maximum allowed page"
" request rate for this website.") != -1 |
def get_instance_id(finding):
"""
Given a finding, go find and return the corresponding AWS Instance ID
:param finding:
:return:
"""
for kv in finding['attributes']:
if kv['key'] == 'INSTANCE_ID':
return kv['value']
return None |
def get_run_number(header_dict):
""" header_dict parse functions, ORCA specific """
for d in (header_dict["ObjectInfo"]["DataChain"]):
if "Run Control" in d:
return (d["Run Control"]["RunNumber"])
raise ValueError("No run number found in header!") |
def _path_to_string(path):
"""Convert a list of path elements into a single path string."""
return '.'.join(path) |
def is_valid_int(value):
""" Returns value if valid cast to integer, otherwise none """
try:
value = int(value)
except ValueError:
value = None
return value |
def normalize_pitch_content(data, midi_start=60):
"""
Normalizes a list of MIDI tones to a a starting value.
:param list data: a list of MIDI tones.
:param int midi_start: the MIDI starting point to which the data are normalized.
:return: a numpy array of the pitch content, normalized to the starting value.
:rty... |
def parse_secret_from_authentication_url(url):
"""
This helper will parse the secret part of a totp url like
otpauth://totp/alice%07c%40apothekia.de?secret=M3FAFWGD2QA5JJPCPWEOKALPBROHXOL3&algorithm=SHA1&digits=6&period=30
"""
return url.split("secret")[1][1:33] |
def get_num_cols(puzzle: str) -> int:
"""Return the number of columns in puzzle.
puzzle is a game board.
>>> get_num_cols('abcd\nefgh\nijkl\n')
4
"""
return puzzle.index('\n') |
def burst_count(session, Type='Int32', RepCap='', AttrID=1250350, buffsize=0, action=['Get', '']):
"""[Burst Count <int32>]
Sets/Gets the number of waveform cycles that the function generator produces after it receives a trigger.
The Burst Count is used when the operation mode is Operate Burst.
RepCap:... |
def is_requirement(line):
"""
Return True if the requirement line is a package requirement;
that is, it is not blank, a comment, a URL, or an included file.
"""
return not (
line == '' or
line.startswith('-c') or
line.startswith('-r') or
line.startswith('#') or
... |
def get_index_from_filename(
file_name: str
) -> str:
"""
Returns the index of chart from a reproducible JSON filename.
:param file_name: `str`
The name of the file without parent path.
:returns: `str`
The index of the chart (e.g., 1) or an empty string.
"""
assembled_ind... |
def _to_native_string(string, encoding='ascii'):
"""Given a string object, regardless of type, returns a representation of
that string in the native string type, encoding and decoding where
necessary. This assumes ASCII unless told otherwise.
"""
if isinstance(string, str):
out = string
... |
def add_defaults(d, dflts):
"""Adds defaults to every (mapping) value of every item of d"""
dflt_keys = set(dflts)
for k, v in d.items():
d[k].update({dflt_key: dflts[dflt_key] for dflt_key in dflt_keys.difference(v)})
return d |
def get_pairs(word):
""" Return set of symbol pairs in a word.
word is represented as tuple of symbols (symbols being variable-length strings)
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs |
def get_config(app):
"""Conveniently get the security configuration for the specified
application without the annoying 'SECURITY_' prefix.
:param app: The application to inspect
"""
items = app.config.items()
prefix = 'SECURITY_'
def strip_prefix(tup):
return (tup[0].replace('SECUR... |
def retry_if_value_error(exception):
"""
Helper to let retry know whether to re-run
:param exception: Type of exception received
:return: <bool> True if test failed with ValueError
"""
return isinstance(exception, ValueError) |
def get_first_numeric(s):
"""Return the index of the first numeric character in s, -1 if none
exists."""
for i in range(len(s)):
if s[i] in '0123456789':
return i
return -1 |
def selection_sort(collection):
"""
Examples:
implementation of sorting algo using python
>> selection_sort[-1, 5, 10, 0]
[-1,0,5,10]
"""
length = len(collection)
for i in range(length - 1):
small = i
for k in range(i + 1, length):
if collection[k] < collec... |
def is_dict(obj):
"""
Determines whether an object acts like a dict.
Args:
obj (object): The object to test.
Return:
True if the obj acts like a dict, False otherwise.
"""
return hasattr(obj, 'keys') and hasattr(obj, '__getitem__') |
def find_attributes(blockquote):
"""Find attributes in a blockquote if they are defined on a
header that is the first thing in the block quote.
Returns the attributes, a list [id, classes, kvs]
where id = str, classes = list, kvs = list of key, value pairs
"""
if blockquote[0]['t'] == 'Header':... |
def _B(s):
"""Convert str to bytes if needed."""
return s if isinstance(s, bytes) else s.encode() |
def str_ljust(_string):
"""Add padding to string."""
pad = 20
return str(_string.ljust(pad, ".") + ":") |
def get_run_name(_run_name_nr):
"""
:param _run_name_nr: [str], e.g. 'runA-1'
:return: _run_name: [str], e.g. 'runA'
"""
return _run_name_nr.split("-")[0] |
def dist(pos_a, pos_b):
"""
Distance between two points
"""
return int(((pos_a[0] - pos_b[0])**2 + (pos_a[1] - pos_b[1])**2)**0.5) |
def __givapp(c,s,vin):
"""
Applies a sequence of Givens rotations (c,s) recursively to the vector
``vin``
:warning: ``vin`` is altered.
"""
vrot=vin
if isinstance(c,float):
vrot=[c*vrot[0]-s*vrot[1],s*vrot[0]+c*vrot[1]]
else:
for i in range(len(c)):
w1=c[i]*v... |
def trigger_source(session, Type='Int32', RepCap='', AttrID=1150007, buffsize=0, action=['Get', '']):
"""[Trigger Source]
Sets the trigger source to Immediate, External, Video, Video Sync Out, or External Sync Out. Reset value: Immediate.
NOTE: This setting has no effect on the hardware until Measurements.... |
def is_pandigital(n):
"""Returns True if n is a pandigital integer, otherwise False
An m-digit number is pandigital if it makes use of all digits 1 to m
exactly once. Example: 2143 is a 4-digit pandigital number.
Args:
n (int): The number to determine if it's pandigital
... |
def limit_trace(ignore_list, text):
"""Determine if row should be ignored."""
for index in range(len(ignore_list)):
if text.find(ignore_list[index].ident_text) != -1:
return True
return False |
def bcd_to_int(bcd):
"""Converts a 1-byte binary-coded decimal to an integer.
:param bcd: the 1-byte binary-coded decimal as a Python `int`.
:returns: the integer value as a Python `int`.
"""
assert(0 <= bcd and bcd <= 255)
ones = bcd & 0b1111
tens = bcd >> 4
return 10*tens + ones |
def _get_single_gpr(asm_str):
"""returns a single GPR from string and check proper formatting (e.g "x5")"""
if len(asm_str.split()) > 1:
raise SyntaxError('Unexpected separator in reg reference')
if not asm_str.lower().startswith('x'):
raise SyntaxError('Missing \'x\' character at start of r... |
def _rindex(L, val):
"""
Return the index of the last occurence of val in L.
"""
return len(L) - L[::-1].index(val) - 1 |
def adjacency_matrix(edges):
"""
Convert a directed graph to an adjacency matrix.
Note: The distance from a node to itself is 0 and distance from a node to
an unconnected node is defined to be infinite.
Parameters
----------
edges : list of tuples
list of dependencies between n... |
def robustmax(data):
"""Like max() but handles empty Lists."""
if data:
return max(data)
return None |
def make_hash_table(nbuckets):
"""
Takes as input a number, nbuckets, and outputs an
empty hash table with nbuckets empty buckets.
"""
return [[] for i in range(nbuckets)] |
def parse_info_value(value):
"""
:param value:
:return:
"""
try:
if '.' in value:
return float(value)
else:
return int(value)
except ValueError:
if ',' in value or '=' in value:
retval = {}
for row in value.split(','):
... |
def patMatch(seq, pat, notDegPos=None):
""" return true if pat matches seq, both have to be same length
do not match degenerate codes at position notDegPos (0-based)
"""
assert(len(seq)==len(pat))
for x in range(0, len(pat)):
patChar = pat[x]
nuc = seq[x]
assert(patChar in "... |
def strip_suffixes(s, *suffixes):
"""Removes the suffix, if it's there, otherwise returns input string unchanged"""
for suffix in suffixes:
if s.endswith(suffix):
s = s[: len(s) - len(suffix)]
return s |
def int_to_bytes(n: int, byteorder: str = "big") -> bytes:
"""Converts given integer number to bytes object
"""
return n.to_bytes((n.bit_length() + 7) // 8, "big") |
def rotate(nist):
"""Spins a list"""
return nist[1:] + nist[:1] |
def validate_image(in_data):
""" Validates data received from client
Validates the input data to make sure it's formatted as expected.
Args:
in_data (dictionary): the request.json in_Data from the client
Returns:
errorCode (int): server error code
errorStatement (str): error m... |
def main(argv):
"""Main entry point of the program"""
print("This is a boilerplate") ## NOTE: indented using two tabs or 4 species
return 0 |
def largeur_image(lst, largeur_bande):
"""
Calcul la largeur de l'image composee de bandes de largeur
largeur_bande, noires ou blanches definies par lst
"""
return len(lst)*largeur_bande |
def format_user_id(user_id):
"""
Format user id so Slack tags it
Args:
user_id (str): A slack user id
Returns:
str: A user id in a Slack tag
"""
return f"<@{user_id}>" |
def get_procedure_windows(procs, procs_per_window, step_size ):
"""
Parameters:
procedures : an iterable of Syngo objects
procs_per_window : an int
Returns:
a list of lists of Syngo objects, each representing a window and
having len of procs_per_window. each list i... |
def verificar_palavra_entidade_loc(palavra, entidades_loc):
"""
Method that check if the word is entity of location.
Params:
----------
word : String
- Word.
entities_loc : List
- List of location entities recognized by spacy.
Return:
----------
True: If the word is... |
def get_formatted_name(name):
"""
Return a 3-letters acronym in upper case and longer names in PascalCase.
Exemple: 'sql' -> 'SQL'; 'hunting' -> 'Hunting'
"""
if len(name) == 3:
neat_title = f"{name.upper()}"
else:
neat_title = f"{name.capitalize()}"
return neat_title |
def get_index_freq(freqs, fmin, fmax):
"""Get the indices of the freq between fmin and fmax in freqs
"""
f_index_min, f_index_max = -1, 0
for freq in freqs:
if freq <= fmin:
f_index_min += 1
if freq <= fmax:
f_index_max += 1
# Just check if f_index_max is not... |
def your_function(argument: str) -> str:
"""Your function's docstring
Parameters
----------
argument: what your argument is
Returns
-------
Whatever it returns
Raises
------
Any error this function might raise
"""
# sample command so this runs
return 'Hello, ' + ar... |
def resume_group(torrent_client, params):
"""
Resume several torrents
params['info_hashes']: list of str - the list of info-hashes in lowercase
:return:
"""
for info_hash in params['info_hashes']:
torrent_client.resume_torrent(info_hash)
return 'OK' |
def split_fqn(fqn, default_name=None, default_kind=None, default_namespace=None):
"""
Splits a fully qualified name ('namespace:kind/name') into its components.
:return: ns, kind, name . If a component is missing, the associated default argument value will be returned instead.
"""
remainder = fqn
... |
def _filter_repeating_nonalnum(phrase, length):
"""
Check if a given phrase has non repeating alphanumeric chars
of given length.
Example: 'phrase $$$' with length=3 will return False
"""
if len(phrase) > 0:
alnum_len = length
for t in phrase:
if not t.is_alpha:
... |
def to_hex(seq):
"""Pretty prints a byte sequence as hex values."""
return " ".join("{:02x}".format(v) for v in seq) |
def larger_than_prev_count(input_):
"""Takes in input file which is a list of numbers
Returns the number of occurences of a measurement being larger than the previous measurement"""
sum = 0
for i in range(1, len(input_)):
if input_[i] > input_[i-1]:
sum += 1
return sum |
def get_last_modified(model, objects):
"""Get last object update time for Last-Modified header."""
if hasattr(model, 'updated_at') and objects:
last_modified = max(obj.updated_at for obj in objects)
else:
last_modified = None
return last_modified |
def hsla_to_rgba(h, s, l, alpha=1.0): # noqa: E741
"""Converts a color given by its HSLA coordinates (hue, saturation,
lightness, alpha) to RGBA coordinates.
Each of the HSLA coordinates must be in the range [0, 1].
"""
# This is based on the formulae found at:
# http://en.wikipedia.org/wiki/H... |
def plural(text: str, size: int) -> str:
"""Auto corrects text to show plural or singular depending on the size number."""
logic = size == 1
target = (("(s)", ("s", "")), ("(is/are)", ("are", "is")))
for x, y in target:
text = text.replace(x, y[logic])
return text |
def bbox2pointobb(bbox):
"""convert bbox to pointobb
Args:
bbox (list): [xmin, ymin, xmax, ymax]
Returns:
list: [x1, y1, x2, y2, x3, y3, x4, y4]
"""
xmin, ymin, xmax, ymax = bbox
x1, y1 = xmin, ymin
x2, y2 = xmax, ymin
x3, y3 = xmax, ymax
x4, y4 = xmin, ymax
po... |
def separate_sampled_functions(sfs):
"""Given a list of SampledFunctions and scalars (representing a constant
sampled function), collect scalars into a single prefactor. Return the
prefactor and a list of the SampledFunctions."""
true_sfs = []
prefactor = 1.0
for sf in sfs:
if type(sf) ... |
def no_duplicates(route):
"""
This function removes duplicate nodes that may be present in a route, ensuring it can be plotted.
Parameters
----------
route : list
list of nodes traversed by route, in order
Returns
-------
route : list
list of nodes traversed by route, i... |
def parse_chromosome(ident):
"""Parse chromosome identifiers."""
# If ident contains an underscore, work on the
# last part only (e.g., MtrunA17_Chr4g0009691)
undersplit = ident.split("_")
if len(undersplit) > 1:
ident = undersplit[-1].upper()
if ident.startswith("CHR"):
... |
def sum_book_score(book_idx_list, book_score_list):
"""
Helper function to get sum of book scores
Args:
book_idx_list: List of Book Index
, book_score_list: List of Book Scores
Returns:
sum of book scores
"""
return sum(book_score_list[book_idx] for book_idx in book... |
def _merge(a, b):
"""Used by "merge_sort" function to merge two sorted arrays into one sorted array."""
result = []
while len(a) > 0 and len(b) > 0:
if a[0] < b[0]:
result.append(a[0])
del a[0]
else:
result.append(b[0])
del b[0]
return [*... |
def sgi_1973_to_2016(sgi_id: str) -> str:
"""
Convert the slightly different SGI1973 to the SGI2016 id format.
:examples:
>>> sgi_1973_to_2016("B55")
'B55'
>>> sgi_1973_to_2016("B55-19")
'B55-19'
>>> sgi_1973_to_2016("E73-2")
'E73-02'
"""
if "-" n... |
def VtuFilenames(project, firstId, lastId = None, extension = ".vtu"):
"""
Return vtu filenames for a Fluidity simulation, in the supplied range of IDs
"""
if lastId is None:
lastId = firstId
assert(lastId >= firstId)
filenames = []
for id in range(firstId, lastId + 1):
filenames.append(proj... |
def file_parser(list_of_files):
"""
-- DESCRIPTION --
Parse a list of filenames for the file extensions. Return needed file types
as dictionary.
"""
# file types processed by PIAScript
pdb = None
sdf1 = None
sdf2 = None
txt = None
piam = None
# extract file extensions
... |
def to_smash(total_candies):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
>>> to_smash(91)
1
"""
print("Splitting", total_candies, "candy" if total_candies == 1 else "candies")
return total_candies % 3 |
def isDataLine(line):
"""
Used for parsing data file. Returns true if the parameter is a data line,
false otherwise.
Args:
line: string, a line from the data file.
Returns:
True or False
"""
return len(line.split()) == 3 and all(x.isdigit() for x in line.split()) |
def pad_sequences(sequences, max_len, pad_mark=0):
"""
:param sequences:
:param pad_mark:
:return:
"""
max_len = max(map(lambda x : len(x), sequences))
seq_list, seq_len_list = [], []
for seq in sequences:
seq = list(seq)
seq_ = seq[:max_len] + [pad_mark] * max(max_len -... |
def increment_version_within_minor_version(version):
"""Increments an androidx SemVer version without bumping the minor version.
Args:
version: the version to be incremented.
Returns:
The incremented version.
"""
if "alpha" in version or "beta" in version or "rc0" in version:
... |
def ConvertTrieToFlatPaths(trie, prefix=None):
"""Flattens the trie of paths, prepending a prefix to each."""
result = {}
for name, data in trie.items():
if prefix:
name = prefix + '/' + name
if len(data) != 0 and not 'results' in data:
result.update(ConvertTrieToFlatPaths(data, name))
el... |
def stem_string(s, lower=True):
"""
Return a string that with spaces at the begining or end removed and all casted to lower cases
:param s: input string
:param lower: if True, the string will be casted to lower cases
:return: stemmed string
"""
if lower:
return s.strip().lower()
... |
def parse_cigar(cigar):
"""
parse cigar string into list of operations
e.g.: 28M1I29M2I6M1I46M ->
[['28', 'M'], ['1', 'I'], ['29', 'M'], ['2', 'I'], ['6', 'M'], ['1', 'I'], ['46', 'M']]
"""
cigar = cigar.replace('M', 'M ').replace('I', 'I ').replace('D', 'D ').split()
cigar = [c.replac... |
def split_number(n: int, parts: int):
"""
Returns a list of integers of length `parts` that sum to `n`
where the positive difference of any two elements does not exceed 1.
"""
return [n // parts + (1 if i < n % parts else 0) for i in range(parts)] |
def from_dero(value_in_dero):
"""Convert number in dero to smallest unit"""
return int(value_in_dero*10**12) |
def collect_id_as_array(event):
"""Collects the trace_id from the event.
Args:
event (json): Json representing an event of a trace.
Returns:
The trace_id of the event.
"""
return [event.get('trace_id')] |
def one_of_k_encoding(x, allowable_set):
"""tbd."""
if x not in allowable_set:
raise Exception("input {0} not in allowable set{1}:".format(x, allowable_set))
return list(map(lambda s: x == s, allowable_set)) |
def chr_length(chr_id):
""" Return the chromosome length for a given chromosome, based on the reference genome hg38."""
#The data of chromosome length was taken from https://www.ncbi.nlm.nih.gov/grc/human/data?asm=GRCh38
length_dict = {'chr1': 248956422, 'chr2': 242193529, 'chr3': 198295559, 'chr4': 190214... |
def __or(funcs, args):
""" Support list sugar for "or" of two predicates. Used inside `select`. """
results = []
for f in funcs:
result = f(args)
if result:
results.extend(result)
return results |
def vmp(t):
"""return propellant burn rate as function of time"""
if t <= 5.:
return 20.
else:
return 0. |
def _trim_batch(batch, length):
"""Trim the mini-batch `batch` to the size `length`.
`batch` can be:
- a NumPy array, in which case it's first axis will be trimmed to size
`length`
- a tuple, in which case `_trim_batch` applied recursively to
each element and the resulting tuple returned
... |
def get_charset_from_content_type(content_type):
""" extract charset encoding type from Content-Type
@param content_type
e.g.
application/json; charset=UTF-8
application/x-www-form-urlencoded; charset=UTF-8
@return: charset encoding type
UTF-8
"""
content_type = conte... |
def letter_grades(highest):
"""
:param highest: integer of highest exam score.
:return: list of integer lower threshold scores for each D-A letter grade interval.
For example, where the highest score is 100, and failing is <= 40,
The result would be [41, 56, 71, 86]:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.