content stringlengths 42 6.51k |
|---|
def wrap(command: bytes):
"""
Wrap the given command into the padding bytes \x02 and \x03
:param command: bytes
:return: padded command: bytes
"""
start = b"\x02"
stop = b"\x03"
return start + command + stop |
def count_tags(data):
"""Count tags from the data.
Parameters
----------
data : iterable
List containing tuples, which consist of a word and a POS tag.
Returns
-------
"""
counts = {}
for _, tag in data:
try:
counts[tag] += 1
except KeyError:
... |
def l2str(items, start=0, end=None):
"""Generates string from (part of) a list.
Args:
items(list): List from which the string is derived (elements need to implement str())
start(int, optional): Inclusive start index for iteration (Default value = 0)
end(int, optional): Exclusive end index for... |
def format_provider(prv_id, name, lastetl, taxrate):
"""
Helper for provider row formatting
"""
data_point = {}
data_point["ID"] = prv_id
data_point["Name"] = name
data_point["LastETL"] = lastetl
data_point["TaxRate"] = taxrate
return data_point |
def es_inicio(i,j):
"""Verifica si el casillero es el de inicio"""
if (i == 7 and j == 7):
return True
else: return False |
def word_after(sentence, word):
"""Return the word following the given word in the sentence string."""
try:
words = sentence.split()
index = words.index(word) + 1
return words[index]
except:
return None |
def ensure_iterable(value, strict=False, cast=list):
"""
Ensures that the provided value is an iterable, either raising a ValueError
(if `strict = True`) or returning the value as the first element in an
iterable (if `strict = False`).
"""
if not hasattr(value, '__iter__') or isinstance(value, t... |
def action_args(pos1, pos2, named1='terry', named2='frank'):
"""Take positional and named arguments."""
print("arg1: {} arg2: {} named1: {} named2: {}".format(
pos1, pos2, named1, named2
))
return True |
def get_bboxes_intersection(roiA, roiB):
"""
Computes the intersection area of two bboxes
:param roiA: the first bbox
:param roiB: the second bbox
:return: the area of the intersection
"""
xInter = min(roiA[3], roiB[3]) - max(roiA[1], roiB[1])
yInter = min(roiA[2], roiB[2]) - max... |
def get_construct_name(words):
"""
Find the construct name, currently works for:
- AsyncFunctionDef
- FunctionDef
- ClassDef
:param words: Tuple of words (no whitespace)
:type words: ```Tuple[str]```
:return: Name of construct if found else None
:rtype: ```Optional[str]```
"""
... |
def sanitize_string(input_string):
"""Removes unwanted characters from a string and returns the result
"""
return input_string.replace('"', '') |
def intersect_chroms(chroms1,chroms2):
"""Return the intersection of two chromosome sets"""
chroms=set(chroms1).intersection(set(chroms2))
chroms=list(chroms)
chroms.sort()
return chroms |
def vertical(hztl):
"""
Transpose of a nx9 list
args:
-hztl - List, on which the Transpose will be applied
returns: Transpose of the list, hztl
"""
i=0
vert = []
while i<9:
j=0
ele = []
while j<len(hztl):
ele.append(hztl[j][i])
j=j+1
... |
def add_white_space_end(string, length):
""" Adds whitespaces to a string until it has the wished length"""
edited_string = str(string)
if len(edited_string) >= length:
return string
else:
while len(edited_string) != length:
edited_string += ' '
return edit... |
def limit_string_length(string, max_len=50):
"""Limit the length of input string.
Args:
string: Input string.
max_len: (int or None) If int, the length limit. If None, no limit.
Returns:
Possibly length-limited string.
"""
if max_len is None or len(string) <= max_len:
return string
else:
... |
def maybe_mod(val: str, base=0):
"""
Takes an argument, which is a string that may start with + or -, and returns the value.
If *val* starts with + or -, it returns *base + val*.
Otherwise, it returns *val*.
"""
base = base or 0
try:
if val.startswith(('+', '-')):
base +... |
def valid_ip(ip):
""" checks to insure we have a valid ip address """
try:
parts = ip.split('.')
return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)
except ValueError:
return False # one of the 'parts' not convertible to integer
except (AttributeError, TypeErro... |
def Dic_by_List_of_Tuple(inlist):
"""
Convert a list of (key,value) tuples to {key:value} dictionary
"""
outdic={}
for key,value in inlist:
outdic[key]=value
return outdic |
def FIRST(expression):
"""
Returns the value that results from applying an expression to the first document in a group of documents that share the same group by key.
Only meaningful when documents are in a defined order.
See https://docs.mongodb.com/manual/reference/operator/aggregation/first/
for m... |
def get_start_idx(current_window_idx, window_size):
"""
assuming the following
1. all idx starts from 0
2. end_idx of previous window == start_idx + 1 of the current window.
"""
return (current_window_idx * window_size) |
def sum_digits(y):
"""Sum all the digits of y.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
>>> a = sum_digits(123) # make sure that you are using return rather than print
>>> a
6
"""
"*** YOUR CODE HERE ***"
... |
def composite_trapezoidal(f, b, a, n):
"""
Calculate the integral from Trapezoidal Rule
Parameters:
f: Function f(x)
a: Initial point
b: End point
n: Number of intervals
Returns:
xi: Integral value
"""
h = (b - a) / n
sum_x = 0
for i in range(0,... |
def producto_escalar(escalar, vector):
"""
>>> producto_escalar(2, [1, 2, 3])
[2, 4, 6]
:param escalar:
:param vector:
:return:
"""
res = []
cont = 0
while cont < len(vector):
res.append(escalar * vector[cont])
cont += 1
return res |
def debugBlob(blob=None):
"""In case you need it."""
try:
print(str(""))
print(str("String:"))
print(str("""\""""))
print(str(blob))
print(str("""\""""))
print(str(""))
print(str("Raw:"))
print(str("""\""""))
print(repr(blob))
print(str("""\""""))
print(str(""))
except Exception:
return False... |
def get_file_name(input_file_name):
"""
Parses apart the pathway from the raw file name, so the file name can be passed
to the rest of the program as a simple variable
: Param input_file_name: Full pathway of file being analyzed
: Return: The file name with pathway removed
"""
... |
def has_date(viz_types):
"""Checks if the datapoint has dates."""
times = False
for item in viz_types:
if item == 'time':
times = True
return times |
def ns(tags):
"""go by the tag name, no namespaces for future/version-proofing
"""
return '/'.join(['*[local-name()="%s"]' % t if t not in ['*', '..', '.'] else t
for t in tags.split('/') if t]) |
def slice_sequence_examples(sequence, num_steps, step_size=1):
""" Slices a sequence into examples of length
num_steps with step size step_size."""
xs = []
for i in range((len(sequence) - num_steps) // step_size + 1):
example = sequence[(i * step_size): (i * step_size) + num_steps]
x... |
def parsed_path(path):
"""
message=hello&author=gua
{
'message': 'hello',
'author': 'gua',
}
"""
index = path.find('?')
if index == -1:
return path, {}
else:
path, query_string = path.split('?', 1)
args = query_string.split('&')
... |
def get_parameter_for_dev_mode(dev_mode_setting):
"""Return parameter for whether the test should be running on dev_mode.
Args:
dev_mode_setting: bool. Whether the test is running on dev_mode.
Returns:
str: A string for the testing mode command line parameter.
"""
return '--params.... |
def extract_vocabulary(D):
"""
D is the list of documents, pairs of the form (cat, [token, ...])
Returns vocabulary V as a map from words to word indices.
"""
vocab = set()
for (cat, tokens) in D:
# naively including every word in the vocabulary!
# This could be trimmed down, or... |
def is_disease_id(str):
""" Returns bool indicating whether or not the passed in string is
a valid disease id.
Args:
str (string)
"""
return len(str) == 8 and str[0] == "C" and str[1:].isdigit() |
def getDeltaMarkup(delta):
"""Returns sign of delta for elapsed tsc or pmc value"""
return '+' if delta > 0 else '' |
def adjust_learning_rate_default(epoch, iteration, dataset_len,
epochs, warmup_epochs):
"""
LR schedule that should yield 76% converged accuracy
with batch size 256"""
factor = epoch // 30
lr = 0.1 ** factor
return lr |
def search(target, sorted_list):
"""
The sorted_list should really be sorted
"""
low_idx = 0
high_idx = len(sorted_list) - 1
while low_idx <= high_idx:
mid_idx = int(low_idx + (high_idx - low_idx) / 2)
if target < sorted_list[mid_idx]:
high_idx = mid_idx - 1
e... |
def _sizeof_fmt(num, suffix='B'):
"""Format a number as human readable, based on 1024 multipliers.
Suited to be used to reformat a size expressed in bytes.
By Fred Cirera, after https://stackoverflow.com/a/1094933/1870254
Args:
num (int): The number to be formatted.
suffix (str... |
def has_no_keywords(example):
"""Check if a python file has none of the keywords for: funcion, class, for loop, while loop."""
keywords = ["def ", "class ", "for ", "while "]
lines = example["content"].splitlines()
for line in lines:
for keyword in keywords:
if keyword in line.lower(... |
def color_html(string, color):
""" Wrap a string in a span with color specified as style. """
return '<span style="color: {}">{}</span>'.format(color, string) |
def dict_to_list(d):
"""Converts an ordered dict into a list."""
# make sure it's a dict, that way dict_to_list can be used as an
# array_hook.
d = dict(d)
try:
return [d[x] for x in range(len(d))]
except KeyError: # pragma: no cover
raise ValueError("dict is not a sequence") |
def machine_function(project_data, prerequisites):
""" Dummy test func. """
return {'version': 'test_v2'} |
def MinMaxScaling(input,min,max,a=-1,b=1):
"""rescales input array from [min,max] -> [a,b]"""
output = a + (input-min)*(b-a)/(max-min)
return output |
def useless_range(rng):
"""
Check if rng is valid and useful range.
Empty range is not significative.
:param rng:
:return: True | False
"""
if not rng:
return True |
def is_bytes(obj):
"""Helper method to see if the object is a bytestring.
>>> is_bytes(b'foo')
True
"""
return type(obj) is bytes |
def mask_address(ip, prefix):
"""
Reduce a 32-bit integer to its first prefix bits
:param ip: 32-bit integer
:param prefix: integer, 0 <= prefix <= 32
:return: integer corresponding to ip where bits [prefix+1..32] are 0
"""
return ip & (0xffffffff << (32 - prefix)) |
def tempConvert(temp, unit):
""" Convert Fahrenheit to Celsius """
if unit == 'F':
celsius = (temp-32) * 5/9
return celsius
else:
return temp |
def validate_string(string, min_len=5):
"""
Validates a string. Returns False if the string
is less than 'min_len' long.
"""
string = string.strip()
if len(string) < min_len:
return False
return True |
def convert(size: tuple, box: list):
"""Takes as input: (width, height) of an image
(xmin, ymin, xmax, ymax) of the bounding box
and returns (x, y, w, h) of the bounding box in yolo format.
"""
dw = 1./size[0]
dh = 1./size[1]
x = (box[2] + box[0])/2.0
y... |
def is_state_valid(missionaries_right, cannibals_right):
"""
Called by generate_child_state so that it does not generate invalid states.
"""
if missionaries_right > 3 or cannibals_right > 3:
return False
if missionaries_right < 0 or cannibals_right < 0:
return False
if missiona... |
def divide(x: float, y: float) -> float:
"""Returns the division of two numbers."""
if y == 0:
raise ValueError("Can not divide by zero!")
return x / y |
def get_uppercase_words(text):
"""Finds individual uppercase words and return in a list"""
s = []
if isinstance(text, list):
text = " ".join(text)
for t in text.split():
if len(t) > 1:
if t.isupper() and not t.isnumeric():
s.append(t)
return s |
def permutations(str):
"""Generates all the permutations of a given
string.
The runtime is O(n*n!) where n is the length of
the string.
Outer loop runs (n-1).
Middle loop runs (n-1)!
Inner loop runs (n).
(n-1) * (n-1)! * (n) = (n-1) * n!
= n*n! - n! = O(n*n!).
Arguments:
... |
def line2items(l_w, midlabel_func=None, dummy_label="N"):
"""Returns items of a line with dummy label, use only for tagging"""
if midlabel_func is None:
midlabel_func = lambda x: x
return [(w, midlabel_func(w), dummy_label) for w in l_w] |
def avg(l):
"""Returns the average of a list of numbers
Parameters
----------
l: sequence
The list of numbers.
Returns
-------
float
The average.
"""
return(sum(l) / float(len(l))) |
def _velocity_to_output(velocity):
"""Approximately maps keyboard velocity in range [1, 120]
to output value in range [0, 255]"""
return (velocity - 1) * 2 + 1 |
def reverse_dict(dictionary):
"""Reverse a dictionary.
Keys become values and vice versa.
Parameters
----------
dictionary : dict
Dictionary to reverse
Returns
-------
dict
Reversed dictionary
Raises
------
TypeError
If there is a value which is un... |
def split_every(length, collection):
"""Splits a collection into slices of the specified length"""
return [
collection[length * i : length * (i + 1)]
for i in range(0, round(len(collection) / length + 1))
if collection[length * i : length * (i + 1)]
] |
def index_generation_with_scene_list(crt_i, max_n, N, scene_list, padding='replicate'):
"""Generate an index list for reading N frames from a sequence of images (with a scene list)
Args:
crt_i (int): current center index
max_n (int): max number of the sequence of images (calculated from 1)
... |
def get_part_name(reference: str) -> str:
"""
Extracts the part name from a passed in SBOL Component reference.
Args:
reference: Input string. Should look something like
<https://synbiohub.programmingbiology.org/user/wrjackso/test/
Design0_Group1_Object2/pTet_Component/1>
Retur... |
def text2bool(text: str) -> bool:
"""Convert input text into boolean, if possible."""
if str(text).lower().startswith(("t", "y", "1", "on", "s")):
return True
elif str(text).lower().startswith(("f", "n", "0", "off")):
return False
raise ValueError("Valor booleano no comprendido '%s'" %... |
def write_positions(positions):
"""parse float tuples of a text string
return string
"""
result = ""
if positions is not None:
for x,y in positions:
result = "%s %s,%s" % (result, x, y)
return result |
def parse_boolean_from_param(param):
"""
Helper to establish True or False
"""
result = False
if param.strip() == "":
result = False
elif param.strip() == "True":
result = True
elif param.strip() == "true":
result = True
elif param.strip() == "False":
re... |
def yandex_operation_is_failed(data: dict) -> bool:
"""
:returns:
Yandex response contains status which
indicates that operation is failed.
"""
return (
("status" in data) and
(data["status"] in (
# Yandex documentation is different in some places
"failure... |
def broken_bond_keys(tra):
""" keys for bonds that are broken in the transformation
"""
_, _, brk_bnd_keys = tra
return brk_bnd_keys |
def skipped_msg(ctx, members):
"""Returns formatted message listing users."""
if not members:
return ''
msg = "Skipped: "
if len(members) == 1:
msg += members[0].name
elif len(members) == 2:
msg += f'{members[0].name} and {members[1].name}'
elif len(members) > 2:
... |
def check_params(params, field_list):
"""
Helper to validate params.
Use this in function definitions if they require specific fields
to be present.
:param params: structure that contains the fields
:type params: ``dict``
:param field_list: list of dict representing the fields
... |
def apply_no_ans_threshold(scores, na_probs, qid_to_has_ans, na_prob_thresh):
"""Applies no answer threshhold"""
new_scores = {}
for qid, s in scores.items():
pred_na = na_probs[qid] > na_prob_thresh
if pred_na:
new_scores[qid] = float(not qid_to_has_ans[qid])
else:
... |
def variable_set_up_computer(num):
"""Returns the computer's choice"""
if num == 1:
return 'The computer chose rock.'
elif num == 2:
return 'The computer chose paper.'
elif num == 3:
return 'The computer chose scissors.' |
def get_swagger_version(obj):
""" get swagger version from loaded json """
if isinstance(obj, dict):
if 'swaggerVersion' in obj:
return obj['swaggerVersion']
elif 'swagger' in obj:
return obj['swagger']
elif 'openapi' in obj:
return obj['openapi']
... |
def _guess_file_format_1(n):
"""
Try to guess the file format for flow-graph files without version tag
"""
try:
has_non_numeric_message_keys = any(not (
connection_n.find('source_key').isdigit() and
connection_n.find('sink_key').isdigit()
) for connection_n in n.f... |
def get_loc_techs(loc_techs, tech=None, loc=None):
"""
Get a list of loc_techs associated with the given technology and/or location.
If multiple of both loc and tech are given, the function will return any
combination of members of loc and tech lists found in loc_techs.
Parameters
----------
... |
def sortedAcronym(field):
"""Find first character of each token, and sort them alphanumerically.
Examples:
.. code:: python
> print(sortedAcronym('Xavier woodward 4K'))
> ('4Xw',)
"""
return (''.join(sorted(each[0] for each in field.split())),) |
def check_mailing_list(sig_info, errors):
"""
Check mailing_list
:param sig_info: content of sig-info.yaml
:param errors: errors count
:return: errors
"""
if 'mailing_list' not in sig_info.keys():
print('ERROR! mailing_list is a required field')
errors += 1
else:
... |
def _detect_encoding(data=None):
"""Return the default system encoding. If data is passed, try
to decode the data with the default system encoding or from a short
list of encoding types to test.
Args:
data - list of lists
Returns:
enc - system encoding
"""
import locale
... |
def getIfromRGB(rgb):
"""
Converts rgb tuple to integer
:param rgb: the rgb tuple n 255 scale
:return: the integer
"""
red = rgb[0]
green = rgb[1]
blue = rgb[2]
RGBint = (red << 16) + (green << 8) + blue
return RGBint |
def n_files_str(count):
"""Return 'N file(s)' with the proper plurality on 'file'."""
return "{} file{}".format(count, "s" if count != 1 else "") |
def theta(x):
"""heaviside function."""
return int(x >= 0) |
def reverseComplement(seq):
""" Returns the reverse complement of a DNA sequence,
retaining the case of each letter"""
complement = ""
for base in seq:
if base == "A": complement += "T"
elif base == "T": complement += "A"
elif base == "G": complement += "C"
elif ba... |
def bool_from_native(value):
"""Convert value to bool."""
if value in ('false', 'f', 'False', '0'):
return False
return bool(value) |
def _is_empty_tuple(x):
"""Check if x is either empty or a tuple of (tuples of) empty things."""
if not isinstance(x, (list, tuple)):
return False
for y in x:
if not _is_empty_tuple(y):
return False
return True |
def indent(block_of_text, indentation):
"""
Helper function to indent a block of text.
Take a block of text, an indentation string and return the indented block.
"""
return "\n".join(map(lambda x: indentation + x, block_of_text.split("\n"))) |
def caesar_cipher_encode(n: int, text: str, p: str) -> str:
"""
Returns a string where the characters in text are shifted right n number
of spaces. The characters in text are only encrypted if they exist in p.
If they don't exist in p, they will remain unchanged.
Ex. str = 'abc12'
n = 3
... |
def _resolve_collections(collections):
"""
Split a list of raw collections into a list of database/collection tuples
:param list[str] collections:
:rtype: list[(str, str|None)]
"""
ret = []
for raw_collection in collections:
attr_chain = raw_collection.split('.', 1)
database... |
def decodeLF(line):
"""takes the line as it comes from the socket and decodes it to
the original binary data contained in a string of bytes"""
return line.replace("\\n", "\n").replace("\\/", "\\") |
def get_installation_id(msg_body):
"""
This is used to identify each bundle install within the porter state store.
"""
return msg_body['id'] |
def palindrome1(x):
"""
Determine if the argument is a palindrome, using a recursive solution.
:param x: An iterable.
:return: True if the argument is a palindrome, False otherwise.
"""
# Arguments of length 0 or 1 are always palindromes.
if len(x) < 2:
return True
# If the fir... |
def str_dict(some_dict):
"""Convert dict of ascii str/unicode to dict of str, if necessary"""
return {str(k): str(v) for k, v in some_dict.items()} |
def get_ids_and_bounds(iterable):
"""Retrieve the identifier and bounds of a number of objects."""
return [
"{0.lower_bound} <= {0.id} <= {0.upper_bound}".format(elem) for elem in iterable
] |
def get_target(name):
"""Transform the targets to binary labels.
"""
if name %2 ==0:
target = 0
else:
target = 1
return target |
def rainfall_parti(ptf, snowm, srz, rzsc, beta):
"""effective precipitation partition"""
# pe: effective precipitation
pe = ptf + snowm
# runoff coefficient
rcoeff = 1 - (1 - srz / (rzsc * (1 + beta))) ** beta
# infiltration
infil = pe * (1 - rcoeff)
# water exceed rzsc
if infil + sr... |
def _parse_req(requires_dist):
"""Parse "Foo (v); python_version == '2.x'" from Requires-Dist
Returns pip-style appropriate for requirements.txt.
"""
if ';' in requires_dist:
name_version, env_mark = requires_dist.split(';', 1)
env_mark = env_mark.strip()
else:
name_version,... |
def get_image_path(path:str) -> str:
"""Takes in the path to an image and returns it in usable format to use in img tags as src attribute
Parameters
----------
path : str
The raw image path from metadata
Returns
-------
str
The string corresponding to the correct path to us... |
def zipwith(Combine, *Lists):
"""
Combine the elements of two lists of equal length into one list.
For each pair X, Y of list elements from the two lists, the element
in the result list will be Combine(X, Y).
zipwith(fun(X, Y) -> {X,Y} end, List1, List2) is equivalent to zip(List1, List2).
Exa... |
def pairFR(L):
"""In : L (list of states)
Out: List of pairs with L[0] paired with each state in L[1:],
with the distinguishability distance initialized to -1.
Helper for generating state_combos.
"""
return list(map(lambda x: ((L[0], x), -1), L[1:])) |
def peak_list_to_dict(peak_list):
"""Create dict of peaks"""
peak_dict = {}
for peak in peak_list:
peak_dict[peak.peak_id] = peak
return peak_dict |
def insert_text(original, new, after):
"""Inserts the new text into the original"""
ret = list()
for line in original.split('\n'):
ret.append(line)
if line == after:
for new_line in new.split('\n'):
ret.append(new_line)
return '\n'.join(ret) |
def add(X, varX, Y, varY):
"""Addition with error propagation"""
Z = X + Y
varZ = varX + varY
return Z, varZ |
def _remove_bad_times(gutime_result):
"""This is a hack to deal with some weird GUTime results. In some cases GUTIME
will create a TIMEX3 tag with duplicate attributes. For example, with input
"at 7:48am (2248 GMT)" you get a TIMEX3 tag spanning "48am" (which is weird in
itself) which looks like:
<... |
def beidou_nav_decode(dwrds: list) -> dict:
"""
Helper function to decode RXM-SFRBX dwrds for BEIDOU navigation data.
:param list dwrds: array of navigation data dwrds
:return: dict of navdata attributes
:rtype: dict
"""
return {"dwrds": dwrds} |
def full_to_type_name(full_resource_name):
"""Creates a type/name format from full resource name.
Args:
full_resource_name (str): the full_resource_name of the resource
Returns:
str: type_name of that resource
"""
return '/'.join(full_resource_name.split('/')[-2:]) |
def EscapeShellArgument(s):
"""
Quotes an argument so that it will be interpreted literally by a POSIX shell.
Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
"""
return "'" + s.replace("'", "'\\''") + "'" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.