content stringlengths 42 6.51k |
|---|
def get_signature_algorithm(alg_type, alg_hash):
"""
Returns signature algorithm for ACM PCA
Args:
isEC: true if Elliptic Curve certificate
alg_type: Hash Algorithm from cryptography package to find
Raises:
ValueError: Algorithm type not supported
"... |
def find_index_larger(times, ref_time):
"""Returns the index of times whose value is just larger than ref_time
Args:
times (list): A list of floats denoting a datestring in seconds
ref_time (float): A input date in seconds
Returns:
int: the index which is just larger than ref_time
... |
def trans_color(color, alpha):
"""
Makes solid color semi-transparent.
Returns:
(int, int, int, int)
Red, green, blue and alpha channels.
"""
if color[3] != 1.:
return color
return color[0], color[1], color[2], alpha |
def booleanise(b):
"""Normalise a 'stringified' Boolean to a proper Python Boolean.
ElasticSearch has a habit of returning "true" and "false" in its
JSON responses when it should be returning `true` and `false`. If
`b` looks like a stringified Boolean true, return True. If `b`
looks like a str... |
def cartezian(*vectors):
"""Compute Cartesian product of passed arguments
"""
ret = ret_old = [(v,) for v in vectors[0]]
for vec in vectors[1:]:
ret = []
for v in vec:
for r in ret_old:
ret.append(r+(v,))
ret_old = ret
return ret |
def queue_dict(system_id):
"""A queue represented as a dictionary."""
return {
"name": "echo.1-0-0.default",
"system": "echo",
"version": "1.0.0",
"instance": "default",
"system_id": system_id,
"display": "foo.1-0-0.default",
"size": 3,
} |
def get_position_name(position):
"""
get_position_name()
Returns position name based on the index (e.g., "first" for 0).
Required args:
- position (int): position number type
Returns:
- (str): position name
"""
position_names = [
"first", "second", "third", "f... |
def get_resource_filename(path):
"""A uniform interface for internal/open-source filenames."""
return './' + path |
def counting_sort_2(arr):
"""This is optional, and returns the sorted array, and doesn't go all the
way to 100."""
minimum_value = 100
maximum_value = 0
for item in arr:
if item < minimum_value:
minimum_value = item
elif item > maximum_value:
maximum_value = i... |
def find_remove_domain_ids(domain, ix2pred):
""" finds the relation types within the target domain """
ids = []
for key, value in ix2pred.items():
value_ = value.split("/")[0]
if value_ in [domain]:
ids.append(key)
return ids |
def floatToString3(f: float) -> str:
"""Return float f as a string with three decimal places without trailing zeros
and dot.
Intended for places where three decimals are enough, e.g. node positions.
"""
return f"{f:.3f}".rstrip("0").rstrip(".") |
def _format_publisher(value: str) -> dict:
""" Publisher requires special formatting. """
results = {}
# for those cases where Curate has a list, choose the first string in that list.
if isinstance(value, list):
for each_value in value:
value = each_value
break
if va... |
def get_bucket_config(config, bucket_name):
"""
Pulls correct bucket config from application config based on name/alias.
Args:
config(dict)
bucket_name(string): bucket name or bucket reference name
Returns:
dict | None: config for bucket or None if not f... |
def prior(mc):
"""This is used to check that only samples within the above ranges are
evaluated in the likelihood function."""
mc_min, mc_max = 0., 40.
if (mc >= mc_min) and (mc <= mc_max):
return 1
else:
return 0 |
def correlate(answer, guess):
"""Return the matching pattern for 'guess' at 'answer'.
Returns a string of N characters:
. = letter of guess does not occur in answer
O = letter of guess occurs in answer but not in the right place
X = letter is in the right place.
Because O only counts for letters th... |
def get_max_key(d):
"""Return the key from the dict with the max value."""
return max(d, key=d.get) |
def compile_playable_podcast1(playable_podcast1):
"""
@para: list containing dict of key/values pairs for playable podcasts
"""
items = []
for podcast in playable_podcast1:
items.append({
'label': podcast['title'],
'thumbnail': podcast['thumbnail'],
'path... |
def sim(nodes1, nodes2):
"""
Parameters
----------
nodes1: Top K biomarkes of GNN Structure 1.
nodes2: Top K biomarkes of GNN Structure 2.
Description
----------
Returns the overlap ratio between Top K biomarkes of two GNN architectures.
"""
counter = 0
for i i... |
def get_message(ftp_socket):
"""
goal: receive a message
type: (socket) -> string
"""
if ftp_socket:
return ftp_socket.recv(1024).decode() |
def is_list_value(value):
"""
Check if an object is a list
:param value:
:return:
"""
return isinstance(value, list) |
def _translate_keyname(inp):
"""map key names in settings file to key names in HotKeys
"""
convert = {'Escape': 'Esc', 'Delete': 'Del', 'Return': 'Enter',
'Page_up': 'PgUp', 'Page_down': 'PgDn', 'NUMPAD_ENTER': 'NumEnter'}
if inp in convert:
out = convert[inp]
else:
ou... |
def interpolate_range(a,b,s=5):
""" Generate consecutive values list between two numbers with optional step (default=5)."""
if (a == b):
return [a]
else:
mx = max(a,b)
mn = min(a,b)
result = []
# inclusive upper limit. If not needed, delete '+1' in the line below
... |
def is_queen_under_attack(col, queens):
"""
:param col: int
Column of queen to test
:param queens: list of tuple of int
List of coordinates of other queens
:return: boolean
True if and only if queen in given position is under attack
"""
left = right = col
for coords ... |
def project(x, meta):
""" project 3D to 2D for polygon clipping
"""
proj_axis = max(range(3), key=lambda i: abs(meta['normal'][i]))
return tuple(c for i, c in enumerate(x) if i != proj_axis) |
def strip_prefix(full_string, prefix):
"""
Strip the prefix from the given string and return it. If the prefix is not present
the original string will be returned unaltered
:param full_string: the string from which to remove the prefix
:param prefix: the prefix to remove
:return: the string wit... |
def get_dates(yearstring):
"""
Given a [yearstring] of forms
year1
year1-year2
year1,year2,year3
year1-year2,year3-year4
Creates tuples of dates
"""
years = []
for subset in yearstring.split(','):
if subset == 'default':
years.append('default')
con... |
def _GenerateAlignedHtml(hyp, ref, err_type):
"""Generate a html element to highlight the difference between hyp and ref.
Args:
hyp: Hypothesis string.
ref: Reference string.
err_type: one of 'none', 'sub', 'del', 'ins'.
Returns:
a html string with
- error of hyp shown in "(hyp)"
- e... |
def format_interval(seconds):
"""
Format an integer number of seconds to a human readable string.
"""
units = [
(("week", "weeks"), 604800),
(("day", "days"), 86400),
(("hour", "hours"), 3600),
(("minute", "minutes"), 60),
# (('second', 'seconds'), 1)
]
re... |
def make_simple_string(m, n):
"""
What comes in:
-- a positive integer m
-- a positive integer n that is >= m
What goes out: Returns the STRING whose characters are
m, m+1, m+2, ... n,
each with a '-' character after it,
where m and n are the given arguments.
Side effe... |
def should_reduce_batch_size(exception: Exception) -> bool:
"""
Checks if `exception` relates to CUDA out-of-memory, CUDNN not supported, or CPU out-of-memory
Args:
exception (`Exception`):
An exception
"""
_statements = [
"CUDA out of memory.", # CUDA OOM
"cuDN... |
def make_unique(indices):
"""
Performs cyclic permutation of the index tuple(i, j, k), such that the first index is the one with the lowest value.
:param indices:
:return:
"""
i = indices[0]
j = indices[1]
k = indices[2]
if i < j and i < k:
return i, j, k
if j < i and ... |
def start_of_chunk(prev_tag, tag, prev_type, type_):
"""Checks if a chunk started between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_start: boolean.
"""... |
def _get_keywords_with_score(extracted_lemmas, lemma_to_word):
"""Get words of `extracted_lemmas` and its scores, words contains in `lemma_to_word`.
Parameters
----------
extracted_lemmas : list of (float, str)
Given lemmas with scores
lemma_to_word : dict
Lemmas and corresponding w... |
def u64(x):
"""Unpacks a 8-byte string into an integer (little endian)"""
import struct
return struct.unpack('<Q', x)[0] |
def minimal_generalizations_cons(h,d):
"""returns all minimal generalizations of h that are consistent
with positive example d"""
generalizations=set()
mg=[f for f in h]
for i,f in enumerate(h):
if f!=d[i]:
if f!="0":
mg[i]="?"
else:
mg... |
def get_vuart_id(tmp_vuart, leaf_tag, leaf_text):
"""
Get all vuart id member of class
:param leaf_tag: key pattern of item tag
:param tmp_vuart: a dictionary to store member:value
:param leaf_text: key pattern of item tag's value
:return: a dictionary to which stored member:value
"""
if... |
def check_digit10(firstninedigits):
"""Check sum ISBN-10."""
# minimum checks
if len(firstninedigits) != 9:
return None
try:
int(firstninedigits)
except Exception: # pragma: no cover
return None
# checksum
val = sum(
(i + 2) * int(x) for i, x in enumerate(rev... |
def build_share2handleindex_dict(file_handles: list) -> dict:
""" given list of open file handles, create a dictionary relating share_num part to index within file_handles list"""
dict_out = {}
for i, fh in enumerate(file_handles):
name = fh.name # ='C:\BsbEtl\OUT\By_Share\120470.ETR\120470.ETR.CS... |
def diffNumAbs(arg1: int, arg2: int) -> int:
"""
The function takes two arguments arg1 and arg2, both int.
The function as result returns the absolute value of the difference of the two numbers feeded as arguments.
Example :
>>> diffNumAbs(4,6)
2
>>>
"""
res... |
def parse_numeric_range(string, base=10):
"""
Expand a numeric range (continuous or not) into a decimal or
hexadecimal list, as specified by the base parameter
'0-3,5' => [0, 1, 2, 3, 5]
'2,8-b,d,f' => [2, 8, 9, a, b, d, f]
"""
values = list()
for dash_range in string.split(','):
... |
def backward_elimination(variables, train_model, score_model, verbose=False):
""" Variable selection using backward elimination
Input:
variables: complete list of variables to consider in model building
train_model: function that returns a fitted model for a given set of variables
... |
def calc_deadtime(
exposure: float, readout_time: float, frequency_accuracy: float
) -> float:
"""Given a fixed exposure time, and a crystal frequency accuracy, what should the
time between trigger rising edges be"""
period = exposure + readout_time
period += frequency_accuracy * period / 1000000
... |
def _should_process_segment(seg, segname):
"""Check if we should process the specified segment."""
return segname.endswith('__DATA_CONST.__mod_init_func') or \
segname == '__DATA.__kmod_init' |
def to_hash(key, length=10):
"""Convert key to hash value.
Args:
key (:obj:): key value.
length (int): length of hash value.
Returns:
str: hash value of key.
"""
try:
return abs(hash(key)) % (10 ** length)
except TypeError:
return abs(hash(str(key))) % (... |
def get_project_group_name(project_uuid):
"""Return project user group name"""
return 'omics_project_{}'.format(project_uuid) |
def dataset_minmax(dataset):
""" Identifica maior e menor valor para cada coluna do dataset.
@param dataset: Conjunto de dados
@type dataset: [[float,...],...]
@return: Retorna uma lista com os valores maximos e minimos de cada coluna
@rtype: [[float,float],...]
"""
min... |
def resource_filter(value, resource, field='displayName'):
""" Given a mapping (resource), gets the data at resource[field] and
checks for equality for the argument value. When field is 'name', it is
expected to look like 'organization/1234567890', and returns only the
number after the slash.
... |
def dotProduct(list1, list2):
"""
This function determines the dot product of two lists
:param list list1: input list 1
:param list list2: input list 2
:return int dp: calculated dot product (could also be type float)
"""
# Exit function if lengths are not the same
if len(list1) != len(... |
def interface(host):
"""Return an IP address for a client connection given the server host.
If the server is listening on '0.0.0.0' (INADDR_ANY)
or '::' (IN6ADDR_ANY), this will return the proper localhost.
"""
if host == '0.0.0.0':
# INADDR_ANY, which should respond on localhost.
r... |
def parse_date(date):
"""Parse date int string into to date int (no-op)."""
if date is None:
return 0
return int(date) |
def as_snake_case_prefix(name):
""" Convert PascalCase name into snake_case name"""
outname = ""
for c in name:
if c.isupper() and len(outname) > 0:
outname += '_'
outname += c.lower()
return outname + ('_' if name else '') |
def convert_slope_intercept_to_line(y1, y2 , line):
"""
Fetching end coordinates from line from equation : y = mx + c
"""
if line is None:
return None
slope, intercept = line
x1 = int((y1- intercept)/slope)
y1 = int(y1)
x2 = int((y2- intercept)/slope)
y2 = int(y2)
... |
def say_hello_ingestion(to):
"""
this method will say hello to the person named 'to'
params:
======
to: str, name of the person to which greetings is made
return: 1 on success
"""
#print('hello there {}'.format(to))
return 'hello there {} - ingestion'.format(to) |
def invert_dict(d):
"""
Invert dictionary by switching keys and values.
Parameters
----------
d : dict
python dictionary
Returns
-------
dict
Inverted python dictionary
"""
return dict((v, k) for k, v in d.items()) |
def P_otc6486(H, D, gamma, c):
""" Returns the uplift resistance of cohesive materials.
OTC6486 - Equation (7)
"""
return gamma * H * D + 2 * H * c |
def iallval(t):
"""Recursively promote and compute allvals """
if t:
return [t.allval()] + iallval(t.promote())
else:
return [] |
def counter_delta(a, b):
"""Gives a delta value between two counter values.
Works with either 32-bit or 64-bit counter, but both
arguments should be the same type.
"""
d = b - a
if (d < 0):
d = d + 2**32
if (d <= 0):
d = d + 2**64 - 2**32
return d |
def nrd(a, b, p):
""" one step of non restoring division algorithm """
return(bin(int(str(a),2)+int(str(b),2)*2**p)) |
def dias_para_segundos(dias, horas, minutos, segundos):
""" Recebe uma data em dias com horas, minutos e segundos, e retorna
a data em segundos"""
dias_para_segundos = dias*86400
horas_para_segundos = horas*3600
minutos_para_segundos = minutos*60
segundos_para_segundos = segundos*1
soma = di... |
def _to_boolean(string):
"""
Parses the given string into a boolean. If its already a boolean, its
returned unchanged.
This method does strict parsing; only the string "True" returns the boolean
True, and only the string "False" returns the boolean False. All other
values throw a ValueError.
... |
def nonelist(somelist):
"""Checks if something is a NoneList"""
print(somelist)
return (
somelist is None
or not isinstance(somelist, list)
or len(somelist) == 0
or all(i is None for i in somelist)
) |
def is_x_a_square(x: int) -> bool:
"""Is x a square number?"""
if x == 0:
return False
left = 1
right = x
while left <= right:
mid = left + (right - left) // 2
if mid ** 2 == x:
return True
elif mid ** 2 < x:
left = mid + 1
else:
... |
def get_params(string_in, separator=' ', defaultmissing='-', params_to_get=3):
"""
Split string using 'separator' into required number of parameters. Fulfill missing parameters with 'defaultmissing'
Current limitation: hardcoded return always 3 of them
"""
rtr = str(string_in).split(separator)
... |
def func_str_str(x: str) -> str:
"""Docstring for func_str_str"""
return x.upper() |
def converter_coordenadas(coordenadas):
"""
Retorna a linha, coluna e diagonal de uma coordenada
Parametros:
coordenadas (tuplo)
Retorna:
linha (int): linha correspondente a coordenada
coluna (int): coluna correspondente a coordenada
diagonal (int, tuplo ... |
def wrap(string, char="'"):
"""Wrap a string in a specified character.
Parameters
----------
string : str
Input string.
char : str
The character to wrap around the string.
Returns
-------
str
The input string wrapped in single quotes.
"""
return char + ... |
def versioned_item_expression(
item_version: int, item_version_key: str = "item_version", id_that_exists: str = ""
) -> dict:
"""Assembles a DynamoDB ConditionExpression with ExprAttrNames and
Values that will ensure that you are the only caller of
versioned_item_diffed_update that has updated this item... |
def evaluate_cards_to_take(laid_card, cards_to_take=0):
"""
Function used to evaluate how many cards have to be taken as a punish.
:param laid_card: tuple with last played card
:param cards_to_take: integer value with earlier punishment
:return: integer value with punishment after card played
""... |
def convert_shell_operation(test):
"""shell-operation superseded by run-bash-script"""
cmd = test['args'].pop('command')
test['args']['source'] = cmd.strip()
test['type'] = 'run-bash-script'
return test |
def greater(actual_value, lower_limit):
"""Assert that actual_value is greater than lower_limit."""
result = actual_value > lower_limit
if result:
return result
else:
raise AssertionError(
"{!r} is LESS than or EQUAL to {!r}".format(
actual_value, lower_limit
... |
def get_number_and_percent(line):
"""
Parses cutadapt line containing a number (string) and returns
number typecasted to int, as well as a percentage (float), as a list.
:param line: basestring
:return line: list
"""
line = [x.strip() for x in line.strip().split(":")]
line = [line[0]] ... |
def get_health(_, __):
"""
Check for the health of the service.
"""
return {"status": "OK"} |
def _function_wrapper(args_tuple):
"""Function wrapper to call from multiprocessing."""
function, args = args_tuple
try:
return function(*args)
except KeyboardInterrupt:
pass |
def my_sqrt(num, epsilon=1e-6, maxiter=1e6):
"""Return square root of num using Newton Raphson method"""
x0, x1 = 0, 1
cnt = 0
while abs(x1 - x0) > epsilon:
x0, x1 = x1, 0.5*(x1 + num/x1)
cnt += 1
if cnt == maxiter: raise Exception("Max iteration reached")
return x1 |
def unique(seq):
"""
Return unique elements of a list, preserving order
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] |
def intersection_of(lhs, rhs):
"""
Intersects two posting lists.
"""
i = 0
j = 0
intersection = []
while (i < len(lhs) and j < len(rhs)):
if (lhs[i] == rhs[j]):
intersection.append(lhs[i])
i += 1
j += 1
elif (lhs[i] < rhs[j]):
... |
def hex2rgb(h):
""" Convert a hex string or number to an RGB triple """
# q.v. https://git.io/fh9E2
if isinstance(h, str):
return hex2rgb(int(h[1:] if h.startswith('#') else h, 16))
return (h >> 16) & 0xff, (h >> 8) & 0xff, h & 0xff |
def com_arr_str(x,y):
"""This Function return (x intersection y) U ('[',']',',',"'",' ')` """
return [var for var in x if var in y and not var in ('[',']',',',"'",' ')] |
def defaultparamsfunc(curlag, sensdict, simparams):
"""
Just a pass through function.
"""
return(curlag, sensdict, simparams) |
def generate_bigrams(x):
"""Token processor for pytorch model to generate bigrams from word token list"""
n_grams = set(zip(*[x[i:] for i in range(2)]))
for n_gram in n_grams:
x.append(' '.join(n_gram))
return x |
def add_function(x,y):
""" This function will add x to y, and return the sum"""
z = x + y
return(z) |
def _short_name(name):
# type: (str)->str
"""
from my_package.sub_package -> m.s
"""
return ".".join(n[0] if n else n for n in name.split(".")) |
def DNI(seed_set_cascades):
"""
Measure the number of distinct nodes in the test cascades started of the seed set
"""
combined = set()
for i in seed_set_cascades.keys():
for j in seed_set_cascades[i]:
combined = combined.union(j)
return len(combined) |
def _extract_last_value_from_string_argument(argument_string: str) -> str:
"""
Internal function for argument string cleanup.
Parameters
----------
argument_string
A string representing an argument to a function.
Can be a string containing a list/tuple/set.
Returns
-------
... |
def default_translator(value):
"""Translates a "default" target to a //conditions:default selection."""
return {"//conditions:default": value} |
def _drop_units(q):
""" Drop the unit definition silently """
try:
return q.magnitude
except:
return q |
def eo_vm(x):
""" Takes an integer and prints statements based on even/odd
:param x: INT: Any integer
No returns
"""
if type(x) != int:
return print('Please input a valid integer')
if x % 2 == 0:
print(f'{x} is even')
value = 'even'
else:
print(f'{x} is odd... |
def reverse_int(n):
"""
Late to the party, but here's a good one.
Integer Reverse:
Given: Any random integer in decimal.
Challenge: Reverse it, without using any of the obvious toString tricks, or transient conversions to a data type other than an int.
"""
r = 0
while n > 0:
r = ... |
def pretty_measure(c):
"""
Pretty print measure names
"""
if c == "complexity.params":
c = "complexity.num.params"
return c.replace("complexity.", "").replace("_", ".").replace("log.", "").replace(".fft", "") |
def clean_set_identifiers(setlist):
"""Reformats setlist and encore identiers from the raw API calls
Parameters
----------
setlist : list
A list of songs from the Phish.net API
Returns
-------
setlist : list
Reformatted version of the list
"""
for i, item in e... |
def get_external_stack_name(project_code, stack_name):
"""
Returns the name given to a stack in CloudFormation.
:param project_code: The project code, as defined in config.yaml.
:type project_code: str
:param stack_name: The name of the stack.
:type stack_name: str
:returns: The name given ... |
def remove_invalid_positions(vortex_pos, antivortex_pos, r):
""" Function that removes oppositely signed vortices that are too close together, typically these are sometimes
detected by the algorithm when the phase field is broken near an existing vortex."""
removable_vort = [] # List of removable vortices... |
def set_breakpoints_active(active: bool) -> dict:
"""Activates / deactivates all breakpoints on the page.
Parameters
----------
active: bool
New value for breakpoints active state.
"""
return {"method": "Debugger.setBreakpointsActive", "params": {"active": active}} |
def gets_discount(x, y):
""" Returns True if this is a combination of a senior citizen
and a child, False otherwise.
>>> gets_discount(65, 12)
True
>>> gets_discount(9, 70)
True
>>> gets_discount(40, 45)
False
>>> gets_discount(40, 75)
False
>>> gets_discount(65, 13)
Fal... |
def validate_tag_update(update):
"""
Property: ResourceUpdateConstraint.TagUpdateOnProvisionedProduct
"""
valid_tag_update_values = [
"ALLOWED",
"NOT_ALLOWED",
]
if update not in valid_tag_update_values:
raise ValueError("{} is not a valid tag update value".format(update)... |
def fixed_charge_coverage(ebit, lease_payments, interest_payments):
"""Computes fixed chage coverage ratio.
Parameters
----------
ebit : int or float
Earnings before interest and taxes
lease_payments : int or float
Lease payments
interest_payments : int or float
Interest... |
def parse_operating_point(operating_point, operating_kinds, class_names):
"""Checks the operating point contents and extracts the three defined
variables
"""
if "kind" not in operating_point:
raise ValueError("Failed to find the kind of operating point.")
elif operating_point["kind"] not in... |
def clean_links(text):
"""Remove brackets around a wikilink, keeping the label instead of the page
if it exists.
"[[foobar]]" will become "foobar", but "[[foobar|code words]]" will return
"code words".
Args:
text (str): Full text of a Wikipedia article as a single string.
Returns:
... |
def label(all_data, val, t):
""" Return data to be used as the column label in a spreadsheet and
denote whether or not the label must be translated, returning the
tuple
(label-data, should-label-be-translated?)
On input:
all_data -- registration report
val -- the id we're looking for i... |
def is_set_obj(obj):
"""Return True if obj is a set."""
return isinstance(obj, set) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.