content stringlengths 42 6.51k |
|---|
def min_latitude(coordinates):
"""
This function returns the minimum value of latitude
of a list with tuples [(lat, lon), (lat, lon)].
:param coordinates: list
list with tuples. Each tuple
has coordinates float values.
... |
def get_marker(label):
"""Set custom markers for scatter plots here"""
if 'Depth' in label: marker = 'o'
elif 'A*' in label: marker = '*'
elif 'Beam' in label: marker = 'x'
elif 'Random' in label: marker = 'D' #should be last lest it picks up on random increments
else: marker = 'H'
return ma... |
def f_list_dim(testlist, dim=0):
"""
Utility function: tests if testlist is a list and how many dimensions it has
returns -1 if it is no list at all, 0 if list is empty
and otherwise the dimensions of it. All elements must be equal"""
if isinstance(testlist, list):
if testlist == []:
... |
def _get_new_shape(name, shape, num_heads):
"""Checks whether a variable requires reshape by pattern matching."""
if "attention/attention_output/kernel" in name:
return tuple([num_heads, shape[0] // num_heads, shape[1]])
if "attention/attention_output/bias" in name:
return shape
patterns = [
... |
def lists_diff(list1, list2):
"""
Get the difference of two list and remove None values.
>>> list1 = ["a", None, "b", "c"]
>>> list2 = [None, "b", "d", "e"]
>>> list(filter(None.__ne__, set(list1) - set(list2)))
['c', 'a']
"""
return list(filter(None.__ne__, set(list1) - set(list2))) |
def to_readable(o, fields, translated):
"""
Convert object properties to nice title readable
"""
res = {}
if o:
for f in fields:
if o.get(f):
if translated.get(f):
res[translated.get(f)] = o.get(f)
else:
res[... |
def replace_plus_minus(string):
"""Replace the + symbol to %2B for url.
Parameters
----------
string:
A string
Returns
-------
string:
A reformatted string.
"""
return str(string).replace('-', '%2D').replace('+', '%2B') |
def _rankine_to_kelvin(SI):
# type: (bool) -> float
"""converts K -> R"""
if SI:
factor = 5 / 9.
else:
factor = 1.
return factor |
def calc_tpr_protected(actual, predicted, sensitive, unprotected_vals, positive_pred, is_tnr=False):
"""
Returns P(C=YES|Y=YES, sensitive=privileged) and P(C=YES|Y=YES, sensitive=not privileged)
in that order where C is the predicited classification and where all not privileged values are
considered equ... |
def _parse_name(name):
""" Parse the name of an ensemble prediction
"""
components = name.split('_')
assert len(components) == 2, 'Name does not follow the convention of type_userdefined, such as point_alice or distribution_bob123'
assert components[0] in ['point', 'distribution', 'interval', 'quan... |
def gen_overlay_dirs(environment, region):
"""Generate possible overlay directories."""
return [
# Give preference to explicit environment-region dirs
"%s-%s" % (environment, region),
# Fallback to environment name only
environment
] |
def filter_matches_distance(matches, dist_threshold):
"""
Filter matched features from two images by distance between the best matches
Arguments:
match -- list of matched features from two images
dist_threshold -- maximum allowed relative distance between the best matches, (0.0, 1.0)
Returns:... |
def make_uppercase_title(title_words):
"""make the title uppercase
>>> make_uppercase_title(["This", "translation", "app", "helps", "professionals", "traveling", "in", "China", "and", "Japan"])
['THIS', 'TRANSLATION', 'APP', 'HELPS', 'PROFESSIONALS', 'TRAVELING', 'IN', 'CHINA', 'AND', 'JAPAN']
"""
... |
def _to_set(obj):
""" Given an object wrap it in a set """
try:
return set(obj)
except TypeError:
if obj is None:
return set()
return set((obj,)) |
def bucket_fill(matrix: list, start: tuple, target: int)-> list:
"""the classics
"""
# define valid functions
row, column = start
base = matrix[row][column]
def valid(node):
row, column = node
if not 0 <= row < len(matrix) or not 0 <= column < len(matrix[0]): return False
... |
def what_versions_sync(pg_versions, gh_versions, pg_versions_gh):
""" versions to add, update, delete.
"""
to_add = gh_versions - pg_versions
to_update = pg_versions_gh & gh_versions
to_delete = pg_versions_gh - gh_versions
return to_add, to_update, to_delete |
def print_part_format(d, config, print_part=None):
"""
:param dict d: item dict.
:param list config: print config.
:param str print_part: which part from config to add to formatted string.
:return str: formatted string.
"""
config_dict = dict()
keys_list = list()
for config_item in c... |
def generate_primes(upper_limit, k):
"""
Takes upper limit and number of primes as argument.
Generates prime numbers by sieve of erothesus method
"""
numbers = [0] * (upper_limit - 1)
for i in range(2, int(upper_limit ** 0.5) + 1 + 1):
prod = 2 * i
while prod <= upper_limit:
... |
def filter_true(argument):
"""
Return the predicate value of given item and the item itself.
:param tuple argument: Argument consists of predicate function and item
iteself.
>>> filter_true((lambda x: x <= 5, 5))
... True, 5
>>> filter_true((lambda x: x > 100, 1)
... |
def none_are_none(*args) -> bool:
"""
Return True if no args are None.
"""
return not any([arg is None for arg in args]) |
def has_global(node, name):
"""
check whether node has name in its globals list
"""
return hasattr(node, "globals") and name in node.globals |
def parse_line_number(proto_dir, message_name, files):
"""
Parses the *.proto files to see on what line number the message appears.
"""
for file in files:
with open(proto_dir + '/' + file) as data_file:
content = data_file.read()
lines = content.split('\n')
message_... |
def convert_boot_type (boot_type):
"""
Convert a next boot type parameter to the string that needs to be passed to system functions.
:param boot_type: The boot type parameter passed to the command. If this is None, no conversion
is performed.
:return The string identifier for the boot typ... |
def sample_sequentials(sequential_keys, exp, idx):
"""
Samples sequentially from the "from" values specified in each key
of the experimental configuration which have sample == "sequential"
Unlike `cartesian` sampling, `sequential` sampling iterates *independently*
over each keys
Args:
se... |
def __add_concordance_counts(x, y):
"""
Adds two tuples. For example.
:math:`x + y = (x_d + y_d, x_t_{xy} + y_t_{xy}, x_t_x + y_t_x, x_t_y + y_t_y, x_c + y_c, x_n + y_n)`
:param x: Tuple (d, t_xy, t_x, t_y, c, n).
:param y: Tuple (d, t_xy, t_x, t_y, c, n).
:return: Tuple (d, t_xy, t_x, t_y, c,... |
def getErrorPage(errorcode, msg = ""):
"""\
Get the HTML associated with an (integer) error code.
"""
if errorcode == 400:
return {
"statuscode" : "400",
"data" : u"<html>\n<title>400 Bad Request</title>\n<body style='background-color: black; color: white;'>\n<... |
def parse_single_alignment(string, reverse=False, one_indexed=False):
"""
Parses a single alignment point
:param string: String representing a single alignment point, e.g. '1-42'
:param reverse: if to reverse the alignments from src-tgt to tgt-src
:param one_indexed: if the position of first word in... |
def split_type_line(type_line):
"""Splits the comment with the type annotation into parts for argument and return types.
For example, for an input of:
# type: (Tensor, torch.Tensor) -> Tuple[Tensor, Tensor]
This function will return:
("(Tensor, torch.Tensor)", "Tuple[Tensor, Tensor]")
... |
def first_existing(dictionary, keys):
"""Get the value of the first key in keys that is in the dictionary."""
try:
return next(k for k in keys if k in dictionary)
except StopIteration:
raise KeyError("None of %s is in dict!" % keys) |
def split_str(str):
"""
Splits strings
Taken from: https://stackoverflow.com/a/57109577
Parameters
----------
str
String to separate (duh!)
Returns
-------
res_arr: list
List of new strings
"""
ref_dict = {'\x07':'a', '\x08':'b', '\x0C':'f', '\n... |
def get_row_indices(all_headers, to_keep):
"""get the indices of each row"""
row_indices = []
for outer_header in to_keep:
if isinstance(outer_header, str):
row_index = all_headers.index(outer_header)
if row_index > -1:
row_indices.append(row_index)
el... |
def qcollide(Aleft, Aright, Bleft, Bright):
"""
optimised for speed.
"""
# quickest rejections first;
if Aright < Bleft:
return False
if Aleft > Bright:
return False
if Aleft <= Bright and Aright >= Bright:
return True # Bright point is within A, collision
if A... |
def is_even(i):
"""
This is a docstring, in here we describe what the function does, the input it takes and the return value
:param i: a positive int
:return: returns True if i is even, otherwise False
"""
# Notice indentation and how it tells us what expressions belong inside the function's bo... |
def format_version(major, minor, patch, prerelease=None, build=None):
"""Format a version according to the Semantic Versioning specification
:param int major: the required major part of a version
:param int minor: the required minor part of a version
:param int patch: the required patch part of a versi... |
def FindPosition(point, points):
"""Determines the position of point in the vector points"""
if point < points[0]:
return -1
for i in range(len(points) - 1):
if point < points[i + 1]:
return i
return len(points) |
def pymatmul(matrix_a, matrix_b):
"""
Implements the dot product between two matrix
:param matrix_a: first matrix
:param matrix_b: second matrix
:return: matrix product
"""
return [(a * b) for a, b in zip(matrix_a, matrix_b)] |
def queue_manager(user, extension, action):
"""queuejoin:queueleave:queuepause:queueunpause:queuetrain"""
data = {}
# if action == 'queuejoin':
# data = backend.add_to_queue(
# agent="SIP/%s" % (extension),
# queue='Q718874580',
# member_name=user.get_full_name()... |
def get_column_from_description(column_dict, description):
"""Returns the column index matching a substring of description"""
index = [value for key, value in column_dict.items() if description in key][0]
if index is None:
return
else:
return index |
def ERR_NOOPERHOST(sender, receipient, message):
""" Error Code 491 """
return "ERROR from <" + sender + ">: " + message |
def replace_oov_words_by_unk(tokenized_sentences, vocabulary, unknown_token="<unk>"):
"""
Replace words not in the given vocabulary with '<unk>' token.
Args:
tokenized_sentences: List of lists of strings
vocabulary: List of strings that we will use
unknown_token: A string repres... |
def calc_wmr(BMR, PAL):
"""Total requirement depending on PAL = physical activity level"""
return BMR * (PAL - 1) |
def turns(a, b):
"""
Finds minimum turns in a dimension where a is the minimum coordinate,
and b is the maximum coordinate, and the teacher is at the origin.
"""
if a >= 0 or b <= 0:
return (max(abs(a), abs(b)) + 1) // 2
else:
t = min(abs(a), abs(b))
return t + turns(a + ... |
def split_url_and_query(url):
"""Split the query from the url"""
try:
index = url.index('?')
except ValueError:
return url, ""
query = url[index + 1:]
url = url[:index]
return url, query |
def undulating(number):
""" Returns True if number is undulating """
if number < 100:
return False
number = str(number)
for idx in range(len(number)-2):
if number[idx] != number[idx+2]:
return False
return True |
def path_info_split(path_info):
"""
Splits off the first segment of the path. Returns (first_part,
rest_of_path). first_part can be None (if PATH_INFO is empty), ''
(if PATH_INFO is '/'), or a name without any /'s. rest_of_path
can be '' or a string starting with /.
"""
if not path_info:... |
def IsPrimeNumber(x):
""" Adjust a number is or not a prime.
Args:
x: the designated number for adjust.
Returns:
if x is prime then True, else False.
"""
if x <= 0:
return 'x should be more than 0.'
for i in range(2, x):
if x % i == 0:
return False
... |
def get_vnics_from_devices(devices):
"""Obtain vnic information."""
vnics = None
if (devices and hasattr(devices, "VirtualDevice")):
vnics = []
devices = devices.VirtualDevice
for device in devices:
if (device.__class__.__name__ in
("VirtualEthernetCard",
... |
def _has_package(mod):
"""
:param mod: Module object. Can be any of the multiple types used to
represent a module, we just check for a __package__ attribute.
:type mod: ``Any``
:return: If given module has a valid __package__ attribute.
:rtype: ``bool``
"""
return hasattr(mod, "__pac... |
def norm(value_string):
"""
Normalize the string value in an RTE pair's C{value} or C{entailment}
attribute.
"""
valdict = {"TRUE": 1,
"FALSE": 0,
"YES": 1,
"NO": 0}
return valdict[value_string.upper()] |
def init(width, height, seed):
""" initialize universe """
universe = [[]]*width
for x in range(0, height):
universe[x] = [False]*width
for coord in seed:
universe[coord[0]][coord[1]] = True
return universe |
def is_word(word):
"""check whether it is an English word."""
for item in list(word):
if item not in 'qwertyuiopasdfghjklzxcvbnm':
return False
return True |
def clean_extension(extension):
"""Return a cleaned-up extension - only applies for JPEG."""
extension_converter = {'jpeg': 'jpg'}
return extension_converter.get(extension, extension) |
def part1(polymer):
"""
React the polymer and return length
"""
reduced = False
while not reduced:
i = 0
reduced = True
while i < len(polymer)-1:
if polymer[i].lower() == polymer[i+1].lower() and polymer[i] != polymer[i+1]:
polymer.pop(i+1)
... |
def _getitem_list_list(items, keys):
"""Ugly but efficient extraction of multiple values from a list of
items.
Keys are contained in a list.
"""
filtered = []
for item in items:
row = []
for key in keys:
try:
row.append(item[key])
except ... |
def get_js(js, **kwargs):
"""Get the specified JS code."""
link = kwargs.get('link', False)
encoding = kwargs.get('encoding', 'utf-8')
if link:
return '<script type="text/javascript" charset="%s" src="%s"></script>\n' % (encoding, js)
else:
return '<script type="text/javascript">\n... |
def revision(instance):
"""Returns the etcd :class:`Revision` of an object used with a
:class:`Session`. If the object is currently *unattached* -- which means it
was not retrieved from the database with :meth:`Session.get` -- this function
returns :obj:`None`.
Args:
instance (object): Obje... |
def find_c(side1, side2, side3):
"""
Takes three side lengths an returns the largest
:param side1: int or float
:param side2: int or float
:param side3: int or float
:return: int or float
"""
list = [side1, side2, side3]
list.sort()
return list[-1] |
def get_param(item_id, params):
"""Method to get param."""
try:
param = params[item_id] if item_id in params else ''
except Exception:
return None
else:
return param |
def find_closest_positive_divisor(a, b):
"""Return non-trivial integer divisor (bh) of (a) closest to (b) in abs(b-bh) such that a % bh == 0"""
assert a>0 and b>0
if a<=b:
return a
for k in range(0, a-b+1):
bh = b + k
if bh>1 and a % bh == 0:
return bh
bh = b ... |
def fibonacci(n):
"""
Return the n_th Fibonnaci number $F_n$. The Fibonacci sequence
starts 0, 1, 1, 2, 3, 5, 8, ..., and is defined as
$F_n = F_{n-1} + F_{n-2}.$
"""
fibs = [0, 1]
for i in range(2, n+1):
fibs.append(fibs[i-1] + fibs[i-2])
return fibs[n] |
def remove_duplicate_QUBO(QUBO_storage):
"""
De-duplicates the QUBO storage list
Parameters
----------
QUBO_storage : list
List of QUBOs (each QUBO is a dictionary).
Returns
-------
unique : list
de-duplicated list.
"""
unique = []
for a in QUBO_storage:
... |
def _sorted_data(lb_node_pairs):
"""
Return HTTP request body to be sent to RCv3 load_balancer_pools/nodes API
from list of (lb_id, node_id) tuples. The returned list is sorted to allow
easier testing with predictability.
:param list lb_node_pairs: List of (lb_id, node_id) tuples
:return: List ... |
def normalize_url(url):
""" It seems some URLs have an empty query string.
This function removes the trailing '?' """
url = url.rstrip('?')
if not url.startswith("http://"):
url = ''.join(("http://", url))
return url |
def clean_generic(text: str) -> str:
"""
Cleans text without affecting semiotic classes.
Args:
text: string
Returns: cleaned string
"""
text = text.strip()
text = text.lower()
return text |
def getPrimaryRucioReplica(matched_replicas, replicas):
""" Return a replica with a proper rucio path """
sfn = ""
# start with the matched replicas list
for replica in matched_replicas:
if "/rucio/" in replica: # here 'replica' is a string
sfn = replica
break
# sea... |
def fresh_operation(op_id):
"""Create a default operation object."""
operation = {'path': '', 'headers': {}, 'header_params': {},
'path_params': {}, 'query_params': {}, 'params': {},
'files': None, 'form_data': None, 'json': None, 'id': op_id,
'dl_path': None, ... |
def _resource_id_from_record_tuple(record):
"""Extract resource_id from HBase tuple record
"""
return record[0]['resource_id'] |
def py_to_val(pyval):
"""Convert python value to ovs-vsctl value argument"""
if isinstance(pyval, bool):
return 'true' if pyval is True else 'false'
elif pyval == '':
return '""'
else:
return pyval |
def fate_table(tracks):
""" Create a fate table of all of the tracks. This is used by the MATLAB
exporter.
"""
fate_table = {}
for t in tracks:
if t.fate_label not in fate_table.keys():
fate_table[t.fate_label] = [t.ID]
else:
fate_table[t.fate_label].append(t... |
def extract_intersection_wkts(intersection):
"""
Given a intersection dict return the segment wkts
"""
return intersection['segmentStrings'][0][0] |
def is_string(val):
""" To check if a variable is a string in the HTML templates. """
return isinstance(val, str) |
def gain_com(exp, num, value):
"""Change the pmt gain in a job.
Return a list with parts for the cam command.
"""
return [
("cmd", "adjust"),
("tar", "pmt"),
("num", str(num)),
("exp", str(exp)),
("prop", "gain"),
("value", str(value)),
] |
def ImpliedArguments(fn):
"""!
@brief Check for keyword-only arguments with no default value.
"""
try:
co = fn.__code__
except AttributeError:
return ()
if co.co_kwonlyargcount == 0:
return ()
else:
kwonlyargs = co.co_varnames[co.co_argcount:co.co_a... |
def int_float(n):
""" Cast to int if there are no decimals. """
return int(n) if n == int(n) else n |
def _coerce_to_bytes(data):
""" Encoding data """
if not isinstance(data, bytes) and hasattr(data, 'encode'):
data = data.encode('utf-8')
# Don't bail out with an exception if data is None
return data if data is not None else b'' |
def center_dydx_3(x0, x1, x2, y0, y1, y2):
"""
Return...
:param x0:
:param x1:
:param x2:
:param y0:
:param y1:
:param y2:
:return: the three-point finite-difference derivative at x1.
"""
return (y0 * ((x1 - x2) /
((x0 - x1) * (x0 - x2))) +
y1 * ... |
def pip_install(package, prefix="sudo", verify=True, verification_command=None):
"""
Install a Python package using pip.
:type package: string
:param package: The package to install.
:type prefix: string
:param prefix: prefix of the pip command. It is 'sudo' by default.
:type... |
def is_verb_tag(nltk_pos_tag):
"""
Returns True iff the given nltk pos tag
is a verb.
"""
return nltk_pos_tag.startswith("V") |
def _fix_params(params):
"""For v1 api -- True is True but False is a string"""
for key, val in params.items():
if val is False or str(val).lower() == 'false':
params[key] = 'False'
elif str(val).lower() == 'true':
params[key] = True
return params |
def find_tts(prices):
"""Returns a list containing the buy day, sell day and resulting profit - finds the best days on which to buy and sell."""
buyday = 0
sellday = 0
profit = 0
for x in range(len(prices)):
for y in range(x+1, len(prices)):
if prices[x] < prices [y]:
... |
def UTh_ppm2molg(U,Th):
"""
Convert concentrations of U and Th from ppm to mol/g
Parameters
----------
U : float
U concentration (ppm)
Th : float
Th concentration (ppm)
Returns
-------
U238_molg : float
U238 (mol/g)
U235_molg : float
U235 (mol/g)... |
def parse_arguments_to_com(args):
"""
Turns the list of argv arguments that is send to a com process (by the editor) into appropriate list of strings
and lists (of topics). It is up to the node's start_exec function to create a list of argv that can be properly
parsed.
:param args: The argv ret... |
def _to_skybell_level(level):
"""Convert the given Safegate Pro light level (0-255) to Skybell (0-100)."""
return int((level * 100) / 255) |
def track_length(value):
"""Converts track length specified in seconds into a pretty string."""
seconds = int(value)
minutes, seconds = divmod(seconds, 60)
return '%i:%02i' % (minutes, seconds) |
def hcf(num1, num2):
"""
Find the highest common factor of 2 numbers
num1:
The first number to find the hcf for
num2:
The second number to find the hcf for
"""
if num1 > num2:
smaller = num2
else:
smaller = num1
for i in range(1, smaller + 1):
if ((nu... |
def status(s_dirt, s_hungry, s_mood):
"""Parameters:
s_dirt, s_hungry, s_mood zet de waardes gelijk aan 0 als deze
kleiner zijn dan 0.
Deze functie controleert of de variabelen altijd boven
de 0 zijn."""
if s_dirt < 0:
s_dirt = 0
elif s_hungry < 0:
s_hung... |
def sort_keys(times):
"""
Function to sort the times
"""
sorted_times = []
for t in times:
year = t.year
month = t.month
date = "{}.{}".format(month, year)
if date in sorted_times:
continue
else:
sorted_times.append(date)
return sor... |
def level_to_exp(level):
"""
Convert level to equivalent total EXP.
Formula: EXP := Sigma(1000 * i, 1, n)
Using Gauss's formula, this is 1000 * n(1+n)/2.
"""
return 500 * level * (1 + level) |
def prod(numbers):
"""
Find the product of a sequence
:param numbers: Sequence of numbers
:return: Their product
"""
ret = 1
for number in numbers:
ret *= number
return ret |
def strip(value: str) -> str:
"""
Strip flanking whitespace from the passed string. Used to coerce values in Cerberus validators.
:param value: the string to strip
:return: the stripped string
"""
return value.strip() |
def get_column_separator(input_):
""" Return the column separator """
""" This logic needs to be improved """
if input_.count('|') > input_.count('\t'):
return '|'
return '\t' |
def _reconstruct_sent(parsed_sentence):
"""Reconstruct sentence from CoreNLP tokens - raw sentence text isn't retained by CoreNLP after sentence splitting and processing
Args:
parsed_sentence (dict): Object containing CoreNLP output
Returns:
str: original sentence
"""
sent = ""
... |
def is_ok_url(url: str):
"""
Check doc url is valid
"""
ng_list = [
"aws-sdk-php",
"AWSAndroidSDK",
"AWSiOSSDK",
"AWSJavaScriptSDK",
"AWSJavaSDK",
"awssdkrubyrecord",
"encryption-sdk",
"mobile-sdk",
"pythonsdk",
"powershell"... |
def _format_date(pdb_date):
"""Converts dates from DD-Mon-YY to YYYY-MM-DD format."""
date = ""
year = int(pdb_date[7:])
if year < 50:
century = 2000
else:
century = 1900
date = str(century + year) + "-"
all_months = [
"xxx",
"Jan",
"Feb",
"Mar... |
def to_weight(fitness, m=100, b=1):
"""Convert from fitness score to probability weighting"""
return int(round(fitness*m + b)) |
def _reversedict(d: dict) -> dict:
"""
Internal helper for generating reverse mappings; given a
dictionary, returns a new dictionary with keys and values swapped.
"""
return {value: key for key, value in d.items()} |
def linear_threshold_reward(distance, threshold, coefficient):
"""
Linear reward with respect to distance, cut of at threshold.
:param distance: current distance to the goal
:param threshold: maximum distance at which some bonus is given
:param coefficient: NEGATIVE --> slope of the linear bonus
... |
def compDictMaps(base=10):
"""
task 0.5.25
dict. comprehension that maps each integer in the reange between the provided base
to the list of three digits that represents each integer
"""
return {i:v for i,v in enumerate([[x, y, z] for x in range(base) for y in range(base) for z in range(ba... |
def get_new_index_name(index_name, reindex_suffix):
"""Get New Index Name."""
new_index_name = index_name + reindex_suffix
return new_index_name.lower() |
def build_match_tree(abbreviation_list):
""" Build the tree used to look up abbreviations """
match_tree = {}
for word, abbreviation in abbreviation_list:
tree_node = match_tree
for letter in word[:-1]:
if letter not in tree_node:
tree_node[letter] = {}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.