content stringlengths 42 6.51k |
|---|
def _FormDestinationUri(bucket):
"""Forms destination bucket uri."""
return 'gs://{}/dependencies'.format(bucket) |
def find_index(val, array):
""" Return the index/position of element, whose value equals to val, in
array
"""
res = [i for i, v in enumerate(array) if v == val]
return res[0] |
def _plotting_formula(k, l, m):
"""
plotting function acc. to DWA-A 531 chap. 5.1.3 for the partial series
Args:
k (float): running index
l (float): sample size
m (float): measurement period
Returns:
float: estimated empirical return period
"""
return (l + 0.2) ... |
def initialize(vertices):
"""
Return initialized graph with
specifying vertex number
@type: vertices, integer
@param: vertices, number of vertices
"""
g = [None] * vertices
for i in range(0, vertices):
g[i] = []
return g |
def enforce_list(*args):
"""Make sure that inputted objects are / become lists."""
args_list = list(args)
for i, arg in enumerate(args_list):
if not isinstance(arg, list):
args_list[i] = [arg]
return args_list[0] if (len(args_list) == 1) else args_list |
def filter_unique_jvm_flags(jvm_flags):
"""filters out the always unique jvm flags from configuration comparision"""
always_unique_jvm_flags = [
'-XX:HeapDumpPath', '-Djava.io.tmpdir', \
'-Djdk.internal.lambda.dumpProxyClasses', \
'-XX:ErrorFile', '-Ddse.system_memory_in_mb',\
]
... |
def sumDigits(s):
"""
Assume s is a str
Returns the sum of the numbers in s
"""
total_sum = 0
for char in s:
try:
char = int(char)
total_sum += char
except ValueError:
pass
return total_sum |
def is_tool(name):
"""Check whether `name` is on PATH."""
from distutils.spawn import find_executable
return find_executable(name) is not None |
def output_requirements(requirements):
"""Prepare print requirements to stdout.
:param dict requirements: mapping from a project to its pinned version
"""
return '\n'.join('{0}=={1}'.format(key, value)
for key, value in sorted(requirements.items())) |
def get_cdf1(latencies):
"""Get CDF of all latencies"""
all_values = []
for k, values in latencies.items():
all_values.extend(values)
all_values.sort()
number_values = len(all_values)
p = 1.0
if number_values > 10000:
p = 10000.0 / number_values
import random
cdf_arr... |
def bytesto(size, to='m', bsize=1024):
"""convert bytes to megabytes, etc.
sample code:
print('mb= ' + str(bytesto(314575262000000, 'm')))
sample output:
mb= 300002347.946
"""
a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 }
r = float(size)
for i in ra... |
def convert_rules_to_removal(rule_array):
"""
Convert existing iptables rules to the iptables arguments needed to remove
the rules.
Args:
rule_array - An array of strings that each contain an iptables rule
"""
removal = []
for rule in rule_array:
removal.append('-D' + rule[2... |
def to_s3_uri(code_dict):
"""Constructs a S3 URI string from given code dictionary
:param dict code_dict: Dictionary containing Lambda function Code S3 location of the form
{S3Bucket, S3Key, S3ObjectVersion}
:return: S3 URI of form s3://bucket/key?versionId=version
:rtype stri... |
def list_to_str(value_list, sep=';'):
"""covert sorted str list (sorted by default) to str
value (splited by sep). This fuction is value safe, which means
value_list will not be changed.
"""
temp = value_list[:]
return sep.join(temp) |
def CalculateBoxSize(nmol, molwt, density):
"""
Calculate the size of a solvent box.
Parameters
----------
nmol : int
Number of molecules desired for the box
molwt : float
Molecular weight in g/mol
density : float
Estimated density in kg/m3 (this should be about ... |
def zipdir(path, ziph):
""" Function for putting everything under an existing folder into
a zip folder.
This function puts all the files in an existing folder into a zipped
folder and then removes it from the existing folder.
Args:
path (str): path to folder desired to be zipped
zi... |
def collatz_sequence(num):
"""collatz sequence - start with positive integer. If it's even, next term
is n/2, otherwise (3n + 1). 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1.
Always ends in 1. This will return [num, n2, n3, n4, ... , 1]
"""
foo = [num]
temp = num
while temp != 1:
if te... |
def add_prefix(inputs, prefix):
"""Add prefix for dict.
Args:
inputs (dict): The input dict with str keys.
prefix (str): The prefix to add.
Returns:
dict: The dict with keys updated with ``prefix``.
"""
outputs = dict()
for name, value in inputs.items():
output... |
def distanc(*args):
"""Calcs squared euclidean distance between two points represented by n dimensional vector
:param tuple args: points to calc distance from
:return: euclidean distance of points in *args
"""
if len(args) == 1:
raise Exception('Not enough input arguments (expected two)')
... |
def _get_size(hyper):
""" return the number of choices from 'something',
something can be either an hyper-parameter but also a constant or a tuple
This allow implicite use of list/tuple to model a choice and object to model a constant
"""
if hasattr(hyper, "size"):
return hyper.size
e... |
def find_dependents(all_specs, providers, deptype='run'):
"""
Return a set containing all those specs from all_specs that depend on
providers at the given dependency type.
"""
dependents = set()
for s in all_specs:
for dep in s.traverse(deptype=deptype):
if dep in pro... |
def _add_plus_addr(addr, accounts, issue):
"""Maybe add +owner, +cc, or +reviewer to the email address."""
acct = accounts.get(addr)
if not acct or not acct.add_plus_role:
return addr # No account set up, or didn't opt-in
username, domain = addr.split('@', 1)
if addr == issue.owner.email():
return '... |
def readable(fileobj):
"""Determines whether or not a file-like object is readable.
:param fileobj: The file-like object to determine if readable
:returns: True, if readable. False otherwise.
"""
if hasattr(fileobj, 'readable'):
return fileobj.readable()
return hasattr(fileobj, 'read'... |
def calculation_to_percentage(value: str, decimal_places: int = 10):
"""
We assume value of 1 is 100%
"""
normalized_value = float(value) * 100
if normalized_value < 1 / (10 ** decimal_places):
return "0%"
return f"{normalized_value:5f}%" |
def combine(*layers):
"""Combine layers into one list as a DGP structure.
Args:
*layers (list): a sequence of lists, each of which contains the GPs (defined by the kernel class) in that layer.
Returns:
list: a list of layers defining the DGP structure.
"""
all_layer=[]
for laye... |
def get_mo(text):
"""take string representing month or abbreviation, convert it to number"""
mo = { "january" : "1", "february" : "2", "march" : "3", "april" : "4", "may" : "5", "june" : "6",
"july" : "7", "august" : "8", "september" : "9", "october" : "10", "november" : "11", "december" : "12",
... |
def merge_dicts(list_of_dicts):
"""Merge multipe dictionaries together.
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
Args:
dict_args (list): a list of dictionaries.
Returns:
dict
"""
merge_dict = {}... |
def hexencode(rgb):
"""Transform an RGB tuple to a hex string (html color)"""
r = int(rgb[0])
g = int(rgb[1])
b = int(rgb[2])
return '#%02x%02x%02x' % (r, g, b) |
def make_data_lines(all_tags, all_bits, segbits):
"""
Formats data lines
"""
lines = []
def map_f(b):
if b < 0: return "0"
if b > 0: return "1"
return "-"
# Bit data
for tag in all_tags:
if tag in segbits.keys():
lines.append("".join(map(map_f, s... |
def _ensure_static_manual(args):
"""Set linkopts and tags keys of args for static linking and manual testing.
Args:
args: A map representing the arguments to either cc_binary or cc_test.
Returns:
The given args modified for linking and tagging.
"""
# Fully static so the test can move ... |
def complete(a, b, distance_function):
"""
Given two collections ``a`` and ``b``, this will return the distance of the
points which are farthest apart. ``distance_function`` is used to determine
the distance between two elements.
Example::
>>> single([1, 2], [3, 4], lambda x, y: abs(x-y))... |
def bisect_last_true(arr):
"""Binary search for last True occurrence."""
lo, hi = -1, len(arr)-1
while lo < hi:
mid = lo + hi + 1 >> 1
if arr[mid]: lo = mid
else: hi = mid - 1
return lo |
def check_auth(username, password):
"""
This function is called to check if a username /password combination is
valid.
"""
return username == 'admin' and password == 'secret' |
def neighbours(pos):
""" Gets coordinates of neighbour coordinates to a coordinate. """
return [
(pos[0], pos[1] + 1),
(pos[0] + 1, pos[1]),
(pos[0], pos[1] - 1),
(pos[0] + -1, pos[1])
] |
def sizeof_fmt(num, suffix='B'):
"""Returns human-readable file size
Supports:
* all currently known binary prefixes
* negative and positive numbers
* numbers larger than 1000 Yobibytes
* arbitrary units (maybe you like to count in Gibibits!)
Example:
--------
>>> sizeof_fmt(16... |
def isint(s):
"""
Method to check if a string is an integer
Parameters
----------
s : str
Returns
-------
bool
"""
try:
int(s)
return True
except (TypeError, ValueError):
return False |
def check_indent(docstring, context, is_script):
"""The entire docstring should be indented same as code.
The entire docstring is indented the same as the quotes at its
first line.
"""
if (not docstring) or len(eval(docstring).split('\n')) == 1:
return
non_empty_lines = [line for line ... |
def getsize(*objs):
"""
sum size of object & members.
https://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python
"""
import sys
from types import ModuleType, FunctionType
from gc import get_referents
# Custom objects know their class.
# Function obj... |
def update_config(config_file, new_log_file):
"""
Helper function to update log config json
"""
config_file['handlers']['file_handler']['filename'] = new_log_file
config_file['handlers']['info_handler']['filename'] = new_log_file
return config_file |
def bytes_to_unicode(bstr):
"""
Return Unicode value for supplied (UTF-8 encoding) bytes.
"""
return bstr.decode('utf-8') |
def get_field_info(field_file):
"""
A utility for easily extracting information about the host model from a
Django FileField (or subclass). This is especially useful for when you want
to alter processors based on a property of the source model. For example::
class MySpec(ImageSpec):
... |
def _position_is_valid(position):
"""
Checks if given position is a valid. To consider a position as valid, it
must be a two-elements tuple, containing values from 0 to 2.
Examples of valid positions: (0,0), (1,0)
Examples of invalid positions: (0,0,1), (9,8), False
:param position: Two-element... |
def encode_count_header(count):
"""
Generate a header for a count HEAD response.
"""
return {
"X-Total-Count": count,
} |
def extract_items(topitems_or_libraryitems):
"""Extracts a sequence of items from a sequence of TopItem or LibraryItem objects."""
list = []
for i in topitems_or_libraryitems:
list.append(i.get_item())
return list |
def count(A,target):
"""invoke recursive function to return number of times target appears in A."""
def rcount(lo, hi, target):
"""Use recursion to find maximum value in A[lo:hi+1]."""
if lo == hi:
return 1 if A[lo] == target else 0
mid = (lo+hi)//2
left = rcount(lo... |
def get_cls_dict(category_list):
"""Get the class ID to name translation dictionary."""
return {i: n for i, n in enumerate(category_list)} |
def sigWxFcn(table, doc):
"""Create and return partial key for SIGMET, AIRMET, and CWA messages.
Args:
table (str): Database table.
doc (dict): Message from database.
Returns:
str: With partial key for ``vectorDict``.
"""
return doc['type'] + '~' + doc['_id'] + '/' + st... |
def create_empty_grid(dimensions):
""" Creates an empty grid with the given dimensions.
dimensions[0] -> lines
dimensions[1] -> columns
"""
return [x[:] for x in [[0]*dimensions[1]]*dimensions[0]] |
def tan2cos(tan: float) -> float:
"""returns Cos[ArcTan[x]] assuming -pi/2 < x < pi/2."""
return (tan ** 2 + 1) ** (-0.5) |
def _sizeParser(argstr):
"""Parse the size argument."""
size = [int(float(siz)) for siz in argstr.split("x")]
if len(size) == 1: # If one value was given, assume cube
return size * 3
return size |
def ratio(fitness1, fitness2):
"""Fixation probability equals the ratio of new fitness over old fitness"""
sij = fitness2 / fitness1
return sij |
def parse_metadata_json(data):
""" Function to parse the json response from the metadata or the
arxiv_metadata collections in Solr. It returns the dblp url.
docs is a list of one result, so this is obtained by docs[0].get('url')"""
# docs contains authors, title, id generated by Solr, url
docs = da... |
def getPhone(phone):
""" Method returns formed phone information
:param phone: raw phone number
:return: formed phone number
"""
message = 'Phone:' + phone
return message |
def compute_qtype_acc(predictions, qtype, key_name='vqa_ans'):
"""
Compute QA accuracy for qtype
"""
acc, cnt = 0, 0
for entry in predictions:
if entry['type'] == qtype:
if entry[key_name] == entry['answer']:
acc += 1
cnt += 1
return acc / (cnt+1e-5), cnt |
def format_number(num):
"""Return a number representation with comma separators."""
snum = str(num)
parts = []
while snum:
snum, part = snum[:-3], snum[-3:]
parts.append(part)
parts.reverse()
return ",".join(parts) |
def is_index_like(s):
""" Looks like a Pandas Index """
typ = type(s)
return (
all(hasattr(s, name) for name in ("name", "dtype"))
and "index" in typ.__name__.lower()
) |
def translate_targets_to_type_id(targets_translation_file, targets):
"""
Obtain the translated targets using the targets_translation_file
"""
# Parse the targets_translation_file
# Fill new with the translations
new={}
with open(targets_translation_file, 'r') as targets_trans_fd:
for... |
def longest_increasing_subsequence(sequence: list) -> list:
"""
calculates the longest increasing subsequence from the given list of integers. items within the result
have the same relative order to each other as in the given input sequence, however some items may be removed in
order to create an increa... |
def rendered_source_for_lang(page_pk, lang):
"""Create cache key for rendered page source based on current language"""
return 'powerpages:rendered_source_lang:{0}:{1}'.format(page_pk, lang) |
def flow_partitioning(Lambda, Qs_out, Qo_out, W, X, Xc):
"""Partition the outflows from soil and overland stores.
Calculates the correct partitioning of outflows from the soil and
overland stores into contributions going to the downstream cell
and/or the channel store of the current cell (if this exist... |
def _make_row(row, conversions):
"""Builds a python native row from proto3 over bsonrpc row."""
converted_row = []
offset = 0
for i, l in enumerate(row['Lengths']):
if l == -1:
converted_row.append(None)
elif conversions[i]:
converted_row.append(conversions[i](row['Values'][offset:offset+l])... |
def extract_elements_paths(elements):
""" """
paths = list()
for el in elements:
if el.is_main_profile_element:
continue
if len(el.definition.types) == 0:
continue
if el.path.endswith("[x]"):
assert len(el.definition.types) > 1
for ty... |
def _getParameter(name, index, args, kwargs, default=None):
"""Find a parameter in tuple and dictionary arguments a function receives"""
param = kwargs.get(name)
if len(args) > index:
if param:
raise TypeError("Parameter '%s' is specified twice" % name)
param = args[index]
r... |
def express_step_from_error(
error: float, max_forth_derivative: float, low: float, high: float) -> float:
"""Get step from known integration error using it's formula.
Args:
error: precalculated integration error.
max_forth_derivative: precalculated value.
high: right range boun... |
def count_number_of_arguments(*args):
"""counts number of arguments passed to fumction"""
sum = 0
for arg in args:
sum += 1
return sum |
def get_in(obj, lookup, default=None):
""" Walk obj via __getitem__ for each lookup,
returning the final value of the lookup or default.
"""
tmp = obj
for l in lookup:
try: # pragma: no cover
tmp = tmp[l]
except (KeyError, IndexError, TypeError): # pragma: no cover
... |
def get_live_data(match_info, event):
"""input: dictionary | output: dictionary updated if match is live"""
for stat in ['downDistanceText', 'shortDownDistanceText', 'possession', 'possessionText', 'isRedZone']:
try:
match_info[stat] = event["competitions"][0]['situation'][stat]
exce... |
def is_simple_callable(obj) -> bool:
"""
:param obj: Any object
:return: true if the object is callable but class constructor.
"""
return callable(obj) and not isinstance(obj, type) |
def undirected_edge_name(u, v) -> str:
"""
:return The name of an undirected edge as "(u,v)" with u <= v.
"""
u_i, v_i = int(u), int(v)
if u_i > v_i:
u_i, v_i = v_i, u_i
return f"({u_i},{v_i})" |
def secure_string_comparison(s1, s2, ord=ord):
"""Securely compare 2 strings in a manner which avoids timing attacks."""
if len(s1) != len(s2):
return False
total = 0
for x, y in zip(s1, s2):
total |= ord(x) ^ ord(y)
return total == 0 |
def format_backlog(backlog):
""" format and return given subscription backlog into dictionary """
return {
"transfer_id": backlog["transfer_id"],
"client_id": backlog["client_id"],
"block_id": backlog["block_id"]
} |
def _parse_findings(findings, region):
"""
Returns relevant information from AWS Security Hub API response.
Args:
findings (list): AWS Security Hub response.
region (str): AWS region.
Returns:
List[dict]: List of compliance information dictionaries.
"""
new_findings = [... |
def check_your_guess(ans, your_guess, turns, history):
"""
The function checks whether the format of user's guess is correct
and calculates how many left chances (depends on the format).
:param ans: str, the answer
:param your_guess: str, the letter user guesses
:param turns: int, how many left ... |
def get_confidence(imgfilename):
"""
1003_c60.jpg -> c6
"""
if not imgfilename:
return ''
return 'c' + imgfilename.split('/')[-1][0:1] |
def ip_parser(ip):
"""IP can be in the form of `ip-x-x-x-x`.
function will return it to `x.x.x.x` format
if it's not an ip, will return `ip` arg back.
Args:
ip (str): ip to parse
Returns:
str: parsed ip indicator
"""
if ip.lower().startswith("ip-"):
return ip.lower... |
def pip_wn(p, poly):
"""2D point inclusion: returns True if point is inside polygon (uses winding number algorithm).
arguments:
p (numpy array, tuple or list of at least 2 floats): xy point to test for inclusion in polygon
poly (2D numpy array, tuple or list of tuples or lists of at least 2 float... |
def probe(value):
"""
Factorization of n by probing.
:param n: value to factorize.
:returns: all proper divisors of n.
>>> probe(10)
[1, 2, 5, 10]
>>> probe(12)
[1, 2, 3, 4, 6, 12]
"""
value = abs(value)
limit = value // 2
divisors = [1]
divisor = 2
while divis... |
def object_types(object_type):
"""return a dictionary of jamf API objects and their corresponding URI names"""
# define the relationship between the object types and their URL
# we could make this shorter with some regex but I think this way is clearer
object_types = {
"package": "packages",
... |
def format_CALL_FUNCTION(argc):
"""argc indicates the number of positional arguments"""
if argc == 1:
plural = ""
else:
plural = "s"
return ("%d positional argument%s" % (argc, plural)) |
def process_add_quotes_around_values(param, process_args=None):
"""
Add a single quote character around each element of a comma
separated list of values
"""
params_list = param.split(',')
for index, elem in enumerate(params_list):
if not elem.startswith("'"):
elem = "'" + ele... |
def get_value_of_bills(denomination, number_of_bills):
"""
:param denomination: int - the value of a bill.
:param number_of_bills: int - amount of bills you received.
:return: int - total value of bills you now have.
"""
total_value = denomination * number_of_bills
return total_va... |
def int_array_to_hex(iv_array):
"""
Converts an integer array to a hex string.
"""
iv_hex = ''
for b in iv_array:
iv_hex += '{:02x}'.format(b)
return iv_hex |
def get_change(current: float, previous: float) -> float:
"""Calculates the percentage change between the current value and previous value.
Args:
current: Current price of stock.
previous: Previous price of stock.
Returns:
float:
Returns the difference percentage.
"""
... |
def GetTreeishName(resolution):
"""Gets the name of the tree-ish (branch, tag or commit)."""
if resolution['type'] == 'branch':
return resolution['branch']
if resolution['type'] in ('version', 'tag'):
return resolution['tag']
return resolution['commit'] |
def time_formatter(num, size):
"""Adjust a number to a specific size using padding leading zeroes if
needed.
Arguments:
num (int): the number that will be formatted.
size (int): the number of characters need in the string representation
of the num.
Returns:
... |
def make_album1(name, album, sta=''):
"""Display the singer's name and albums, the optional album numbers"""
# Define the dictionary
zj1 = {'n_name1': name, 'a_album1': album}
# if sta is true, add the sta into the dictionary
if sta:
zj1['sta'] = sta
# Return the dictionary
return zj... |
def get_next_contig(contig_list):
"""
Removes and returns the right-hand end of the first contig in a list of contig tuples
(e.g. from order_chromosomal_contigs()), adding a fiveprime_ or threeprime_ prefix
depending on the direction given in the second item of the tuple
"""
next_contig_tuple ... |
def lines(a, b):
"""Return lines in both a and b"""
lines = []
# Split string a into lines: \n
# For each lines:
for line in a.split("\n"):
# Split string b into lines: \n
# Check if line from a appears in b
if line in b.split("\n"):
# Check if the line is empty
... |
def get_result_path_for_dataset_and_model(dataset_name, model, dir='../results'):
"""
Returns Result path for Cross Validation
:param dataset_name:
:param model:
:param dir:
:return:
"""
return f'{dir}/{dataset_name}/{model}_Folds' |
def sort_dict_by_value(inputdict):
"""Sort a dictionary by its values.
:param inputdict: the dictionary to sort
:type inputdict: dict
:return: list of keys sorted by value
:rtype: list
"""
items = [(v, k) for k, v in inputdict.items()]
items.sort()
items.reverse()
items = [k... |
def saturated_density(rhog, rhofl, phi):
"""Saturated bulk density
Args:
rhog (array-like): dry frame grain density
rhofl (array-like): fluid density
phi (array-like): porosity (frac)
Returns:
(array-like): saturated rock bulk density (rhob)
"""
return rh... |
def sort_response(response_dict, *args):
"""
Used in tests to sort responses byt tw or more fields.
For example if rersponse includes experimentKey and FeatureKey, the function
will sort by primary and secondary key, depending which one you put first.
The first param will be primary sorted, second s... |
def is_zh(ch):
"""return True if ch is Chinese character.
full-width puncts/latins are not counted in.
"""
x = ord(ch)
# CJK Radicals Supplement and Kangxi radicals
if 0x2e80 <= x <= 0x2fef:
return True
# CJK Unified Ideographs Extension A
elif 0x3400 <= x <= 0x4dbf:
retu... |
def get_board_dict(data):
"""Convert the data dictionary into a format that is used by the
print_board function.
"""
board_dict = {}
for type, tokens in data.items():
if type == "upper":
for tok in tokens:
board_dict[(tok[1], tok[2])] = "({})".format(tok[0].uppe... |
def check_for_duplicate_ids(id_map) -> bool:
"""
Checks for duplicate ids in the map
:param id_map: The id_map generated by build_id_dict()
:return: True if duplicate non-null id's exist, false otherwise
"""
used_ids = set()
for sheet in id_map.keys():
for row in id_map[sheet].keys()... |
def _elide_string_middle(text, max_length):
"""Replace the middle of the text with ellipses to shorten text to the desired length.
Args:
text: [string] Text to shorten.
max_length: [int] Maximum allowable length of the string.
Returns:
[string] The elided text, e.g. "Some really lo... |
def parse_condition(condition):
"""
Parses a condition for cond_labels
>>> parse_condition("review.approval > 3")
['review.approval', '3']
"""
elems = condition.split(">")
if len(elems) != 2:
raise ValueError("Unable to parse ")
return [e.strip() for e in elems] |
def penn_to_wn(tag):
""" Convert between a Penn Treebank tag to a simplified Wordnet tag """
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if tag.startswith('J'):
return 'a'
if tag.startswith('R'):
return 'r'
return None |
def _sorting_key(s):
"""Numerical/lexicographical sorting.
"""
try:
val = int(s)
norm = "{:010}".format(val)
except ValueError:
norm = s
return norm |
def formatear_camino(pila):
"""Convierte una lista de ciudades en un string separado por ->"""
return " -> ".join(map(str,pila)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.