content stringlengths 42 6.51k |
|---|
def ApplicationError(e):
"""Return a custom 500 error."""
return 'Sorry, unexpected error: {}'.format(e), 499 |
def _conv_size(width, size, stride, padding):
"""Compute the output size of a convolutional layer."""
if padding.lower() == 'valid':
return 1 + (width - size) // stride
elif padding.lower() == 'same':
return 1 + (width - 1) // stride
else:
raise ValueError('Unknown padding type: %s' % padding) |
def get_last_syllable(token_list):
"""
Gets last syllable from a word in a dictionary
:param token_list: list of dictionary tokens
:return: Last syllable
"""
if len(token_list) > 0:
for token in token_list[::-1]:
if 'word' in token:
return token['word'][-1] |
def hook_newHeadline(VO, level, blnum, tlnum):
"""Return (tree_head, bodyLines).
tree_head is new headline string in Tree buffer (text after |).
bodyLines is list of lines to insert in Body buffer.
"""
tree_head = 'NewHeadline'
bodyLines = ['%s %s %s' %('='*level, tree_head, '='*level), '']
return (tree_head, bodyLines) |
def build_tos(
precedence: int, lowdelay: bool, throughput: bool, reliability: bool, lowcost: bool
) -> int:
"""Building IP Type of Service value
Args:
precedence (int): intended to denote the importance or priority of the datagram
0b1000 -- minimize delay
0b0100 -- maximize throughput
0b0010 -- maximize reliability
0b0001 -- minimize monetary cost
0b0000 -- normal service
lowdelay (bool): low (True), normal (False)
throughput (bool): high (True) or low (False)
reliability (bool): high (True) or normal (False)
lowcost (bool): minimize memory cost (True)
Returns:
int: type of service as describe in the RFC 1349 and 791
"""
return (
(lowcost << 1)
+ (reliability << 2)
+ (throughput << 3)
+ (lowdelay << 4)
+ (max(min(precedence, 0b111), 0b000) << 5)
) |
def format_index(index):
"""Load stem or raw index. Reformat if in string form.
Parameters
----------
index : int or str
Index in string or integer form.
E.g. any of 1 or 'S01' or 'R01'
Returns
-------
formatted_index : int
Index in integer form
"""
if isinstance(index, str):
return int(index.strip('S').strip('R'))
elif index is None:
return None
else:
return int(index) |
def rabbits(n, k):
"""
>>> rabbits(5, 3)
19
"""
prev, nxt = 1, 1
for _ in range(2, n):
prev, nxt = nxt, prev * k + nxt
return nxt |
def to_month(n):
"""Returns a string with the name of the month, given its number."""
months = ["January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December"]
return months[n - 1] |
def increment(input):
"""
>>> increment("a")
'b'
>>> increment("abc")
'abd'
>>> increment("asd")
'ase'
>>> increment("zzz")
'aaaa'
"""
result = ""
carry = False
for i in range(len(input)-1, -1, -1):
if input[i] == "z":
result = "a" + result
carry = True
else:
result = input[:i] + chr(ord(input[i]) + 1) + result
carry = False
break
if carry:
return "a" + result
else:
return result |
def is_3x3_digit_product(num):
"""Verify that number is product of two 3 digits numbers."""
for j in range(100, 999 + 1):
if num % j == 0 and 100 <= num // j <= 999:
return True
return False |
def lengthOfLastWord(s: str):
"""Determines the character length of the last word in the string
Args:
s (str): String being analyzed
Returns:
int: length of last word in string
"""
length = 0
hit = False
i = len(s) - 1
while i >= 0:
if s[i] == " " and hit == True:
return length
elif s[i] != " ":
hit = True
length += 1
i -= 1
return length |
def get_test_ids_from_param_values(param_names,
param_values,
):
"""
Replicates pytest behaviour to generate the ids when there are several parameters in a single `parametrize`
:param param_names:
:param param_values:
:return: a list of param ids
"""
nb_params = len(param_names)
if nb_params == 0:
raise ValueError("empty list provided")
elif nb_params == 1:
paramids = list(str(v) for v in param_values)
else:
paramids = []
for vv in param_values:
if len(vv) != nb_params:
raise ValueError("Inconsistent lenghts for parameter names and values: '%s' and '%s'"
"" % (param_names, vv))
paramids.append('-'.join([str(v) for v in vv]))
return paramids |
def handle_prices(data: dict) -> dict:
"""Set price according to rate."""
for reservation in data['Reservation']:
if reservation['Tarif'] == "Plein tarif":
price = 10.00
elif reservation['Tarif'] == "Tarif reduit":
price = 8.00
elif reservation['Tarif'] == "Senior":
price = 7.00
elif reservation['Tarif'] == "Tarif etudiant":
price = 7.00
else:
price = None
reservation['prix'] = price
return data |
def example_function(param1, param2=None, *args, **kwargs):
# pylint: disable=keyword-arg-before-vararg,unused-argument
"""Show an example of a module level function.
Function parameters should be documented in the ``Args`` section. The name
of each parameter is required. The type and description of each parameter
is optional, but should be included if not obvious.
If ``*args`` or ``**kwargs`` are accepted,
they should be listed as ``*args`` and ``**kwargs``.
The format for a parameter is::
name (type): description
The description may span multiple lines. Following
lines should be indented. The "(type)" is optional.
Multiple paragraphs are supported in parameter
descriptions.
Args:
param1 (int): The first parameter.
param2 (str): The second parameter. Defaults to None.
Second line of description should be indented.
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
Returns:
bool: True if successful, False otherwise.
The return type is optional and may be specified at the beginning of
the ``Returns`` section followed by a colon.
The ``Returns`` section may span multiple lines and paragraphs.
Following lines should be indented to match the first line.
The ``Returns`` section supports any reStructuredText formatting,
including literal blocks::
{
'param1': param1,
'param2': param2
}
Raises:
AttributeError: The ``Raises`` section is a list of all exceptions
that are relevant to the interface.
ValueError: If `param2` is equal to `param1`.
Example:
``Examples`` should be written in doctest format, and should
illustrate how to use the function.
>>> print([i for i in range(4)])
[0, 1, 2, 3]
Examples:
You can also use literal blocks::
print([i for i in range(4)])
>>> [0, 1, 2, 3]
Todo:
* The ``Todo`` section lists in an orange block every task that needs to be done.
* Make sure to use an * (asterisk) to display bullet points
"""
if param1 == param2:
raise ValueError("param1 may not be equal to param2")
return True |
def top_answers(answers, top=5):
"""Top answers by score"""
return sorted(answers, key=lambda x: x["score"], reverse=True)[:top] |
def _host_absolute(name):
"""
Ensure that hostname is absolute.
Prevents us from making relative DNS records by mistake.
"""
if not name.endswith("."):
name = name + "."
return name |
def vector_subtract(v, w):
"""subtracts two vectors componentwise"""
return [v_i - w_i for v_i, w_i in zip(v, w)] |
def is_even_for_rounding(c, exp):
"""General-purpose tiebreak used when rounding to even.
If the significand is less than two bits,
decide evenness based on the representation of the exponent.
"""
if c.bit_length() > 1:
return c & 1 == 0
else:
return exp & 1 == 0 |
def b64pad(data):
"""
Pad base64 data with '=' so that it's length is a multiple of 4.
"""
missing = len(data) % 4
if missing:
data += b'=' * (4 - missing)
return data |
def n_fib(n):
"""
Find the nth Fibonacci Number.
:param n: Nth element in the fibonacci series.
:return: returns None if n is 0 otherwise returns the nth Fibonacci Number.
"""
if n == 0:
return None
if n == 1 or n == 2:
return n - 1
a, b = 0, 1
for i in range(2, n):
a, b = b, a+b
return b |
def is_cn_char(ch):
""" Test if a char is a Chinese character. """
return ch >= u'\u4e00' and ch <= u'\u9fa5' |
def find_location(filas, element_to_find):
"""Encuentra la ubicacion de una pieza en el rompecabezas.
DEvuelve una tupla: fila, columna"""
for ir, row in enumerate(filas):
for ic, element in enumerate(row):
if element == element_to_find:
return ir, ic |
def improved_i_sqrt(n):
""" taken from
http://stackoverflow.com/questions/15390807/integer-square-root-in-python
Thanks, mathmandan """
assert n >= 0
if n == 0:
return 0
i = n.bit_length() >> 1 # i = floor( (1 + floor(log_2(n))) / 2 )
m = 1 << i # m = 2^i
#
# Fact: (2^(i + 1))^2 > n, so m has at least as many bits
# as the floor of the square root of n.
#
# Proof: (2^(i+1))^2 = 2^(2i + 2) >= 2^(floor(log_2(n)) + 2)
# >= 2^(ceil(log_2(n) + 1) >= 2^(log_2(n) + 1) > 2^(log_2(n)) = n. QED.
#
while (m << i) > n: # (m<<i) = m*(2^i) = m*m
m >>= 1
i -= 1
d = n - (m << i) # d = n-m^2
for k in range(i-1, -1, -1):
j = 1 << k
new_diff = d - (((m<<1) | j) << k) # n-(m+2^k)^2 = n-m^2-2*m*2^k-2^(2k)
if new_diff >= 0:
d = new_diff
m |= j
return m |
def full_request_url(base, text, wildcards={}):
"""
Build a full request URL from the API URL and endpoint.
Any URL parameters will be replaced with the value set in the environment variables.
"""
for key in wildcards.keys():
text = text.replace(key, str(wildcards[key]))
return str(base) + str(text) |
def inx2coordinate(inx, row=8, col=16):
"""Convert inx of bbox into coordinate of solar cell (x_col, y_row).
Coordinate of solar cell on solar module looks like:
[[(0,0), (1,0), (2,0)]
[(0,1), (1,1), (2,1)]]
Parameters
----------
inx: int
Index of the bbox
row, col: int
number of rows and columns of solar module
Returns
-------
coordinate_cell: int
(x_col, y_row) of the bbox
"""
return inx % col, inx // col |
def preserve_cover_metadata(data, prev_record=None):
"""Preserve cover metadata if they existed."""
if "cover_metadata" not in data and prev_record:
data["cover_metadata"] = prev_record.get("cover_metadata", {})
return data |
def FIT(individual):
"""Sphere test objective function.
F(x) = sum_{i=1}^d xi^2
d=1,2,3,...
Range: [-100,100]
Minima: 0
"""
y=sum(x**2 for x in individual)
return y |
def ToCamel(identifier, lower_initial=False, dilimiter='_'):
"""Splits |identifier| using |dilimiter|, makes the first character of each
word uppercased (but makes the first character of the first word lowercased
if |lower_initial| is set to True), and joins the words. Please note that for
each word, all the characters except the first one are untouched.
"""
result = ''.join(word[0].upper() + word[1:]
for word in identifier.split(dilimiter) if word)
if lower_initial and result:
result = result[0].lower() + result[1:]
return result |
def check_if_vertically_overlapped(box_a, box_b):
"""
Return if box_b is intersected vertically with coord_a boxes.
:param box_a:
:param box_b:
:return: true if intersected, false instead
"""
return \
box_a['y_min'] < box_b['y_min'] < box_a['y_max'] or \
box_a['y_min'] < box_b['y_max'] < box_a['y_max'] or \
(box_a['y_min'] >= box_b['y_min'] and box_a['y_max'] <= box_b['y_max']) or \
(box_a['y_min'] <= box_b['y_min'] and box_a['y_max'] >= box_b['y_max']) |
def to_bool(value, keep_null=False):
"""
convert the value passed to boolean if it meets criteria otherwise return what was passed
NOTE: if None is passed (null) then we want to keep it since the db can support it
"""
if value is not None:
# note: need this line because strings and numbers are truthy and will return true
if isinstance(value, str):
if value.lower() in ["0", "n", "f", "false", "no"]:
return False
if value in [0, False]:
return False
if value:
return True
return False
else:
if keep_null:
return None
return False |
def _resolve_frameworks(lookup_dict, data):
"""
Resolves any framework related includes
"""
if "frameworks" in lookup_dict:
# cool, we got some frameworks in our lookup section
# add them to the main data
fw = lookup_dict["frameworks"]
if "frameworks" not in data:
data["frameworks"] = {}
if data["frameworks"] is None:
data["frameworks"] = {}
data["frameworks"].update(fw)
return data |
def flatten(l, ltypes=(list, tuple)):
""" Flattens nested lists l to yield a 1-d list"""
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return ltype(l) |
def parse_requirements(filename):
"""Load requirements from a pip requirements file"""
try:
lineiter = (line.strip() for line in open(filename))
return [line for line in lineiter if line and not line.startswith("#")]
except IOError:
return [] |
def create_flanking_regions_fasta(genome, dataframe, flanking_region_size):
"""
Makes batch processing possible, pulls down small
region of genome for which to design primers around.
This is based on the chromosome and position of input file.
Each Fasta record will contain:
>Sample_Gene_chr:pos__
Seq of flanking region
Args:
genome (list): genome list of tuples (header, seq).
dataframe (pandas object): dataframe with sample info.
flanking_region_size (int): length of sequence upstream and downstream of
input coordindate position to pull as sequence to design primers around.
Returns:
output (list): list of tuples with (header, seq) where seq is flanking region
and header is sample ID.
"""
output = []
for headers, seqs in genome:
chrm = str(headers)
seq = str(seqs)
for gene, sample, chrom, pos in zip(dataframe.Gene, dataframe.Sample,
dataframe.Chr, dataframe.Pos):
if str(chrom) == chrm:
header = str(str(sample)+"_"+str(gene)+"_"+str(chrom)+":"+str(pos)+"__")
flank_seq = seq[int(pos)-int(flanking_region_size):\
int(pos)+int(flanking_region_size)]
output.append((header, flank_seq.upper()))
return output |
def _env_to_list(val):
"""Take a comma separated string and split it."""
if isinstance(val, str):
val = map(lambda x: x.strip(), val.split(","))
return val |
def add_suffix_before_extension(file_name_with_extension, prefix):
""" Adds provided suffix before extension to file name """
file_name, extension = file_name_with_extension.split('.')
return "%s_%s.%s" % (file_name, prefix, extension) |
def transpose(matrix):
"""Matrix transpose
Args:
matrix: list of list
Returns:
list: list of list
"""
return list(map(list, zip(*matrix))) |
def score(score1, score2):
"""combines the scores for the two cross-validation sets
into a single score"""
return score1*score1 + score2*score2 |
def get_worker_info(_):
"""Mock replacement of :meth:`aiida.engine.daemon.client.DaemonClient.get_worker_info`."""
return {
'status': 'ok',
'time': 1576585659.221961,
'name': 'aiida-production',
'info': {
'4990': {
'cpu': 0.0,
'mem': 0.231,
'pid': 4990,
'create_time': 1576585658.730482,
}
},
'id': '4e1d768a522a44b59f85039806f9af14'
} |
def del_stop(x, stop):
"""
>>> l = [1,2,3,4]
>>> del_stop(l, 2)
[3, 4]
>>> l = [1,2,3,4,5,6,7]
>>> del_stop(l, -20)
[1, 2, 3, 4, 5, 6, 7]
>>> del_stop(l, -8)
[1, 2, 3, 4, 5, 6, 7]
>>> del_stop(l, -4)
[4, 5, 6, 7]
>>> del_stop(l, -2)
[6, 7]
>>> l
[6, 7]
>>> del_stop(l, -2)
[6, 7]
>>> del_stop(l, 2)
[]
>>> del_stop(l, -2)
[]
>>> del_stop(l, 20)
[]
>>> del_stop([1,2,3,4], -20)
[1, 2, 3, 4]
>>> del_stop([1,2,3,4], 0)
[1, 2, 3, 4]
"""
del x[:stop]
return x |
def operator_check(operator_name):
"""
check operator name
"""
block_list = ["tuple_getitem", "make_tuple", "Depend", "GetNext"]
return operator_name in block_list |
def to_str(string):
"""Dummy string retriever."""
if string is None:
return ''
return str(string) |
def get_max_value(carrot_types, capacity):
"""
Use dynamic programing (bottom up) to find optimal problem solution
by building up from minimum capacity and reusing already calculated
values found along the way to the top (given capacity)
"""
processed_capacities = [0] * (capacity + 1)
for current_capacity in range(capacity+1):
for carr in carrot_types:
kg, price = carr.values()
if(kg <= current_capacity):
# if the fruit fits into the bag, we will have two
# options, let's pick the one with higher value.
processed_capacities[current_capacity] = max(
processed_capacities[current_capacity],
processed_capacities[current_capacity - kg] + price
)
return round(processed_capacities[capacity]) |
def get_metadata_store_table_name(friendly_table_name, table_names_array):
"""Returns the actual metadata store name for the friendly name
Keyword arguments:
friendly_table_name -- the friendly table name used in the feature files, i.e. main, audit or equalities
table_names_array -- the table names array from the context
"""
for table_name_details in table_names_array:
if table_name_details[0].lower() == friendly_table_name.lower():
return table_name_details[1].lower()
friendly_table_names_allowed = [
table_name_details[0].lower() for table_name_details in table_names_array
]
raise AssertionError(
f"'{friendly_table_name}' is not a valid friendly name for any metadata store table, the allowed values are '{friendly_table_names_allowed}'"
) |
def get_AZN(nco_id):
"""Returns mass number :math:`A`, charge :math:`Z` and neutron
number :math:`N` of ``nco_id``.
Args:
nco_id (int): corsika id of nucleus/mass group
Returns:
(int,int,int): (Z,A) tuple
"""
Z, A = 1, 1
if nco_id >= 100:
Z = nco_id % 100
A = (nco_id - Z) // 100
else:
Z, A = 0, 0
return A, Z, A - Z |
def reverse_lookup(data):
"""Construct an index reverse lookup map from an iterable."""
return {
datum: i for i, datum in enumerate(data)
} |
def _splitPrefix(name):
""" Internal method for splitting a prefixed Element name into its
respective parts """
ntok = name.split(":", 1)
if len(ntok) == 2:
return ntok
else:
return (None, ntok[0]) |
def parse_shutitfile_args(args_str):
"""Parse shutitfile args (eg in the line 'RUN some args', the passed-in args_str would be 'some args').
If the string is bounded by square brackets, then it's treated in the form: ['arg1','arg2'], and the returned list looks the same.
If the string composed entirely of name-value pairs (eg RUN a=b c=d) then it's returned as a dict (eg {'a':'b','c':'d'}).
If what's passed-in is of the form: "COMMAND ['a=b','c=d']" then a dict is also returned.'
Also eg: ["asd and space=value","asd 2=asdgasdg"]"""
ret = []
if args_str == '':
return ret
if args_str[0] == '[' and args_str[-1] == ']':
ret = eval(args_str)
assert isinstance(ret, list)
else:
ret = args_str.split()
# if all the items have a = in them, then return a dict of nv pairs
nv_pairs = True
for item in ret:
if item.find('=') < 0:
nv_pairs = False
if nv_pairs:
d = {}
for item in ret:
item_nv = item.split('=')
d.update({item_nv[0]:item_nv[1]})
ret = d
return ret |
def object_full_name(obj: object):
"""Get a full qualified name of the object.
This function will returned the full name, including the module name (class name or builtin)
where the object is declared, and the object defined name. Each identical object will have
different full name.
From https://stackoverflow.com/a/2020083
Args:
obj (object): The object.
Returns:
str: The object's full qualified name.
"""
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__ # Avoid reporting __builtin__
else:
return module + '.' + obj.__class__.__name__ |
def ovn_metadata_name(id_):
"""Return the OVN metadata name based on an id."""
return 'metadata-%s' % id_ |
def list_count(liste):
"""
count the occurrences of all items in a list and return a dictionary
that is of the form {nb_occurence:list_item}, which is the opposite of
standard implementation usually found on the web
-----------------------------------------------------------------
in python >= 2.7, collections may be used, see example below
>> from collections import Counter
>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
:param liste:
:return:
"""
return dict((liste.count(it), it) for it in liste) |
def form_get_request_to_list_playlists_of_channel(channel_id, api_key, page_token='', max_results='50'):
"""
Form get request to list all playlist of a certain channel.
"""
get_request = 'https://www.googleapis.com/youtube/v3/playlists/?maxResults={}&channelId={}&part=snippet%2CcontentDetails&key={}'.format(
max_results, channel_id, api_key)
if page_token:
get_request += '&pageToken={}'.format(page_token)
return get_request |
def amel2hz(mel):
"""Convert a value in Mels to Hertz
:param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise.
:returns: a value in Hertz. If an array was passed in, an identical sized array is returned.
"""
return 8000 - 700 * (10 ** (mel / 2595.0) - 1) |
def clean_unit(unit_str):
"""remove brackets and all white spaces in and around unit string"""
return unit_str.strip().strip('[]').strip() |
def boolean(string):
""" Convert strings to booleans for argparse """
string = string.lower()
if string in ['0', 'f', 'false', 'no', 'off']:
return False
elif string in ['1', 't', 'true', 'yes', 'on']:
return True
else:
raise ValueError() |
def peak_friction_angle_peak_et_al_1974(spt_blow_count):
"""
See https://link.springer.com/content/pdf/10.1007%2F978-1-4020-8684-7.pdf
Eq. 2.6
:param spt_blow_count:
:return:
"""
return 30. + 10. / 35 * (spt_blow_count - 10) |
def pythagorean_triple(a,b,c):
"""
>>> pythagorean_triple(3,4,5)
True
>>> pythagorean_triple(3,4,6)
False
"""
if(a**2+b**2==c**2):
return True
else:
return False
"*** YOUR CODE HERE ***" |
def raw_entities_to_table_data(entities):
"""
Convert raw entities from a direct API call into table data of the form:
data = {
"columns": [
{"title": "Heading1"},
{"title": "Heading2"}
],
"data": [
["dat1", "dat2"],
["dat3", "dat4"]
}
}
Where the length of each list in data['data'] must equal to the number of columns
:param entities: Response object containing entities from a direct API call
:param return: Dictionary of data parsable by the UI Table Componenent
"""
# pylint: disable=redefined-outer-name
data = {
"columns": [
{"title": "id"},
{"title": "name"},
{"title": "type"},
],
"data": [],
}
# Iterate through each entity
for entity in entities:
data["data"].append([entity.get_id(), entity.name, entity.get_type()])
return data |
def split_hand(hand_args):
"""
:param hand_args:
:return:
"""
hand = []
card_1 = hand_args[0:2]
hand.append(card_1)
card_2 = hand_args[2:4]
hand.append(card_2)
return hand |
def extract_words(sentence):
"""Extracts the words from a given sentence and returns them in an array"""
words = sentence[0:].split(' ')
return words |
def get_template_string(is_sql):
"""
Generate template string
:param sql:
:return:
"""
if is_sql:
template_string = """from flask_easy.repository import SqlRepository
from app.models import {{model_name}}
class {{repo_name}}(SqlRepository):
model = {{model_name}}
"""
else:
template_string = """from flask_easy.repository import MongoRepository
from app.models import {{model_name}}
class {{repo_name}}(MongoRepository):
model = {{model_name}}
"""
return template_string |
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts. Supports NoneType.
"""
result = {}
for dictionary in dict_args:
if dictionary:
result.update(dictionary)
return result |
def computeAddition( var1, var2):
""" does the addition given two list and exclude NaN values """
total = 0
if var1 != "NaN" and var2 != "NaN":
total = var1 + var2
return total |
def _validated_param(obj, name, base_class, default, base_class_name=None):
"""Validates a parameter passed to __init__. Makes sure that obj is
the correct class. Return obj if it's not None or falls back to default
:param obj: The object passed in.
:param name: The name of the parameter.
:param base_class: The class that obj must inherit from.
:param default: The default object to fall back upon if obj is None.
"""
base_class_name = base_class_name if base_class_name else base_class.__name__
if obj is not None and not isinstance(obj, base_class):
raise ValueError('{name} must be an instance of {cls}'
.format(name=name, cls=base_class_name))
return obj or default |
def update_file_info_in_job(job, file_infos):
"""
Update the 'setup.package.fileInformations' data in the JSON to append new file information.
"""
for file_info in file_infos:
try:
job['setup']['package']['fileInformations'].append(file_info)
except (KeyError, TypeError, AttributeError):
# If we get here, 'setup.package.fileInformations' does not exist yet.
print('Job file input is missing required setup.package.fileInformations data.')
exit(1)
return job |
def av_score_fct(i):
"""AV score function.
Note: this is used only for unit tests atm, because AV is separable anyway and therefore not
implemented as optimization problem
"""
if i >= 1:
return 1
else:
return 0 |
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
If the result is small enough to fit in an int, return an int.
Else return a long.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000L
>>> factorial(30L)
265252859812191058636308480000000L
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000L
It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
result *= factor
factor += 1
return result |
def make_url(ip, port, protocol='tcp'):
""" Return a URL """
return '{}://{}:{}'.format(protocol, ip, port) |
def sort_by_size(s):
"""Sorts the input elements by decreasing length.
Returns a list with the sorted elements."""
return sorted(s, key=len, reverse=True) |
def proper_registry_model_name(name):
"""
A proper registry model name is:
* lowercase
* replaces all non-alphanumeric with dashes
* removes leading and trailing dashes
* limited to 1 dash in a row
"""
name = "".join([(char if char.isalnum() else "-") for char in name])
while name.startswith("-"):
name = name[1:]
while name.endswith("-"):
name = name[:-1]
name = name.lower()
while "--" in name:
name = name.replace("--", "-")
return name |
def entity_in_group(entity, group):
"""
Returns True if entity is contained in a group span, False otherwise
:param entity: A single entity span
:param group: A single group
"""
for span in group["spans"]:
if (span["start"] <= entity["start"] and
span["end"] >= entity["end"]):
return True
return False |
def getNumbersFromString(s):
""" Splits the passed string at spaces and extracts all numeric values
Parameters
----------
@param s - string to be split and have its numbers extracted
Returns
----------
@param vals - list of floats
"""
vals = []
for v in s.replace(',',' ').split():
try:
vals.append(float(v))
except ValueError:
pass
return vals |
def get_savename_from_varname(
varname, varname_prefix=None,
savename_prefix=None):
"""
Args:
varname(str): a variable name in the graph
varname_prefix(str): an optional prefix that may need to be removed in varname
savename_prefix(str): an optional prefix to append to all savename
Returns:
str: the name used to save the variable
"""
name = varname
if varname_prefix is not None \
and name.startswith(varname_prefix):
name = name[len(varname_prefix) + 1:]
if savename_prefix is not None:
name = savename_prefix + '/' + name
return name |
def compact_regions(regions):
"""Returns the list of regions in the compact value used for updates """
out_regions = []
for region in regions:
new_region = []
new_region.append(region.get("label"))
new_region.append(region.get("xmin"))
new_region.append(region.get("ymin"))
new_region.append(region.get("xmax"))
new_region.append(region.get("ymax"))
out_regions.append(new_region)
return out_regions |
def to_update_param(d: dict) -> dict:
"""
Convert data dict to update parameters.
"""
param = {f"set__{k}": v for k, v in d.items()}
return param |
def merge_dict(data, *override):
"""
Utility function for merging dictionaries
"""
result = {}
for current_dict in (data,) + override:
result.update(current_dict)
return result |
def translate_to_group_coordinates(group_crop_list):
"""Translates lists of group crops into groups internal coordinates."""
if len(group_crop_list) == 1:
return group_crop_list
else:
group_crop_list_transl = []
for grp_crops in group_crop_list:
left_anch = min([crp[0] for crp in grp_crops])
top_anch = min([crp[1] for crp in grp_crops])
transl_crops = []
for crp in grp_crops:
transl_crops.append(
(crp[0] - left_anch,
crp[1] - top_anch,
crp[2] - left_anch,
crp[3] - top_anch)
)
group_crop_list_transl.append(transl_crops)
return group_crop_list_transl |
def _GenerateLocalProperties(sdk_dir):
"""Returns the data for local.properties as a string."""
return '\n'.join([
'# Generated by //build/android/gradle/generate_gradle.py',
'sdk.dir=%s' % sdk_dir,
'',
]) |
def dict_contains_sub_dict(config, test_config):
"""
Determine whether a dictionary contains a sub-dictionary. Returns True if
test_config is an empty dict.
Parameters
----------
config : dict
test_config : dict
"""
if not isinstance(config, dict) or not isinstance(test_config, dict):
raise ValueError("config and test_config both must be dictionaries")
if bool(test_config) is False:
return True
out = []
for k, v in test_config.items():
if not all(out):
break
if k not in config:
out.append(False)
continue
elif isinstance(v, dict):
out.append(dict_contains_sub_dict(config[k], test_config[k]))
else:
out.append(True if config[k] == v else False)
return all(out) |
def is_winning(p, state):
"""Defines all of the states where a player wins in function of morpions
rules."""
return state[0][0] == state[0][1] == state[0][2] == p or \
state[1][0] == state[1][1] == state[1][2] == p or \
state[2][0] == state[2][1] == state[2][2] == p or \
state[0][0] == state[1][0] == state[2][0] == p or \
state[0][1] == state[1][1] == state[2][1] == p or \
state[0][2] == state[1][2] == state[2][2] == p or \
state[0][0] == state[1][1] == state[2][2] == p or \
state[0][2] == state[1][1] == state[2][0] == p |
def reduce_dict(dictionary, keys):
"""Returns a dictionary containing only the input keys"""
return {key: (dictionary[key] if key in dictionary else []) for key in keys} |
def format_bytes(n: int) -> str:
"""Format bytes as text
>>> from dask.utils import format_bytes
>>> format_bytes(1)
'1 B'
>>> format_bytes(1234)
'1.21 kiB'
>>> format_bytes(12345678)
'11.77 MiB'
>>> format_bytes(1234567890)
'1.15 GiB'
>>> format_bytes(1234567890000)
'1.12 TiB'
>>> format_bytes(1234567890000000)
'1.10 PiB'
For all values < 2**60, the output is always <= 10 characters.
"""
for prefix, k in (
("Pi", 2**50),
("Ti", 2**40),
("Gi", 2**30),
("Mi", 2**20),
("ki", 2**10),
):
if n >= k * 0.9:
return f"{n / k:.2f} {prefix}B"
return f"{n} B" |
def unit_normalization(series, config):
""" Do unit normalization based on "reference_length" number of bins
at the end of the series"""
reference_length = int(config["reference_length"])
SMALL_NUMBER = 0.00001
offset = int(config["baseline_offset"])
lower_idx = -(int(config["reference_length"]) + offset)
upper_idx = -offset
total = sum(series[lower_idx:upper_idx])/float(reference_length)
if total == 0:
total = SMALL_NUMBER
return [float(pt)/total for pt in series] |
def merge_sort(alist, inplace=False, print_inv=True, inversions=[0], reset_inv=True):
"""Merge sort implementation with inversions counter.
:param alist: list
:param inplace: bool. If True, list is sorted in place, otherwise a new list is returned.
:param print_inv: bool. If True prints out total inversions number.
:param inversions: mutable default argument to avoid globals (educational goal only).
:param reset_inv: bool. Inversions parameter is set to [0] when sorting is done.
>>> merge_sort([4, 3, 2, 1])
Inversions: [6]
[1, 2, 3, 4]
>>> merge_sort([5, 4, 3, 2, 1])
Inversions: [10]
[1, 2, 3, 4, 5]
>>> merge_sort([5, 4, 3, 2, 1, 5])
Inversions: [10]
[1, 2, 3, 4, 5, 5]
>>> merge_sort([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], True)
Inversions: [45]
"""
if inplace:
combined = alist
else:
combined = alist[:]
list_len = len(combined)
if list_len > 1:
middle = list_len // 2
left = combined[:middle]
right = combined[middle:]
merge_sort(left, True, False, inversions, False)
merge_sort(right, True, False, inversions, False)
left_idx = 0
right_idx = 0
for k in range(list_len):
if left_idx == len(left):
combined[k] = right[right_idx]
right_idx += 1
elif right_idx == len(right):
combined[k] = left[left_idx]
left_idx += 1
elif left[left_idx] <= right[right_idx]:
combined[k] = left[left_idx]
left_idx += 1
elif left[left_idx] > right[right_idx]:
combined[k] = right[right_idx]
right_idx += 1
# When this term is met. Count inversions by adding
# a number of remaining elements in a left sublist.
# Sublists are sorted, so when left element is greater
# than the right one, all next left elements are greater too.
inversions[0] += len(left[left_idx:])
if print_inv:
print("Inversions:", inversions)
if reset_inv:
inversions[0] = 0
if not inplace:
return combined
return None |
def bit_mask(n):
"""Return an integer of n bits length with all bits set.
>>> bin(bit_mask(5))
'0b11111'
"""
return (1 << n) - 1 |
def factors(n):
"""
Finds all factors for a given number.
Copied from https://stackoverflow.com/a/19578818
:param n: some integer
:return: set with all factors of n
"""
from functools import reduce
from math import sqrt
step = 2 if n % 2 else 1
return set(
reduce(
list.__add__,
([i, n // i] for i in range(1, int(sqrt(n)) + 1, step) if n % i == 0),
)
) |
def move_after(_list, static, dynamic):
"""
Move *static* elem. after *dynamic* elem. in list *_list*
Both *static* and *dynamic* MUST belong to *_list*.
:return list: return _list with moved *dynamic* elem.
"""
_list.remove(dynamic)
next_pos = _list.index(static) + 1
_list.insert(next_pos, dynamic)
return _list |
def wrap_lines(lines, line_length=80,
word_sep=' ', line_sep='\n',
strip_whitespace=True):
"""Wrap the contents of `lines` to be `line_length` characters long.
Parameters
==========
lines : string
Text to wrap
line_length : integer
Maximum number of characters per line
word_sep : string
Word separator. Where possible, this function will attempt to preserve
words by wrapping at instances of this string
line_sep : string
Line separator to identify individual lines in `lines` and to join the
newly-wrapped lines back together
strip_whitespace : boolean
If True, strip leading and trailing whitespace from the newly-wrapped
lines
Returns
=======
wrapped : string
Version of `lines`, wrapped to a maximum of `line_length`
Notes
=====
Where `word_sep` is not an empty string, this function attempts to split at
word boundaries while still having each line have a maximum character
length of `line_length`.
Where this is not possible, the line is simply wrapped at `line_length`
characters.
"""
# Just return if wrapping not required
if len(lines) <= line_length:
return lines
# Split by `line_sep`
lines = lines.split(line_sep)
# Wrap one line at a time
wrapped = []
for line in lines:
while len(line) > line_length:
rightmost_word_sep = line[:line_length + 1].rfind(word_sep)
# Just set to `line_length` if no word separator found
if rightmost_word_sep == -1:
rightmost_word_sep = line_length
wrapped.append(line[:rightmost_word_sep])
line = line[rightmost_word_sep:]
wrapped.append(line)
# Strip whitespace
if strip_whitespace:
wrapped = [w.strip() for w in wrapped]
# Join and return
wrapped = line_sep.join(wrapped)
return wrapped |
def replace_dollar(sentence, even=False):
"""
convert method
"""
if even:
return sentence.replace('$', '\\\\)', 1)
return sentence.replace('$', '\\\\(', 1) |
def max(a,b):
"""
Return the maximum of A and B.
"""
if a > b:
return a
else:
return b |
def pick(*args):
"""
Returns the first non None value of the passed in values
:param args:
:return:
"""
for item in args:
if item is not None:
return item
return None |
def valid_vestal_transaction(transaction):
""" check if raw client transaction contains required fields """
valid = True
if "header" not in transaction:
return False
tx_header = transaction["header"]
if "transaction_type" not in tx_header or not tx_header["transaction_type"]:
valid = False
elif "owner" not in tx_header or not tx_header["owner"]:
valid = False
return valid |
def compute_lps_table(P):
"""Computes the longest prefix suffix table for KMP algorithm."""
m = len(P)
lps_table = [0] * m
j = 1
k = 0
while j < m:
if P[j] == P[k]:
lps_table[j] = k + 1
j += 1
k += 1
# k follows matching prefix
elif k > 0:
k = lps_table[k - 1]
# no match found at index j
else:
j += 1
return lps_table |
def BinarySearch(list, target):
""" Takes a list of numbers as the input and returns the index if the
target value is found in the list otherwise it returns None
"""
first=0
last=len(list) -1
while first<=last:
midpoint=(first+last)//2
if list[midpoint] == target:
return midpoint
else:
if list[midpoint] < target:
first=midpoint+1
else:
last=midpoint-1
return None |
def LOWER(text):
"""Convert all text to uppercase.
Parameters
----------
text : list or string
string(s) to be converted to lowercase.
Returns
-------
list or string
A list of converted strings or converted string to lowercase.
"""
if type(text) == str:
return((text).lower())
elif type(text) == list:
try:
text_return = [(i).lower() for i in text]
return(text_return)
except:
print('Invalid list: please enter a list of strings.')
else:
print('Invalid type: please enter a string or list of strings.') |
def prependToList(originalList, listToPrepend):
"""
Add a new list to the beginnning of an original list.
Parameters
----------
originalList : list
The list to prepend to.
listToPrepend : list
The list to add to the beginning of (prepend) the originalList.
Returns
-------
originalList : list
The original list with the listToPrepend at it's beginning.
"""
listToPrepend.reverse()
originalList.reverse()
originalList.extend(listToPrepend)
originalList.reverse()
listToPrepend.reverse()
return originalList |
def cost_lower_bound(hashable_state, target, type_costs, steps, rooms):
"""
Give a lower bound for the lowest cost from state to target.
Estimation: measure cost of moving each animal to the topmost
tile of their respective rooms, ignoring all other animals.
"""
if isinstance(hashable_state, dict):
hashable_state = hashable_state.items()
cost_bound = 0
for pos, kind in hashable_state:
if pos[0] >= 2 and pos[1] == rooms[kind]:
# we're in the right room, might not have to move at all
continue
cost_bound += type_costs[kind] * steps[pos, (2, rooms[kind])]
return cost_bound |
def dp_lcs_recr(s1, s2, m, n):
"""O(2^max(M, N))"""
if m == 0 or n == 0:
return 0
elif s1[m - 1] == s2[n - 1]:
return 1 + dp_lcs_recr(s1, s2, m - 1, n - 1)
else:
return max(
dp_lcs_recr(s1, s2, m - 1, n),
dp_lcs_recr(s1, s2, m, n - 1)
) |
def __fire_trans(m, preset, postset):
"""
Fires a transition and returns a new marking
Parameters
---------------
m
Marking
preset
Preset
postset
Postset
Returns
---------------
new_m
New marking
"""
ret = {}
for k in m:
if k in preset:
diff = m[k] - preset[k]
if diff > 0:
ret[k] = diff
else:
ret[k] = m[k]
for k in postset:
if k not in ret:
ret[k] = postset[k]
else:
ret[k] = ret[k] + postset[k]
return ret |
def oaseries2html(N, t, s=2, k='a'):
""" Return html string for design specification """
cstr = 'OA(%d; %d; %d<sup>%s</sup>)' % (N, t, s, k)
# cstr='OA(%d; %d<sup>%s</sup>; %d)' % (N, s, k, t)
return cstr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.