content stringlengths 42 6.51k |
|---|
def transform_annotations(annotations):
"""Transform annotations dumbly, asserting it is a sequence of strs."""
assert isinstance(annotations, (list, tuple))
for annotation in annotations:
assert isinstance(annotation, str)
return annotations |
def partition_reguliere(n,k):
"""
Input : n : nombre de sommets
k : nombre de classes
Ouput : vecteur de classes
"""
assert(n%k==0)
resultat=[]
for l in range(k):
for i in range(int(n/k)):
resultat.append(l)
return(resu... |
def reverse_dictionary_dictionary(to_reverse):
"""Exchanges two dictionary layers.
For instance, dic[keyA][key1] will become dic[key1][keyA].
Args:
to_reverse (dict): Dictionary of dictionaries.
Returns:
Reversed dictionary.
"""
first_keys = list(to_reverse.keys())
second_... |
def lstDiff(a, b):
"""Intelligently find signed difference in 2 lsts, b-a
Assuming a clockwise coordinate system that wraps at 24=0
A value ahead clockwise is "larger" for subtraction purposes,
even if it is on the other side of zero.
Parameters:
-----------
a : np.float32, float
... |
def s2b(s):
"""Converts an ASCII string into binary data
Args:
s: A string of ASCII characters
Returns:
A long of binary data
"""
#start a binary long
r=0
#for each character in the string
for c in s:
#left shift the data by 8 bits and add the integer representation of the character
... |
def createRefVal(pool_n=1):
"""Return a 2D list of reference distance and power"""
dist = [100, 200, 400]
power = [2000, 5000]
liste = []
for i in range(pool_n):
for p in power:
for d in dist:
liste.append([p, d])
return liste |
def parseownidentitiesresponse(response):
"""Parse the response to Get OwnIdentities from the WoT plugin.
:returns: [(name, {InsertURI: ..., ...}), ...]
>>> resp = parseownidentitiesresponse({'Replies.Nickname0': 'FAKE', 'Replies.RequestURI0': 'USK@...', 'Replies.InsertURI0': 'USK@...', 'Replies.Identity0... |
def string2perm(string):
"""
Convert string from user input to permutation in one-line notation as list
:param string: Permutation as string
:type string: string
:return: Returns permutation in one-line notation as list
:rtype: list
"""
string = string.replace('<', '').replace('>', '')... |
def isDmzProxySecurityActionValueValid( action, value ):
"""Indicates whether the supplied action/value is valid for secure proxy security."""
if 'routing' == action and ('static' == value or 'dynamic' == value):
return True
if 'jarVerification' == action and ('unsigned' == value or 'dynamic' == val... |
def itk_1km_to_250m ( i_tk_1km ) :
"""
return the 250m grid index along track of a 1km pixel
"""
return 1.5 + 4. * i_tk_1km |
def wizard_active(step, current):
"""
Return the proper classname for the step div in the badge wizard.
The current step needs a 'selected' class while the following step needs a
'next-selected' class to color the tip of the arrow properly.
"""
if current == step:
return 'selected'
... |
def parse_filename(filename):
# time_tag=TIME_INFOLDER_TAG,
# time_fmt=TIME_INFILE_FMT,
# ):
"""Parse Hive and RPi number from filename.
Filename e.g.: raw_hive1_rpi1_190801-000002-utc.jpg
"""
prefix, hive_str, rpi_str, t_str = filename.split("_")
... |
def sift(iterable, predicate):
"""
Sift an iterable into two lists, those which pass the predicate and those who don't.
:param iterable:
:param predicate:
:return: (True-list, False-list)
:rtype: tuple[list, list]
"""
t_list = []
f_list = []
for obj in iterable:
(t_list ... |
def create_class_list(scopes):
""" Create a list of class names to eliminate constructor and destructor
function name checks.
"""
classes = []
for scope in scopes:
if scope.type == 'Class' or scope.type == 'Struct':
classes.append(scope.className)
return classes |
def calc_margin(buying_price, selling_price):
"""Compute gross margin for products"""
selling_price = float(selling_price)
buying_price = float(buying_price)
margin = ((selling_price - buying_price) / buying_price) * 100
return "%.2f" % margin |
def addToStart(text, toAdd, ignoreCase=None):
"""returns text with "toAdd" added at the start if it was not already there
if ignoreCase:
return the start of the string with the case as in "toAdd"
>>> addToStart('a-text', 'a-')
u'a-text'
>>> addToStart('text', 'b-')
u'b-text'
>>> addToStart('... |
def cria_celula(cv):
"""
cria_celula: {-1, 0, 1} >>> celula
- Cria uma celula a partir de um valor numerico que representa o seu estado
"""
if cv not in (-1, 0, 1):
raise ValueError("cria_celula: argumento invalido.")
return {"valor": cv} |
def calc(*_x):
"""Thie function is used to calculate ...."""
_sum = 0
for _temp in _x:
_sum = int(_temp) + _sum
return _sum |
def make_grade_table(name_list, grades_list):
"""
Given a list of name_list (as strings) and a list of grades
for each name, return a dictionary whose keys are
the names and whose associated values are the lists of grades
"""
grade_table = {}
for name, grade in zip(name_list, grades_list):
... |
def IMF_N(m,a=.241367,b=.241367,c=.497056):
"""
returns number of stars with mass m
"""
# a,b,c = (.241367,.241367,.497056)
# a=b=c=1/3.6631098624
if .1 <= m <= .3:
res = c*( m**(-1.2) )
elif .3 < m <= 1.:
res = b*( m**(-1.8) )
elif 1. < m <= 100.:
# res = a*( m*... |
def _camelcase(value):
"""
Helper method to convert module name to class name.
"""
return ''.join(str.capitalize(x) if x else '_' for x in value.split("_")) |
def dicesum(throw):
"""
Returns the sum of all dices in a throw
"""
return sum([int(i) for i in throw]) |
def find_dict_with_keyvalue_in_json(json_dict, key_in_subdict, value_to_find):
"""
Searches a json_dict for the key key_in_subdict that matches value_to_find
:param json_dict: dict
:param key_in_subdict: str - the name of the key in the subdict to find
:param value_to_find: str - the value of the ke... |
def listToNum(list):
"""Converts a bit-list [0, 1, 0, 1] to an int."""
return int(''.join(str(x) for x in list), 2) |
def calc_isotope_frag_mz(mz, charge, cl_containing, label, label_mz_difference):
"""
Adjusts the mass computation for the un-indentified labeled sequence
"""
if cl_containing:
if label == 0:
return mz + label_mz_difference / charge
else:
return mz - label_... |
def count_increasing_quantity(alist):
"""
count the number times a quantity increases only
:param alist: list of numbers or characters which
are float-convertible
:return: int
"""
quantity = [float(value) for value in alist]
count_increments = []
for index, depth in enumerate(quantit... |
def multiply(a, b=1) -> int:
"""Multiplica dos numeros"""
mult = a * b
print(f"Esto se ejecuta dentro de la funcion {mult}")
print(f"a: {a}, b: {b}")
return mult |
def TrimDataset(dataset, seq_length, eval_mode=False,
sentence_pair_data=False, logger=None, allow_cropping=False):
"""Avoid using excessively long training examples."""
if sentence_pair_data:
trimmed_dataset = [
example for example in dataset if len(
example... |
def extractSI(s):
"""Convert a measurement with a range suffix into a suitably scaled value"""
du = s.split()
num = float(du[0])
units = du[1] if len(du) == 2 else ' '
# http://physics.nist.gov/cuu/Units/prefixes.html
factor = {'Y': 1e24,
'Z': 1e21,
'E': 1e... |
def lineToList(line):
"""Converts a tab-delimited line into a list of strings, removing the terminating \n and \r."""
return line.rstrip("\n\r").split("\t") |
def normalizeEOL(text):
"""Return text with line endings replaced by \n."""
#return text.replace('\r\n', '\n').replace('\r', '\n')
return '\n'.join(text.splitlines()) |
def get_feat_names_from_base_feats(feat_names: list, base_feat_names: list):
"""Generate feature names in feat_names that stem from features in base_feats
"""
feats = set()
for base_feat_name in base_feat_names:
for feat_name in feat_names:
if base_feat_name in feat_name:
... |
def _dictionary_builder(dictionary, parameter_name, item_validator):
"""
Builds a dictionary item validated by the given validator from the given one.
Parameters
----------
dictionary : `None`, `dict`, (`set`, `tuple`, `list`) of `tuple[2]`
The value to convert.
parameter_name : `st... |
def var(name):
"""Return a page variable
Variables are a mechanism for adapting lesson pages to the course
or run they're part of.
"""
# Templates that use vars should override this with `vars.get`.
return None |
def flatten_list( x ):
"""
https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python
"""
if x.__class__ == list:
return [a for i in x for a in flatten_list(i)]
else:
return [x] |
def _to_plotly_palette(scl, transparence=None):
"""
converts a rgb color palette in format (0-1,0-1,0-1) to a plotly color palette 'rgb(0-255,0-255,0-255)'
"""
if transparence:
return ['rgb({0},{1},{2},{3})'.format(r*255, g*255, b*255, transparence) for r, g, b in scl]
else:
return [... |
def filter_action_by_name(actions, name):
"""
Filter action list by name and return filtered list
"""
return list(filter(lambda x: x['name'] == name, actions)) |
def _mean(listvalue):
"""
The mean value of the list data.
"""
return sum(listvalue) / len(listvalue) |
def align_matches(matches: list):
"""
takes matches from find_matches and converts it to a dictionary of counts per offset and file name
Args
matches (list[str, int]): list of matches from find_matches
Returns
-------
sample_difference_counter (dict{str{int}}): of the form... |
def get_number_of_flavors(body_response):
"""
Returns the number of images in the list.
:param body_response: Parsed response (Python dic). List of flavors
:return: Length of the list
"""
return len(body_response['flavors']) |
def getRailCoordinates(message, key):
"""Return a list of x, y coordinates of the rail in its zig zag order."""
railCoordinates = []
y = 0
direction = 'DOWN'
for x in range(len(message)):
railCoordinates.append((x, y))
if direction == 'DOWN':
y += 1
if y == ke... |
def cleanup_number(text):
"""
Lefting just valid numbers
"""
return ''.join([i for i in text if i.isdigit()]) |
def process_function(fun_args_tuple):
"""
Accepts a tuple of:
- fun - A function name
- args - A tuple of positional args. By default: ()
- kwargs - A dict of keyword args. By default: {}
Calls the received function with the provided positional
and keyword arguments.
"""
... |
def chars_match (found, word):
"""Checks if the leters found are the start of the word we are looking for"""
index = 0
for i in found:
if (i != word[index]):
return False
index += 1
return True |
def corpus2sentences(corpus):
"""split corpus into a list of sentences.
"""
return corpus.strip().split('\n') |
def get_mm(sl):
"""Gets an alignment line in SAM format and returns the number of mismatches"""
for opt in sl[11:]:
if opt[:3] == 'NM:':
return int(opt[5:])
return -1 |
def check_even_numbers_in_a_list (base_list) -> list:
"""
Checks that all numbers in a list are equal.
Args:
base_list :
(Generated by docly)
"""
return [a for a in base_list if a % 2 == 0] |
def project25dAlt(wx, wy, wz, win_width, win_height, worldScale = 1.0):
""" Project 3d coords into 2d plane (screen)
"""
## I used the idea and the algorythm at:
## http://www.inversereality.org/tutorials/graphics%20programming/3dprojection.html
if wz == 0:
OneOverZ = 0
... |
def get_qname(uri, name):
"""
Returns an expanded QName from URI and local part. If any argument has boolean value
`False` or if the name is already an expanded QName, returns the *name* argument.
:param uri: namespace URI
:param name: local or qualified name
:return: string or the name argumen... |
def map_merge_cubes(process):
"""
"""
# intentionally empty, just for clarity
# the only thing needed for this process is to create a new pickled object from the input ones, already mapped by other functions in map_processes.py
return [] |
def set_output_filename(ifile, ext):
"""
Create output file name from input file name by adding *ext* before
the file suffix.
Parameters
----------
ifile : str
input file name
ext : str
string to add before file suffix
Returns
-------
str
output filename... |
def is_pos_pow_two(x: int) -> bool:
"""
Simple check that an integer is a positive power of two.
:param x: number to check
:return: whether x is a positive power of two
"""
if x <= 0:
return False
while (x & 1) == 0:
x = x >> 1
return x == 1 |
def get_word_count(s):
"""Get word count in string s"""
word_count = {}
for word in s.split(' '):
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
return word_count |
def parent_path(xpath):
"""
Removes the last element in an xpath, effectively yielding the xpath to the parent element
:param xpath: An xpath with at least one '/'
"""
return xpath[:xpath.rfind('/')] |
def lin_transform(u, a, b):
"""Linear tranformation"""
return u * (b - a) + a |
def set_value_by_dot(doc, key, value):
"""Set dictionary value using dotted key"""
result = doc
keys = key.split('.')
for i in keys[:-1]:
if i not in result:
result[i] = {}
result = result[i]
result[keys[-1]] = value
return doc |
def num_to_mod(number):
"""This is the way pyttanko does it. (https://github.com/AznStevy/owo/blob/6d7b63494aa4534d93b32a16f03db8ed1dbbb47a/cogs/osu.py#L3211)
Just as an actual bitwise instead of list.
Deal with it."""
number = int(number)
mod_list = []
if number & 1 << 0:
mod_list.appe... |
def nrsqrt(d, width=32):
"""Non-Restoring Square Root Algorithm
"An FPGA Implementation of a Fixed-Point Square Root Operation", Krerk Piromsopa, 2002
https://www.researchgate.net/publication/2532597_An_FPGA_Implementation_of_a_Fixed-Point_Square_Root_Operation
"""
q = 0
r = 0
for i in reve... |
def render_text(element):
"""Render hiccup-style HTML vector as text."""
if not isinstance(element, list):
raise Exception(f"Element is not a list: {element}")
if len(element) == 0:
raise Exception("Element is an empty list")
tag = element.pop(0)
output = ""
if len(element) > 0:
... |
def extract_result(content):
"""
extracts the result
"""
result = content['result']
return result |
def default_replace(row, target, *pattern_repl):
"""
Replaces the pattern in the target string with a given string. The pattern
can be either a string or regular expression, if a regular expression is
used groups can be used in the replacement string.
:param row: The row being transformed (not used... |
def J2kWh(x):
"""J -> kWh"""
return x/1000./3600. |
def get_mesos_quorum(state):
"""Returns the configured quorum size.
:param state: mesos state dictionary"""
return int(state['flags']['quorum']) |
def regroup(tuples):
"""Tuples is a list of tuples.
(0, lol), (1, truc), (0, bra) --> {0 : [lol, bra], 1 : [truc]}"""
group = dict()
existing = list()
for t in tuples:
if t[0] in existing:
group[t[0]].append(t[1])
else:
existing.append(t[0])
group[... |
def parse_int_string(obj: str) -> int:
"""Parse a string as `int`. Throws a ValueError if `obj` is not a string.
Args:
obj : the string to parse
"""
if not isinstance(obj, str):
raise ValueError()
return int(obj) |
def reversebits3(max_bits, num):
""" Reversal based on string and list slicing operations.
BTW, this is the fastest bit reversal implementation
in this file! I guess Python can efficiently work with
strings, while C/C++ can efficiently work with bits. """
return int(bin(num)[2:].zfill(... |
def _get_ring_marker(used_markers):
"""
Returns the lowest number larger than 0 that is not in `used_markers`.
Parameters
----------
used_markers : Container
The numbers that can't be used.
Returns
-------
int
The lowest number larger than 0 that's not in `used_markers`.
... |
def to_json_type(v):
""""Convert string value to proper JSON type.
"""
if v.lower() in ('true', 'false'):
v = v[0].upper() + v[1:].lower()
try:
return eval(v, {}, {})
except:
raise ValueError("Could not convert to JSON type.") |
def dict_of_gen_relays(relays, gens):
"""
Create dictionaries of the relay keys from the
gen elements
"""
gen_relays = {k: list() for k in gens.keys()}
for relay_name, relay in relays.items():
gen_relay_mappings = relay['gen']
if gen_relay_mappings:
for b in gen_rela... |
def is_pos_square(n: int) -> bool:
"""
Return whether n is a positive perfect square
>>> is_pos_square(5)
False
>>> is_pos_square(9)
True
"""
return 0 < n and (round(n ** 0.5) ** 2 == n) |
def str_wrap_double(s):
""" Adds double quotes around the input string """
s = str(s)
return '"' + s + '"' |
def num2ip(num):
"""Converts local number to ipv4 string"""
ip1 = num&0xFF;
ip2 = (num>>8)&0xFF;
ip3 = (num>>16)&0xFF;
ip4 = (num>>24)&0xFF;
return "%d.%d.%d.%d" % (ip4,ip3,ip2,ip1) |
def rects_merge(rects):
""" Merge a list of rectangle (xywh) tuples.
Returns a list of rectangles that cover the same
surface. This is not necessarily optimal though.
>>> rects_merge([(0,0,1,1),(1,0,1,1)])
[(0, 0, 2, 1)]
"""
def stack(rects, horizontal=False):
... |
def to_path(sql_uri: str) -> str:
"""Allows sqlite:/// style paths or regular file paths."""
if sql_uri.startswith("sqlite:///"):
sql_uri = sql_uri[len("sqlite:///") :]
return sql_uri |
def fizzbuzz(n):
"""
Fizzbuzz game.
For multiples of three print "Fizz" instead of the number
and for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
Parameters:
-----------
n: int
The integer number to test
... |
def validate_password(pw: str):
"""
Check if a password is valid and return a tuple of (bool, reason)
This function does not perform checks for strong passwords.
"""
pw = pw.strip() if pw is not None else ""
if pw == "":
return (False, "Password is blank")
elif len(pw) < 4:
#... |
def _approximate_bias(b, name):
"""
Find a reasonable match for the given name when we have existing biases in gazetteer entry.
Otherwise if the name is just long enough it should be rather unique and return a high bias ~ 0.3-0.5
If a name varies in length by a third, we'll approximate the name bias to... |
def split_stream_name(ui_stream_name):
""" Splits the hypenated reference designator and stream type into a tuple of
(mooring, platform, instrument, stream_type, stream)
"""
mooring, platform, instrument = ui_stream_name.split('-', 2)
instrument, stream_type, stream = instrument.split('_', 2)
st... |
def data(data):
"""
Converts array of 8-bit ints into string of 0s and 1s.
"""
output = ""
for b in data:
output += ("{0:08b}".format(b))[::-1]
return output |
def unpack_maybe(sample):
"""
Loads the supplied sample from disk (or the network) if the audio isn't loaded in to memory already.
"""
if hasattr(sample, 'unpack'):
realized_sample = sample.unpack()
else:
realized_sample = sample
return realized_sample |
def _format_config(file_value, effective_value, name=None, envvar_name=None):
"""
Construct a string to show on a terminal, indicating the value and
possibly other useful things such as the setting name and whether
it is being controlled by an environment variable.
>>> _format_config('x', 'x')
... |
def _get_repo_type(remote_url):
"""
Returns repo type by parsing the remote_url for github.com and visualstudio.com
"""
lower_case_url = remote_url.lower()
if 'github.com' in lower_case_url:
return 'github'
elif 'visualstudio.com' in lower_case_url:
return 'vsts'
return None |
def convert_tide_row(row):
"""
>>> convert_tide_row(["2017-10-27","2017-10-27 12:35:13","T17102713351310619","DECADE CITY ref: DC HBC","","","1000.00","Faster Payment in",None,"DECADE CITY","DC HBC",None,None,"Cleared"])
['27/10/2017', '1000.00', 'DECADE CITY ref: DC HBC']
>>> convert_tide_row([])
T... |
def fixChars(text:str) -> str:
"""Fixes \\xa0 Latin1 (ISO 8859-1), \\x85, and \\r, replacing them with space"""
text = text.replace(u'\xa0', u' ')
text = text.replace(u'\x85', u' ')
text = text.replace(u'\r', u' ')
return text |
def samflags(flag=0, verbose=True):
"""This script converts a decimal flag to binary and get the corresponding properties according to the sam-flag standard.
The code is based on the explanation given here https://davetang.org/muse/2014/03/06/understanding-bam-flags/
For manual checking sam flags, check htt... |
def _convert_hex_str_to_int(val):
"""Convert hexadecimal formatted ids to signed int64"""
if val is None:
return None
hex_num = int(val, 16)
# ensure it fits into 64-bit
if hex_num > 0x7FFFFFFFFFFFFFFF:
hex_num -= 0x10000000000000000
assert -9223372036854775808 <= hex_num <= 9... |
def classify_var(var, state_options, parameter_options, control_options, polynomial_control_options):
"""
Classifies a variable of the given name or path.
This method searches for it as a time variable, state variable,
control variable, or parameter. If it is not found to be one
of those variables... |
def lowercase(text):
"""casefolding menjadi huruf kecil
:return: lower case string
:rtype: string
"""
return text.lower() |
def find_select_idx_name(
central_idx: int, limit_idx: int, close_to_limit: bool
):
"""Returns a two-tuple which contains an int of value 0 or -1 in
the first position and a string of value 'min' or 'max' in the second.
The string is determined based on the relative values of
*central_idx* to *limi... |
def mergedicts(source, destination):
"""This function recursively merges two dictionaries:
`source` into `destination"""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
mergedicts(val... |
def removeDuplicates(bookmarks, newBookmarks):
"""Creates and returns a new list of bookmarks
without any duplicates"""
nodup = []
for bmNew in newBookmarks:
foundDup = False
for bm in bookmarks:
if (bm.linkURL == bmNew.linkURL):
foundDup = True
break
if (not foundDup):
nodup.ap... |
def get_r_list(area1, area2, max_area, tol=0.02):
"""
returns a list of r1 and r2 values that satisfies:
r1/r2 = area2/area1 with the constraints:
r1 <= Area_max/area1 and r2 <= Area_max/area2
r1 and r2 corresponds to the supercell sizes of the 2 interfaces
that align them
"""
r_lis... |
def round_filters(filters: int, width_coefficient, depth_divisor, min_depth) -> int:
"""
Calculate and round number of filters based on depth multiplier.
"""
filters *= width_coefficient
min_depth = min_depth or depth_divisor
new_filters = max(min_depth, int(filters + depth_divisor / 2) // depth... |
def number_of_lottery_tickets(total_sales):
"""
Function to calculate the number of lottery
tickets to assign for each participants based on sales.
Args:
total_sales(int): total sales done by the participant.
"""
total_sales = int(total_sales)
max_ticket_to_assign = 15
sales_t... |
def _module_name_for_display(module):
"""Extract a name for the module."""
if isinstance(module, dict):
return module['path']
try:
return module.path
except Exception: # pylint: disable=broad-except
return str(module) |
def addstr(str1, str2):
"""
Concatenate two strings.
"""
return "{}{}".format(str1, str2) |
def validate(message):
"""
Check if the message is in the correct format.
"""
if not ('x' in message and 'y' in message):
return False
if not(isinstance(message['x'], float)) or not(isinstance(message['y'], float)):
return False
return True |
def validate_fields(*fields):
"""
Checks if any of the provided fields are empty
Returns: True if any of the fields is empty
"""
return not all(fields) |
def calculateProfit(positions):
"""
Calculates the total profit/loss from input positions.
Parameters-
positions: Array of positions.
"""
totalProfit = 0.0
for position in positions:
totalProfit += float(position['pl'])
return totalProfit |
def dict_merge(base, override):
"""Recursively merge two dictionaries
Parameters
----------
base : dict
Base dictionary for merge
override : dict
dictionary to override values from base with
Returns
-------
dict
Merged dictionary of base and overrides
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.