content stringlengths 42 6.51k |
|---|
def get_docker_tag(platform: str, registry: str) -> str:
""":return: docker tag to be used for the container"""
platform = platform if any(x in platform for x in ['build.', 'publish.']) else 'build.{}'.format(platform)
if not registry:
registry = "mxnet_local"
return "{0}/{1}".format(registry, p... |
def _truncate(s: str, max_length: int) -> str:
"""Returns the input string s truncated to be at most max_length characters
long.
"""
return s if len(s) <= max_length else s[0:max_length] |
def add_anchors(pattern):
"""If there's no explicit start and end line symbols it is necessary to
add the corresponding regexes to the beggining and end of the string.
:param pattern: A regular expression.
:type pattern: str
"""
# Start line.
pattern = pattern[1:] if pattern.startswith('^'... |
def invalid_br_vsby(v):
"""Checks if visibility is inconsistent with BR"""
return not 0.6 < v < 6.1 |
def unlist(_list):
""" if list is of length 1, return only the first item
:arg list _list: a python list
"""
if len(_list) == 1:
return _list[0]
else:
return _list |
def mean(data):
""" This is used to find the mean in a set of data. The mean is commonly referred to as the 'average'."""
data = data
sum = 0
for x in data:
sum += x
return sum/len(data)
def __repr__(): "Mean(enter data here)" |
def get_stat( dance, player, stat ):
"""
Accepts a bin representing the player
and a string representing the stat
and returns the stat's value.
"""
return dance[ str(player) ][ str(stat) ] |
def check_in_data(var, data):
""" Check, if var in data dictionary or not """
if var not in data:
# print(f"Info : Key error for { var }")
data[var] = ""
return data[var] |
def get_descriptors_text(dl):
"""
Helper function that separates text descriptors from the mixture
of text and uris that is returned from Agritriop
Parameters
----------
dl : list
Descriptor list.
Returns
-------
list
list of text descritors only.
"""
retur... |
def is_prime(x):
"""Assumes x is a nonnegative int
Returns True if x is prime; False otherwise"""
if x <= 2:
return False
for i in range(2, x):
if x%i == 0:
return False
return True |
def nesting_level(x):
"""Calculate nesting level of a list of objects.
To convert between sparse and dense representations of topological
features, we need to determine the nesting level of an input list.
The nesting level is defined as the maximum number of times we can
recurse into the object whi... |
def copy_rate(sent1, sent2):
"""
copy rate between two sentences.
In particular, the proportion of sentence 1 that are copied from sentence 2.
Input:
sent1, sent2: two sentence strings (generated summary, source).
Output:
score: copy rate on unigrams.
"""
sent1_split = set(s... |
def determinant(point1, point2, point3):
"""
Compute the determinant of three points, to determine the turn direction,
as a 3x3 matrix:
[p1(x) p1(y) 1]
[p2(x) p2(y) 1]
[p3(x) p3(y) 1]
:param point1: the first point coordinates as a [x,y] list
:param point2: the second point coordinates... |
def quorum_check(value_x, value_y, value_z, delta_max):
"""
Quorum Checking function
Requires 3 input values and a max allowed delta between sensors as args.
Checks all 3 values against each other and max delta to determine if sensor has
failed or is way out of agreement with the other two.
Retu... |
def bit_mask(start, stop):
"""Return a number with all it's bits from `start` to `stop` set to 1."""
number_of_set_bits = stop - start + 1
return ((1 << number_of_set_bits) - 1) << start |
def shiftRow(s):
"""ShiftRow function"""
return [s[0], s[1], s[3], s[2]] |
def revert_dictionary(dictionary):
"""Given a dictionary revert it's mapping
:param dictionary: A dictionary to be reverted
:returns: A dictionary with the keys and values reverted
"""
return {v: k for k, v in dictionary.items()} |
def speech_response(output, endsession):
""" create a simple json response """
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'shouldEndSession': endsession
} |
def clean_comment(comment):
"""Remove comment formatting.
Strip a comment down and turn it into a standalone human readable sentence.
Examples:
Strip down a comment
>>> clean_comment("# hello world")
"Hello world"
Args:
comment (str): Comment to clean
Returns:
... |
def countchanges(hunk):
"""hunk -> (n+,n-)"""
add = len([h for h in hunk if h[0] == '+'])
rem = len([h for h in hunk if h[0] == '-'])
return add, rem |
def format_exc_for_journald(ex, indent_lines=False):
"""
Journald removes leading whitespace from every line, making it very
hard to read python traceback messages. This tricks journald into
not removing leading whitespace by adding a dot at the beginning of
every line
:param ex: Error lines
... |
def are_all_terms_fixed_numbers(sequence: str):
"""
This method checks whither the sequence consists of numbers (i.e. no patterns)
sequence: A string that contains a comma seperated numbers
returns: True if the sequence contains numbers only, False otherwise.
"""
seq_terms = sequence.split(",")
... |
def _errors_to_text(errors):
"""Turn a resolution errors trace into a list of text."""
texts = []
for err in errors:
texts.append('Server {} {} port {} answered {}'.format(err[0],
'TCP' if err[1] else 'UDP', err[2], err[3]))
return texts |
def merge_two_dicts(x, y):
"""Copied from https://stackoverflow.com/a/26853961/4386191"""
z = x.copy() # start with x's keys and values
z.update(y) # modifies z with y's keys and values & returns None
return z |
def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
... |
def __get_wind_adjustment(wind_speed):
"""
Calculate the wind adjustment value by wind speed
:param float wind_speed:
:return:
"""
if wind_speed < 0:
raise ValueError('wind speed cannot be negative')
if 0 <= wind_speed <= 12:
wind = 1
elif 13 <= wind_speed <= 25:
... |
def _extract_match(toc, index, seperator=','):
"""
Extracts a path between seperators (,)
:toc (str) Table of contents
:index (int) Index of match
returns full path from match
"""
length = len(toc)
start_index = index
while toc[start_index] != seperator and start_index >= 0:
... |
def removeEmptyElements(list):
""" Remove empty elements from a list ( [''] ), preserve the order of the non-null elements.
"""
tmpList = []
for element in list:
if element:
tmpList.append(element)
return tmpList |
def get_letter_from_index(index: int) -> str:
"""Gets the nth letter in the alphabet
Parameters
----------
index : int
Position in the alphabet
Returns
-------
str
Letter at given position in the alphabet
"""
return chr(ord("@") + index) |
def billetes_verdes(cant):
"""
Str -> num
:param cant: valor de una cantidad en euros
:return: los billetes
>>> billetes_verdes('434')
'2 billetes de 200 1 billete de 20 euros 1 billete de 10 euros 2 monedas de 2 euros'
>>> billetes_verdes('626')
'3 billetes de 200 1 billete de 20 euro... |
def second_word(s):
"""Returns the second word of `s`, regardless of how many spaces are before
it.
Parameters
----------
s : str
Returns
-------
second_w : str
The second word of `s`.
"""
# Initialisations
s_list = list(s)
for i in range(1, len(s)):
i... |
def _get_metric_value(nested_dict, metric_name):
"""Gets the value of the named metric from a slice's metrics."""
for key in nested_dict:
if metric_name in nested_dict[key]['']:
typed_value = nested_dict[key][''][metric_name]
if 'doubleValue' in typed_value:
return typed_value['doubleValue']... |
def _store_chunks_in_order(seen: str, unseen: str, seen_first: bool) -> list:
"""
Save two strings (a 'seen' and an 'unseen' string) in an array where the 'seen' string is
the first element if the seen_first parameter is True.
@param seen: The 'seen' string
@param unseen: The 'unseen' string
@r... |
def is_tuner(x):
"""
Whether or not x is a tuner object (or just a config object).
"""
return x is not None and hasattr(x, 'iter_params') |
def handle_value(data):
"""
Take a non-string scalar value and turns it into yamelish.
Return a tuple: yamelish (string), whether this string is a block (boolean)
"""
return str(data), False |
def pixel_to_world(geo_trans, x, y):
"""Return the top-left world coordinate of the pixel
:param geo_trans: geo transformation
:type geo_trans: tuple with six values
:param x:
:param y:
:return:
"""
return geo_trans[0] + (x * geo_trans[1]), geo_trans[3] + (y * geo_trans[5]) |
def _set_default_capacitance(
subcategory_id: int,
style_id: int,
) -> float:
"""Set the default value of the capacitance.
:param subcategory_id:
:param style_id:
:return: _capacitance
:rtype: float
:raises: KeyError if passed a subcategory ID outside the bounds.
:raises: IndexError... |
def is_in(x, l):
"""Transforms into set and checks existence
Given an element `x` and an array-like `l`, this function turns `l` into a
set and checks the existence of `x` in `l`.
Parameters
--------
x : any
l : array-like
Returns
--------
bool
"""
return x in set(l) |
def split_kwargs(relaxation_kwds):
"""Split relaxation keywords to keywords for optimizer and others"""
optimizer_keys_list = [
'step_method',
'linesearch',
'eta_max',
'eta',
'm',
'linesearch_first'
]
optimizer_kwargs = { k:relaxation_kwds.pop(k) for k in ... |
def casa_argv(argv):
""" Processes casarun arguments into C-style argv list.
Modifies the argv from a casarun script to a classic argv list
such that the returned argv[0] is the casarun scriptname.
Parameters
----------
argv : list of str
Argument list.
... |
def from_tags(tags):
"""Transform the boto way of having tags into a dictionnary"""
return {e['Key']: e['Value'] for e in tags} |
def ascii2int(str, base=10,
int=int):
""" Convert a string to an integer.
Works like int() except that in case of an error no
exception raised but 0 is returned; this makes it useful in
conjunction with map().
"""
try:
return int(str, base)
except:
... |
def is_straight(pips):
"""Return True if hand is a straight.
Compare card pip values are in decending order. Hand is presorted.
"""
return (pips[0] == pips[1] + 1 == pips[2] + 2 ==
pips[3] + 3 == pips[4] + 4) |
def vector2d(vector):
""" return a 2d vector """
return (float(vector[0]), float(vector[1])) |
def getkey(value, key):
"""\
Fetch a key from a value. Useful for cases such as dicts which have '-' and ' '
in the key name, which Django can't cope with via the standard '.' lookup.
"""
try:
return value[key]
except KeyError:
return "" |
def romi(total_revenue, total_marketing_costs):
"""Return the Return on Marketing Investment (ROMI).
Args:
total_revenue (float): Total revenue generated.
total_marketing_costs (float): Total marketing costs
Returns:
Return on Marketing Investment (float) or (ROMI).
"""
re... |
def path2fname(path):
"""
Split path into file name and folder
========== ===============================================================
Input Meaning
---------- ---------------------------------------------------------------
path Path to a file [string], e.g. 'C:\\Users\\SPAD-F... |
def find_key(d, nested_key):
"""Attempt to find key in dict, where key may be nested key1.key2..."""
keys = nested_key.split('.')
key = keys[0]
return (d[key] if len(keys) == 1 and key in d else
None if len(keys) == 1 and key not in d else
None if not isinstance(d[key], dict) el... |
def round_filters(filters, multiplier, divisor=8, min_width=None):
"""Calculate and round number of filters based on width multiplier."""
if not multiplier:
return filters
filters *= multiplier
min_width = min_width or divisor
new_filters = max(min_width, int(filters + divisor / 2) // diviso... |
def validate_key(data, key):
"""
Validates that a key exists or not
"""
try:
return data[key[0]]
except Exception as e:
return "NAN" |
def linearize(a, b, y):
"""Generates linearization constraints for the product y = ab.
Parameters
----------
a : str
First factor.
b : str
Second factor.
y : Product.
Returns
-------
List[str]
A list holding the three linearization constraints.
"""
... |
def de_dupe_list(input):
"""de-dupe a list, preserving order.
"""
sam_fh = []
for x in input:
if x not in sam_fh:
sam_fh.append(x)
return sam_fh |
def mean(val_a, val_b):
"""
A function returning the mean of both values.
This function is redeveloped so as to be called as choice_func in the function "values_as_slop()" (see below) in external projects.
Parameters
----------
val_a : float
First value.
val_b : float
Second... |
def fit_function(x, a, b):
"""
This function ...
:param x:
:param a:
:param b:
:return:
"""
return a * x + b |
def list_intersection(a, b):
"""
Find the first element in the intersection of two lists
"""
result = list(set(a).intersection(set(b)))
return result[0] if result else None |
def encode(num, alphabet):
"""Encode a positive number into Base X and return the string.
Arguments:
- `num`: The number to encode
- `alphabet`: The alphabet to use for encoding
"""
if num == 0:
return alphabet[0]
arr = []
arr_append = arr.append # Extract bound-method for fast... |
def escape(inp, quote='"'):
"""
Escape `quote` in string `inp`.
Example usage::
>>> escape('hello "')
'hello \\"'
>>> escape('hello \\"')
'hello \\\\"'
Args:
inp (str): String in which `quote` will be escaped.
quote (char, default "): Specify which char... |
def sortkey(d):
"""Split d on "_", reverse and return as a tuple."""
parts=d.split("_")
parts.reverse()
return tuple(parts) |
def _strip_sort_key(the_dict):
"""
The sort key is prepended to the each of the values in this list of
dictionaries. But that sort key shouldn't remain a part of the dictionary,
so remove it. It's separated from the name by a colon.
"""
new_dict = {}
for k, v in the_dict.items():
new... |
def encode_var_int(number):
"""
Returns a bytearray encoding the given number.
"""
buf = bytearray()
shift = 1
while True:
buf.append(number & 0x7F)
number -= buf[-1]
if number == 0:
buf[-1] |= 0x80
break
number -= shift
number >>= 7
shift += 7
return buf |
def calc_jac_titles(title1, title2):
"""
Identify titles for jaccard similarity (used in calculate_jaccard)
"""
countIntersection = 0
for token in title2:
if token in title1:
countIntersection += 1
countUnion = len(title1) + len(title2) - countIntersection
return countInt... |
def is_summary(number):
"""
Takes a number as input
Identifies a sentence as part of the summery or not
"""
if number != 0:
return 'yes'
else:
return 'no' |
def eq_by(f, value_1, value_2):
"""Check if two values are equal when applying f on both of them."""
return f(value_1) == f(value_2) |
def _neighboring_points(o_index, i_index, e_len, f_len):
"""
A function that returns list of neighboring points in
an alignment matrix for a given alignment (pair of indexes)
"""
result = []
if o_index > 0:
result.append((o_index - 1, i_index))
if i_index > 0:
result.append(... |
def _to_map(keys, vals):
"""Attach the keys from the file header to the values. Both are assumed
to be in the order read from the input file"""
return {k: v for k, v in zip(keys, vals)
if v is not None and v != ''} |
def dictSave(d,fname=None):
"""format a dictionary to text. If no fname given, just print."""
out=""
for k in sorted(d.keys()):
if type(d[k])==str:
out+='%s = "%s"\n'%(k,str(d[k]))
else:
out+="%s = %s\n"%(k,str(d[k]))
if fname==None:
print(out)
else:
#debug("writing configuration ... |
def remove_comments(lines, token='#'):
""" Generator. Strips comments and whitespace from input lines.
"""
l = []
for line in lines:
s = line.split(token, 1)[0].strip()
if s != '':
l.append(s)
return l |
def _deep_value(*args, **kwargs):
""" Drills down into tree using the keys
"""
node, keys = args[0], args[1:]
for key in keys:
node = node.get(key, {})
default = kwargs.get('default', {})
if node in ({}, [], None):
node = default
return node |
def get_list_index_or_none_if_out_of_range(imageList, index):
"""
This function...
:param imageList:
:param index:
:return:
"""
if index < len(imageList):
return imageList[index]
else:
return None |
def human_format(num):
"""
Convert <num> into human form (round it and add a suffix)
"""
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
# add more suffixes if you need them
return '%.3f%s' % (num, ['', 'K', 'M', 'B', 'T', 'Q'][magnitude]) |
def append_s(value):
"""
Adds the possessive s after a string.
value = 'Hans' becomes Hans'
and value = 'Susi' becomes Susi's
"""
if value.endswith('s'):
return u"{0}'".format(value)
else:
return u"{0}'s".format(value) |
def html_list_element(content):
"""Creates an html list element from the given content
:returns: html list element as string
"""
return "<li>" + content + "</li>" |
def namestr(object):
"""This method returns the string name of a python object.
:param object: The object that should be used
:type object: Python object
:returns: Object name as string
"""
for n,v in globals().items():
if v == object:
return n
return None |
def caseless_uniq(un_uniqed_files):
"""
Given a list, return a list of unique strings, and a list of duplicates.
This is a caseless comparison, so 'Test' and 'test' are considered duplicates.
"""
lower_files = [] # Use this to allow for easy use of the 'in' keyword
unique_files = [] # Guarante... |
def bubble_sort(input_data):
"""Implementation of the bubble sort algorithm, employs an enhancement where the inner loops
keep track of the last sorted element as described in the video below.
(https://www.youtube.com/watch?v=6Gv8vg0kcHc)
The input_data is sorted in-place, this is dangerous to do
... |
def getDigitsFromStr(string:str,withDigitPoint:bool = False):
"""
Extract number from a string. Return a list whose element is strings that is number.
Parameters
----------
string : str
The string that may contain numbers.
withDigitPoint : bool
Use true is the numbers are float. False if all numbers are int.... |
def period_contribution(x):
"""
Turns period--1, 2, 3, OT, etc--into # of seconds elapsed in game until start.
:param x: str or int, 1, 2, 3, etc
:return: int, number of seconds elapsed until start of specified period
"""
try:
x = int(x)
return 1200 * (x - 1)
except ValueErro... |
def AND(p: bool, q: bool) -> bool:
"""
Conjunction operator used in propositional logic
"""
return bool(p and q) |
def first(value):
"""Returns the first item in a list."""
try:
return value[0]
except IndexError:
return '' |
def get_accuracy_count(data_list, optimal_distance):
"""
Processes data list from file to find accuracy count.
Returns accuracy count.
"""
count = sum(1 for i in data_list if optimal_distance in i)
return count |
def bottom_up_mscs(seq: list) -> tuple:
"""Dynamic programming bottom-up algorithm which finds the sub-sequence of
seq, such that the sum of the elements of that sub-sequence is maximal.
Let sum[k] denote the max contiguous sequence ending at k. So, we have:
sum[0] = seq[0]
sum[k + 1] = m... |
def _unquote(tk):
"""Remove quotes from a string. Perform required substitutions.
- Enclosing quotes are removed
- SQL-like escape sequence in single quotes are replaced by
their value (i.e: 'abc''def' => abc'def)
"""
if not tk:
return tk
if tk[0] == tk[-1] == '"':
retur... |
def get_local_name(full_name):
"""
Removes namespace part of the name.
Namespaces can appear in 2 forms:
{full.namespace.com}name, and
prefix:name.
Both cases are handled correctly here.
"""
full_name = full_name[full_name.find('}')+1:]
full_name = full_n... |
def fib(n : int) -> int:
"""precondition: n >= 0
"""
if n == 0:
return 1
elif n == 1:
return 1
else:
return fib(n-2) + fib(n-1) |
def _get_config(path, value):
"""
Create config where specified key path leads to value
:type path: collections.Sequence[six.text_type]
:type value: object
:rtype: collections.Mapping
"""
config = {}
for step in reversed(path):
config = {step: config or value}
return config |
def IS_ARRAY(expression):
"""
Determines if the operand is an array. Returns a boolean.
See https://docs.mongodb.com/manual/reference/operator/aggregation/isArray/
for more details
:param expression: Any valid expression.
:return: Aggregation operator
"""
return {'$isArray': expression} |
def py_str(x):
"""convert c string back to python string"""
return x.decode('utf-8') |
def borr(registers, a, b, c):
"""(bitwise OR register) stores into register C the result of the bitwise OR of register A and register B."""
registers[c] = registers[a] | registers[b]
return registers |
def get_path_to_service(service_id):
"""In lieu of a url-reversing mechanism for routes in the app"""
return '/app/index.html#/service/%d' % service_id |
def dblp_key_extract(entry):
"""Return dblp key if the bibtex key is already a DBLP one, otherwise
return none."""
if entry["ID"].startswith("DBLP:"):
return entry["ID"][5:]
else:
return None |
def circulator(circList, entry, limit):
"""
This method will wrap a list overwriting at the
beginning when limit is reached.
Args
----
circList: list
initial list
entry: any
item to add to list
limit: int
size limit for circular list
Returns
-------
... |
def find_diff_indexes_and_lenght_on_same_size_values(value_one, value_two):
"""Find the diff indexes and lenght of the difference, as follows below, and return on an array of diffs. Some more details follows below:"""
"""(a) on the first different char in a sequence, save that index on a buffer along with t... |
def nil_eq(a, b):
"""Implementation of `equal` (only use with Nil types)."""
return a is None and b is None |
def _get_vault_path(device_uuid):
"""Generate full vault path for a given block device UUID
:param: device_uuid: String of the device UUID
:returns: str: Path to vault resource for device
"""
# return '{}/{}'.format(
# socket.gethostname(),
# device_uuid
# )
return device_u... |
def sfx(uri: str) -> str:
"""
Add a separator to a uri if none exists.
Note: This should only be used with module id's -- it is not uncommon to use partial prefixes,
e.g. PREFIX bfo: http://purl.obolibrary.org/obo/BFO_
:param uri: uri to be suffixed
:return: URI with suffix
"""
return s... |
def xy_to_xyz(x, y):
"""Convert `xyY` to `xyz`."""
return [x / y, 1, (1 - x - y) / y] |
def _transform_summarized_rep(summarized_rep):
"""change around the keys of the summarized_representation dictionary
This makes them more readable
This function makes strong assumptions about what the keys look like
(see PooledVentralStreams.summarize_representation for more info on this):
a singl... |
def strp(value, form):
"""
Helper function to safely create datetime objects from strings
:return: datetime - parsed datetime object
"""
# pylint: disable=broad-except
from datetime import datetime
def_value = datetime.utcfromtimestamp(0)
try:
return datetime.strptime(value, for... |
def control_game(cmd):
"""
returns state based on command
"""
if cmd.lower() in ("y", "yes"):
action = "pictures"
else:
action = "game"
return action |
def decompose_seconds(seconds):
"""
Descomponer una cantidad de segundos en horas, minutos y segundos.
:param seconds:
:return:
"""
h = int(seconds // 3600)
m = int(seconds % 3600 // 60)
s = int(seconds % 60)
ms = int((seconds - int(seconds)) * 1000)
return h, m, s, ms |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.