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:
counts[tag] = 1
return counts |
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 iteration (Default value = None)
Returns:
: str - Generated string.
"""
start = max(start, 0)
end = end if end else len(items)
return ' '.join([str(i) for i in items[start:end]]) |
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, type):
if strict:
raise ValueError("Value %s is not an iterable." % value)
return cast([value])
return value |
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(roiA[0], roiB[0])
return max(xInter, 0) * max(yInter, 0) |
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]```
"""
for idx, word in enumerate(words):
if len(words) > idx + 1:
if word == "def":
return words[idx + 1][: words[idx + 1].find("(")]
elif word == "class":
end_idx = (
lambda _end_idx: words[idx + 1].find(":")
if _end_idx == -1
else _end_idx
)(words[idx + 1].find("("))
return words[idx + 1][:end_idx] |
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
vert.append(ele)
i=i+1
return vert |
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 edited_string |
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:
return "..." + string[len(string) - max_len:] |
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 += int(val)
else:
base = int(val)
except (ValueError, TypeError):
return base
return 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, TypeError):
return False |
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 more details
:param expression: expression or variables
:return: Aggregation operator
"""
return {'$first': expression} |
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 ***"
total = 0
while y > 0:
digit = y % 10
total += digit
y = y // 10
return total |
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, n - 1):
x = a + (i + 1) * h
print(x)
sum_x += f(x)
xi = h / 2 * (f(a) + 2 * sum_x + f(b))
return [xi] |
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
return True |
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
"""
input_file_name = input_file_name.split("\\")
input_file_name = input_file_name[-1]
input_file_name = input_file_name.split("/")
file_name = input_file_name[-1]
return (file_name) |
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]
xs.append(example)
return xs |
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('&')
query = {}
for arg in args:
k, v = arg.split('=')
query[k] = v
return path, query |
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.devMode=%s' % dev_mode_setting |
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 we could do some preprocessing, maybe
# ignore rare words.
vocab.update(tokens)
# oooooh, look at this guy, writing a dictionary comprehension.
return {wordtype : i for (i, wordtype) in enumerate(sorted(list(vocab)))} |
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
elif target > sorted_list[mid_idx]:
low_idx = mid_idx + 1
else:
return mid_idx
return -1 |
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): the measure unit to append at the end of the formatted
number.
Returns:
str: The formatted number including multiplier and measure unit.
"""
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix) |
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():
return {"has_no_keywords": False}
return {"has_no_keywords": True} |
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 = (box[3] + box[1])/2.0
w = abs(box[2] - box[0])
h = abs(box[3] - box[1])
x = x*dw
w = w*dw
y = y*dh
h = h*dh
return (x, y, w, h) |
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 missionaries_right != 0 and missionaries_right < cannibals_right:
return False
missionaries_left = 3 - missionaries_right
cannibals_left = 3 - cannibals_right
if missionaries_left != 0 and missionaries_left < cannibals_left:
return False
return True |
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:
str: The string to find the permutations of
Returns:
An array of permutations of the given string.
"""
# Store all the partial permutations
partial_perms = [str]
# For a 4 length string, the partial
# permutations will be of size 1 -> 2 -> 3
for i in range(len(str) - 1):
# Since we shouldn't modify the length of
# partial_perms while iterating over it,
# create a temporary variable to hold the
# next iteration of partial permutations.
temp = []
# Basically, switch the character in
# position i with the character at
# position k, and this will be a new
# permutation. You have to do this for
# all partial permutations (j).
for j in range(len(partial_perms)):
current_perm = partial_perms[j]
for k in range(i, len(current_perm)):
# To swap characters it's easiest
# to turn the string into an
# array and perform a swap that way.
new_perm = list(current_perm)
temp_char = new_perm[k]
new_perm[k] = new_perm[i]
new_perm[i] = temp_char
temp.append(''.join(new_perm))
partial_perms = temp
return partial_perms |
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 unhashable, therefore cannot be a dictionary key.
"""
return {i: value for value, i in dictionary.items()} |
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)
N (int): reading N frames
scene_list (list): scene list indicating the start of each scene, example: [0, 10, 51, 100]
padding (str): padding mode, one of replicate
Example: crt_i = 0, N = 5
replicate: [0, 0, 0, 1, 2]
Returns:
return_l (list [int]): a list of indexes
"""
assert max_n == scene_list[-1]
n_pad = N // 2
return_l = []
num_scene = len(scene_list) - 1
for i in range(num_scene):
if (crt_i >= scene_list[i]) and (crt_i <= scene_list[i + 1] - 1):
for j in range(crt_i - n_pad, crt_i + n_pad + 1):
if j < scene_list[i]:
if padding == 'replicate':
add_idx = scene_list[i]
else:
raise ValueError('Wrong padding mode')
elif j > (scene_list[i + 1] - 1):
if padding == 'replicate':
add_idx = scene_list[i + 1] - 1
else:
raise ValueError('Wrong padding mode')
else:
add_idx = j
return_l.append(add_idx)
return return_l |
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>
Returns:
Base Component Name. With above example, would be 'pTet'
"""
return reference.split("/")[-2].split("_Component")[0] |
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'" % text) |
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":
result = False
elif param.strip() == "false":
result = False
elif param.strip() == "1":
result = True
elif param.strip() == "0":
result = False
else:
return result
return result |
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",
"failed"
))
) |
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:
for member in members[:-1]:
msg += f'{member.name}, '
msg += f'and {members[-1].name}'
return msg |
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
[{'name': str, 'required': True/False', 'type': cls}]
:type field_list: ``list`` of ``dict``
:return True or raises ValueError
:rtype: ``bool`` or `class:ValueError`
"""
for d in field_list:
if not d['name'] in params:
if 'required' in d and d['required'] is True:
raise ValueError(("%s is required and must be of type: %s" %
(d['name'], str(d['type']))))
else:
if not isinstance(params[d['name']], d['type']):
raise ValueError(("%s must be of type: %s. %s (%s) provided." % (
d['name'], str(d['type']), params[d['name']],
type(params[d['name']]))))
if 'values' in d:
if params[d['name']] not in d['values']:
raise ValueError(("%s must be one of: %s" % (
d['name'], ','.join(d['values']))))
if isinstance(params[d['name']], int):
if 'min' in d:
if params[d['name']] < d['min']:
raise ValueError(("%s must be greater than or equal to: %s" % (
d['name'], d['min'])))
if 'max' in d:
if params[d['name']] > d['max']:
raise ValueError("%s must be less than or equal to: %s" % (
d['name'], d['max']))
return True |
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:
new_scores[qid] = s
return new_scores |
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']
return None
else:
# should be an instance of BaseObj
return obj.swaggerVersion if hasattr(obj,
'swaggerVersion') else obj.swagger |
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.find('flow_graph').findall('connection'))
if has_non_numeric_message_keys:
return 1
except:
pass
return 0 |
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
----------
loc_techs : list
set of loc_techs to search for the relevant tech and/or loc
tech : string or list of strings, default None
technology/technologies to search for in the set of location:technology
loc : string or list of strings, default None
location(s) to search for in the set of location:technology
Returns
-------
relevant_loc_techs : list of strings
"""
# If both are strings, there is only one loc:tech possibility to look for
if (
isinstance(tech, str)
and isinstance(loc, str)
and "::".join([loc, tech]) in loc_techs
):
relevant_loc_techs = ["::".join([loc, tech])]
tech = [tech] if tech is not None and isinstance(tech, str) else tech
loc = [loc] if loc is not None and isinstance(loc, str) else loc
if tech and not loc:
relevant_loc_techs = [i for i in loc_techs if i.split("::")[1] in tech]
elif loc and not tech:
relevant_loc_techs = [i for i in loc_techs if i.split("::")[0] in loc]
elif loc and tech:
loc_techs_set = set(tuple(i.split("::")) for i in loc_techs)
possible_loc_techs = set((l, t) for l in loc for t in tech)
relevant_loc_techs = [
"::".join(i) for i in possible_loc_techs.intersection(loc_techs_set)
]
else:
relevant_loc_techs = [None]
return relevant_loc_techs |
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:
print('Check mailing_list: PASS')
return errors |
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
enc_list = ['utf-8', 'latin-1', 'iso8859-1', 'iso8859-2',
'utf-16', 'cp720']
code = locale.getpreferredencoding(False)
if data is None:
return code
if code.lower() not in enc_list:
enc_list.insert(0, code.lower())
for c in enc_list:
try:
for line in data:
line.decode(c)
except (UnicodeDecodeError, UnicodeError, AttributeError):
continue
return c
print("Encoding not detected. Please pass encoding value manually") |
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 base == "C": complement += "G"
elif base == "N": complement += "N"
elif base == "a": complement += "t"
elif base == "t": complement += "a"
elif base == "g": complement += "c"
elif base == "c": complement += "g"
elif base == "n": complement += "n"
elif base == "*": complement += "*"
else:
complement += base
print("Warning: reverse complement function encountered unknown base " + "'" + base + "'")
reverseComplement = complement[::-1]
return reverseComplement |
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
returns - 'def45'
Notes:
Currently p can be string.ascii_lowercase or string.printable characters.
The only whitespace string.printable will use is " ". (one space only,
no newline, tabs, etc.)
str.maketrans returns a translation table that replaces items in p with
items in p[n:] + p[:n], which is just the string p shifted to the right n
units.
my_str.translate(lookup_table) returns a copy of my_str using the lookup
table.
"""
lookup_table = str.maketrans(p, p[n:] + p[:n])
return text.translate(lookup_table) |
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 = attr_chain[0]
if len(attr_chain) == 2:
ret.append((database, attr_chain[1]))
else:
ret.append((database, None))
return ret |
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 first and last elements are not the same, it's not a palindrome.
if x[0] != x[-1]:
return False
# Otherwise, strip the first and last elements and recurse
return palindrome1(x[1:-1]) |
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 + srz > rzsc:
infil = rzsc - srz
# runoff
runoff = pe - infil
return infil, runoff |
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, env_mark = requires_dist, None
if '(' in name_version:
# turn 'name (X)' and 'name (<X.Y)'
# into 'name == X' and 'name < X.Y'
name, version = name_version.split('(', 1)
name = name.strip()
version = version.replace(')', '').strip()
if not any(c in version for c in '=<>'):
version = '==' + version
name_version = name + version
return name_version, env_mark |
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 use in img tags src attributes
Examples
--------
### Passing in an image path from a project in the projects section:
#### JINJA USAGE
```jinja2
{% for project in projects %}
{% if project[0]["image"] %}
<img src="{{ project[0]['image'] | get_image_path }}" alt="{{ project[0]['image'] | get_filename_without_extension }}" />
{% endif %}
{% endfor %}
```
The above jinja is roughly equivalent to something like this in pure python:
```python
project = [{"image": "image.jpg"}, ["other stuff"]]
if project[0]["image"]:
print(get_image_path(project[0]['image'])) # Prints /images/image.jpg which is a usable path
project = [{"image": "https://example.com/img/image.jpg"}, ["other stuff"]]
if project[0]["image"]:
print(get_image_path(project[0]['image'])) # Prints https://example.com/img/image.jpg which is a usable path
```
"""
if path.startswith("http"):
return path
elif path.startswith("images"):
return f"{path}"
else:
return f"images/{path}" |
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).
Example:
>>> from m2py.functional.hof import zipwith
>>>
>>> f = lambda x, y, z: x**2+y**2 - z
>>> zipwith(f, [1, 2, 3], [4, 5, 6], [3, 9, 8])
[14, 20, 37]
Note: Function taken from Erlang -
http://erldocs.com/17.3/stdlib/lists.html#zipwith
"""
return [Combine(*row) for row in zip(*Lists)] |
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:
<TIMEX3 tid="t4" TYPE="TIME" VAL="T48" ERROR="Bad Time" ERROR="Inconsistent">
When the XML parser later reads this it chokes and no timexes are added to
the Tarsqi document."""
filtered_result = []
removed_bad_time = False
remove_closing_timex = False
for line in gutime_result.split("\n"):
if "TIMEX3" in line and "ERROR" in line:
lex_idx = line.find("<lex ")
filtered_result.append(line[lex_idx:])
remove_closing_timex = True
removed_bad_time = True
elif remove_closing_timex and "</TIMEX3>" in line:
filtered_result.append(line[:-9])
remove_closing_timex = False
else:
filtered_result.append(line)
return "\n".join(filtered_result) if removed_bad_time else gutime_result |
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.