content stringlengths 42 6.51k |
|---|
def get_data_type_name(component_name: str, data_type_name: str) -> str:
"""Get the plain data type name from a $ref URI.
:param component_name: $ref URI to the data type of interest
:param data_type_name: context in which the data type is being retrieved (used for error message only)
:return: Plain da... |
def _cleanse_dict(original):
"""Strip all admin_password, new_pass, rescue_pass keys from a dict."""
return dict((k, v) for k, v in original.items() if "_pass" not in k) |
def process_license(license):
"""If license is Creative Common return the zenodo style string
else return license as in plan
Parameters
----------
license : dict
A string defining the license
Returns
-------
zlicense : dict
A modified version of the license... |
def fibonacci(num):
"""Return a number from the sequance Fibonnaci by an index."""
if not isinstance(num, int) or num < 0:
raise ValueError('Sequence Fibonacci can be determined only for positive integer')
if num in [0, 1]:
return num
elif num == 2:
return 1
return fibonacc... |
def distribution_function(yb, x):
""""
Modulate the parabolic distribution y= a(b-x)**2 +c fct. with the
following boundary conditions:
- 1. x=0: y == 3 : follows from the initial distribution function
- 2. Int[0,1] == 1: normalization criteria
- 3. x=1: y == yb, where yb is the tunable pa... |
def create_cities_dict(cities):
"""
We zip for reference each city to a number
in order to work and solve the TSP we need a list
of cities like
[1,2,3,4,5,...........]
with the dictionary we will have a reference of the coordinates of each city
to calculate the distan... |
def diagonalDifference(arr):
"""
Time O(n) Iterate only 1 time
Space O(2n)
"""
n = len(arr)
l2r = []
r2l = []
for i in range(n):
l2r.append(arr[i][i])
r2l.append(arr[i][(n-1)-i])
return abs(sum(l2r) - sum(r2l)) |
def find_multiplicity(knot=-1, knotvector=(), tol=0.001):
""" Finds knot multiplicity."""
# Find and return the multiplicity of the input knot in the given knot vector
mult = 0 # initial multiplicity
# Loop through the knot vector
for kv in knotvector:
# Float equality should be checked w.r... |
def mesh2str(mesh):
"""Converts a mesh number to string
This subroutine converts an integer mesh number to a string.
FDS specifies mesh numbers as zero-padded integers with 4 digits.
Parameters
----------
mesh : int
Integer mesh number
Returns
-------
str
... |
def convert_tibiawiki_position(pos):
"""Converts from TibiaWiki position system to regular numeric coordinates
TibiaWiki takes the coordinates and splits in two bytes, represented in decimal, separated by a period.
Parameters
----------
pos : :class:`str`
A string containing a coordinate.
... |
def to_cxx(data):
"""Generates C++ code from a list of encoded bytes."""
text = '/* This file is generated. DO NOT EDIT!\n\n'
text += 'The byte array encodes effective tld names. See make_dafsa.py for'
text += ' documentation.'
text += '*/\n\n'
text += 'const unsigned char kDafsa[%s] = {\n' % len(data)
fo... |
def _to_j2kt_jvm_name(name):
"""Convert a label name used in j2cl to be used in j2kt jvm"""
if name.endswith("-j2cl"):
name = name[:-5]
return "%s-j2kt-jvm" % name |
def transpose(matrix):
""" Transpose a matrix (defined as a list of lists, where each sub-list is a row in the matrix) """
# This feels dirty somewhow; but it does do exactly what I want
return list(zip(*matrix)) |
def final_12wellplate(sample_number):
"""Determines well containing the final sample from sample number for 12 well plate spotting
"""
letter_12wellplate = ['A', 'B', 'C']
plate_number = sample_number// 12 + (1 if sample_number % 12 > 0 else 0)
final_well_column = sample_number // 3 + \
(1 ... |
def make_url_action(label, url, i18n_labels=None):
"""
make url action.
reference
- https://developers.worksmobile.com/jp/document/1005050?lang=en
:param url: User behavior will trigger the client to request this URL.
:return: actions content
"""
if i18n_labels is not None:
... |
def is_part_of_word(word_fragment, wordlist):
"""Returns True if word_fragment is the beginning of a word in wordlist.
Returns False otherwise. Assumes word_fragment is a string."""
for word in wordlist:
is_part_of_list = word_fragment == word[:len(word_fragment)]
if is_part_of_list == True:... |
def get_conv_output_shape_flattened(input_shape, structure):
"""
Input_shape: (Channels, Height, Width) of input image
structure: List containing tuple (out_channels, kernel_size, stride, padding) per conv layer
"""
def get_layer_output(input, layer_structure):
# See shape calculatio... |
def isiterable(x):
""" Is x iterable?
>>> isiterable([1, 2, 3])
True
>>> isiterable('abc')
True
>>> isiterable(5)
False
"""
try:
iter(x)
return True
except TypeError:
return False |
def cross(v1, v2):
"""Cross product of two vectors"""
n = len(v1)
prod = n*[0]
if n == 3 and len(v2) == 3:
prod[0] = v1[1]*v2[2] - v1[2]*v2[1]
prod[1] = v1[2]*v2[0] - v1[0]*v2[2]
prod[2] = v1[0]*v2[1] - v1[1]*v2[0]
return prod |
def gcd(first_number: int, second_number: int) -> int:
"""
gcd: Function which finds the GCD of two numbers.
The GCD (Greatest Common Divisor) of two numbers is found by the Steins GCD Algorithm.
Args:
first_number (int): First number
second_number (int): Second number
Returns:
... |
def followed_by(pattern):
""" matches if the current position is followed by the pattern
:param pattern: an `re` pattern
:type pattern: str
:rtype: str
"""
return r'(?={:s})'.format(pattern) |
def sign_changes(x, z):
"""
Checks if two numbers have different sign
"""
return x*z < 0 |
def converttoskewedmatrix(m):
"""
convert to a skewed diamond shape.
a
a b c d b
d e f -> g e c
g h i h f
i
"""
d = [ [ "" for _ in range(len(m)) ] for _ in range(2*len(m)-1) ]
for y in range(1, 2*len(m)):
for x... |
def getRuleCount( lstRules, policy_name ):
"""
This function return the rule count for a given policy
indicated by policy_name
Parameters:
- IN : 1. List containing all the rules
2. Name of the policy
- Out: # of rules in the policy.
"""
count = 0
for x in lstRules:
if x.split(',')[0] == poli... |
def test_train_val_split(patient_id,
sub_dataset_ids,
cv_fold_number):
""" if cv_fold_number == 1:
if patient_id in sub_dataset_ids[-5:]: return 'test'
elif patient_id in sub_dataset_ids[-7:-5]: return 'validation'
else: return 'train'
... |
def _normalize(url):
"""
Ensure that its argument ends with a trailing / if it's nonempty.
"""
if url and not url.endswith("/"):
return url + "/"
else:
return url |
def dup_strip(f):
"""Remove leading zeros from `f` in `K[x]`. """
if not f or f[0]:
return f
i = 0
for cf in f:
if cf:
break
else:
i += 1
return f[i:] |
def exp(n, m):
"""
Calculates m ^ n.
"""
if n == 1:
# m ^ 1 = m
return m
else:
# m ^ n = m * m ^ (n-1)
return m * exp(m, n - 1) |
def numbers(number_list):
"""
Add up numbers in a list.
:return: sum of the numbers
"""
test_sum = 0
for this_num in number_list:
test_sum = test_sum + this_num
return test_sum |
def diff(x, y):
"""Return absolute difference between x and y, assumed to be of the same basic type
if numeric and neither is missing (None), return ordinary absolute value
if not numeric, return 0 if identical and not blank.
Otherwise return BIG."""
BIG = 1e100
try:
return abs(x ... |
def partition_string(s, segments):
"""
Partition a string into a number of segments. If the given number of
segments does not divide evenly into the string's length, extra characters
are added to the leading segments in order to allow for the requested number
of segments.
This is useful when pa... |
def write_trailer(trailer):
"""Write the trailer. Not implemented."""
return (trailer or []) |
def reverse(n):
"""Reverse the bits of <n>"""
return int(bin(n)[:1:-1], 2) |
def __to_dict( obj, attr_list ):
"""
Turn an object into a dictionary of its readable attributes.
"""
ret = {}
if len(attr_list) > 0:
for attr in attr_list:
ret[attr] = getattr( obj, attr )
return ret |
def get_thresholds_and_fn_rate(thresholds_and_tps):
"""FN etc. rates *with regards to start cluster*!!!"""
thresholds_and_fns = []
for thresholds, tp_rate in thresholds_and_tps:
fn_rate = 1 - tp_rate
thresholds_and_fns.append((thresholds, fn_rate))
return thresholds_and_fns |
def set_passive_el(xmin, xval, passive_el):
""" Sets the values of passive elements.
Args:
xmin (:obj:`numpy.array`):
xval (:obj:`numpy.array`): Indicates where there is mass.
passive_el (:obj:`numpy.array`): Passive element nodes.
Returns:
A tuple with updated xmin and xv... |
def update_user_count_eponymous(set_of_contributors, anonymous_coward_comments_counter):
"""
Eponymous user count update.
Input: - set_of_contributors: A python set of user ids.
- anonymous_coward_comments_counter: The number of comments posted by anonymous user(s).
Output: - user_count: ... |
def is_metalink(url):
""" Checks if a given url is a metalink url
"""
return 'metalink?' in url.lower() |
def uniformcdfcrit_c(C,zc):
"""Cumulative distribution function of a (critical emission) random
=variable uniformly distributed from c_crit = 0 to 1/2"""
return C/(1./2.-zc) * (0<C)*(C<1./2.-zc) + (1./2.-zc<C) |
def getChildrenLayer(layer):
"""
Get the children layers. All the children of children recursively.
\nin:
MixinInterface.LayerProperties
\nout:
MixinInterface.LayerProperties
"""
result = []
if layer is not None:
num_children = layer.getNumChildren()
... |
def merge_and_dedup(*data):
"""This function merges various data elements into a single, deduplicated list.
:param data: One or more data elements to merge and deduplicate
:returns: A merged and deduplicated list of data
"""
iter_types, unique_list = [list, tuple, set], []
for element in data:
... |
def solution1(nums):
"""
Solution by myself
---
:type nums: list[int]
:rtype nums: int
"""
for i in range(0, len(nums), 2):
try:
if nums[i] != nums[i + 1]:
return nums[i]
# Consider the condition that the single num is the last one
except ... |
def override_socket(bind):
""" Bind all sockets to specific address """
import socket
class BoundSocket(socket.socket):
"""
requests is kinda an asshole when it comes to using source_address.
Also volapi is also an asshole.
"""
def __init__(self, *args, **kw):
... |
def _extensionize(ext: str) -> str:
"""Ensure extensions are prefixed with a dot."""
return f".{ext}" if ext[0].isalpha() else ext |
def get_align_from_hjust(hjust: float) -> str:
"""
Maps 0 -> 'left', 0.5 -> 'center', 1 -> 'right'
... and in-between things get nudged to the nearest of those three.
"""
if hjust <= 0.25:
return 'left'
elif hjust >= 0.75:
return 'right'
return 'center' |
def remove_space_and_symbols(data):
"""Remove spaces and - _ from a list (or a single) of strings.
Args:
data: list of strings or a single string to clean
Returns:
data: list of strings or a string without space and symbols _ and -
"""
import re
if type(data) is list:
... |
def _make_tuple(x):
"""
Helper to convert x into a one item tuple if it's not a tuple already.
"""
return x if isinstance(x, tuple) else (x,) |
def resolve_bang(query: str, bangs_dict: dict) -> str:
"""Transform's a user's query to a bang search, if an operator is found
Args:
query: The search query
bangs_dict: The dict of available bang operators, with corresponding
format string search URLs
(i.... |
def is_one_away(left: str, right: str) -> bool:
"""
Checks for a one character difference,
on same size strings
"""
if len(left) != len(right):
return False
diff: int = 0
for i in range(len(left)):
if left[i] != right[i]:
diff += 1
return diff == 1 |
def convert_parameters(ansible_parameters):
"""
convert name=value;name=value syntax to a dictionary
:param ansible_parameters:
:return: dictionary
"""
params_dict = {}
if ansible_parameters:
for item in ansible_parameters.split(u";"):
if len(item.strip(u' ')) > 0:
... |
def get_left(sprites):
"""
:return: which sprite to use.
"""
return sprites["block"][0] |
def get_package_name(data):
"""Get "name" from a package with a workaround when it's not defined.
Use the last part of details url for the package's name otherwise since
packages must define one of these two keys anyway.
"""
return data.get('name') or data.get('details').rsplit('/', 1)[-1] |
def answer(input):
"""
>>> answer("1234")
1234
"""
lines = input.split('\n')
for line in lines:
return int(line) |
def xml_float(line, tag, namespace, default=0):
""" Get float value from etree element """
try:
val = float(line.find(namespace + tag).text)
except:
val = default
return val |
def add_percent_sign(n):
"""Add a % sign to the end of x, unless x is empty"""
if not isinstance(n, str):
n = str(n)
if len(n) > 0:
return n + "%"
return n |
def gregtojulian (yr, mo, dy, qty_of_days, op):
""" Receive the date from parameter
name: Ricardo Portela da Silva
date: 31/12/2016
"""
juliandays = 0
a = int((14-mo)/12)
y = yr + 4800 - a
m = mo + 12*a - 3
g2jd = dy + int((153*m+2)/5)+365*y+int(y/4)-int(y/100)+int(y/400)-32045
... |
def py_mul(*x):
"""
Function for python operator ``*``.
@param x floats
@return `x*y`
"""
if len(x) == 2:
return x[0] * x[1]
else:
p = x[0]
for y in x[1:]:
p *= y
return p |
def noll_to_wss(zern):
"""
Transform a Noll Zernike index into a JWST WSS framework Zernike index.
:param zern: int; Noll Zernike index
:return: WSS Zernike index
"""
noll = {1: 'piston', 2: 'tip', 3: 'tilt', 4: 'defocus', 5: 'astig45', 6: 'astig0', 7: 'ycoma', 8: 'xcoma',
9: 'ytrefo... |
def is_present(header, headers):
"""
Takes a string as the frist argument and a dictionary as the second
Returns true if the header exists in headers.
"""
i = 0
ret = False
header = header.lower().strip()
headers = list(headers.keys())
while i < len(headers) and ret == False:
if header == headers[i]:
ret ... |
def make_refs(cols):
"""
Return a dictionary from a list
"""
return {k: v for v, k in enumerate(cols)} |
def human_format(num, precision=2):
"""Return numbers rounded to given precision and with sensuous suffixes.
Parameters
==========
num : float
The number to humanify.
precision : int, default : 2
Number of decimal places.
Return
======
s : String
Human readable ... |
def word_bits(word):
"""Convert a 32-bit word to a human-legible bitstring with separators"""
return '_'.join(bin(int(digit,16))[2:].zfill(4) for digit in ('%08x' % word)) |
def upper_triangle(matrix):
"""
Return the upper triangle of a list of list representation of a square matrix
"""
assert len(matrix) == len(matrix[0])
return [i[matrix[:-1].index(i)+1:] for i in matrix[:-1]] |
def parse_dns_record(record: dict) -> dict:
"""
Parse the DNS record.
Replace the ttl and prio string values with the int values.
:param record: the unparsed DNS record dict
:return: the parsed dns record dict
"""
if record.get("ttl", None) is not None:
record["ttl"] = int(record["... |
def at_eol_marker(data, index):
"""Is the array at index indicating an end of line (eol)?
:return: The number of bytes indicating the eol, or 0 if no eol.
"""
if len(data) > index and data[index:index+1] == b"\x0a":
return 1
if len(data) > index+1 and data[index:index+2] == b"\x0d\x0a":
... |
def extract_context(error):
"""
Extract extract context from an error.
Errors may (optionally) provide a context attribute which will be encoded
in the response.
"""
return getattr(error, "context", {"errors": []}) |
def find_parent_loop_name(node_name, while_loop_name_set):
"""Find name of direct parent while loop."""
ploop_name = ""
name_prefix = node_name.rsplit("/", 1)[0]
if name_prefix.startswith("^"):
name_prefix = name_prefix[1:]
for lname in while_loop_name_set:
if name_prefix.startswith(... |
def fix_path(path):
"""Method fixes Windows path
Args:
none
Returns:
str
"""
path = path.replace('\\', '/')
return path |
def strip_prefix(string, prefix):
"""Strip off prefix if it exists."""
if string.startswith(prefix):
return string[len(prefix):]
return string |
def _linreg(X, Y):
"""
Summary
Linear regression of y = ax + b
Usage
real, real, real = linreg(list, list)
Returns coefficients to the regression line "y=ax+b" from x[] and
y[], and R^2 Value
"""
from math import sqrt
assert len(X) == len(Y)
N = len(X)
Sx = Sy = Sxx = Syy... |
def filter_none(obj):
"""Remove ``None`` values from tuples, lists or dictionaries. Return other objects as-is.
:param obj: the object
:return: collection with ``None`` values removed
"""
if obj is None:
return None
new_obj = None
if isinstance(obj, dict):
new_obj = type(obj... |
def compress_indexes(indexes):
"""Compress a list of indexes. The list is assumed to be sorted in ascending
order, and this function will remove the all the consecutives numbers and
only keep the first and the number of the consecutives in a dict.
eg : [0, 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 18, 19, 2... |
def isiterable(obj):
"""
Check if object is iterable (string excluded)
"""
return hasattr(obj, "__iter__") |
def _neg_units(units):
"""Helper method to invert sign of units
Parameters
----------
units : dict
Units
Returns
-------
units_out : dict
Inverted units
"""
out_dict = {}
for key in units.keys():
out_dict[key] = - units[key]
return... |
def expand_ch_groups(ch_groups):
"""
Expand a ch_group from its json shorthand
ch_groups: a dictionary whose keys are the names of channel groupings,
and whose values have the following fields:
ch_list (list): a list of channels and channel ranges associated
with this group
... |
def construct_kurucz_path(Z,root):
"""This constructs the path to the kurucz models after they are downloaded
with download_kurucz()"""
mstring = str(Z).replace('.','')
if Z < 0:
s = 'm'
mstring=mstring.replace('-','')
else:
s = 'p'
mpath = root+'a'+s+mstring+'k2.dat'
... |
def blank_or_string(s):
"""If it's empty, output the string blank"""
if not s.strip():
return 'blank'
return s |
def truncate(string, length=60):
"""Truncate the given string when it exceeds the given length."""
return string[:length - 4] + '.' * 3 if len(string) > length else string |
def checa_vazio(lista):
"""
Funcao para verificar se o estoque ou o carrinho estao vazios
:param lista: lista contendo o estoque ou o carrinho
:return: bool -> True se o carrinho estiver vazio
"""
if len(lista) == 0:
return True
else:
return False |
def convert_list_to_string(l):
"""
Converts list to string
:param l: Input list
"""
lts = " ".join(str(s) for s in l)
return lts |
def dist(pt1, pt2):
"""Distance between two points"""
return ((pt2[0] - pt1[0])**2 + (pt2[1] - pt1[1])**2 + (pt2[2] - pt1[2])**2)**0.5 |
def merge_nd(nd_cdp, nd_lldp):
""" Merge CDP and LLDP data into one structure """
neis = dict()
nd = list()
for n in nd_lldp:
neis[(n['local_device_id'], n['remote_device_id'], n['local_int'], n['remote_int'])] = n
for n in nd_cdp:
# Always prefer CDP, but grab description from L... |
def bib_reference_name(reference_id: str) -> str:
"""
Generates an identifier that can be used in the Latex document
to generate a reference object
"""
return f"ref{reference_id}" |
def truncpad(srcline, length, align=u'l', ellipsis=True):
"""Return srcline truncated and padded to length, aligned as requested."""
# truncate
if len(srcline) > length:
if ellipsis and length > 4:
ret = srcline[0:(length-1)] + u'\u2026' # Ellipsis
else:
ret = srcline... |
def get_nested_dict_from_list(in_list) -> dict:
"""Convert list ['a','b','c'] to a nested dict {'a':{'b':{'c':{}}}}
Args:
in_list ([list]): list to convert
Returns:
[dict]: list converted to nested dict
"""
out = {}
for key in reversed(in_list):
out = {key: out}
ret... |
def check_number_v1(num):
"""
Runtime exceeded
:param num: input number integer -> check if this is perfect number
:return: bool True/False if the input is perfect number of not
"""
if num <= 0:
return False
count = 1
for i in range(2, num ** 2, 1):
if num % i =... |
def numberise(n):
""" Convert a value to an integer if possible. If not, simply return
the input value.
"""
if n == "NaN":
return None
try:
return int(n)
except ValueError:
return n |
def play_or_pass(card_values, pegging_total):
"""
:param cards:
:param pegging_total:
:return: action
"""
action = 'PASS'
remainder = 31 - pegging_total
if any(int(value) <= remainder for value in card_values):
action = 'PLAY'
return action |
def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1):
"""
Utility function for computing output of convolutions
takes a tuple of (h,w) and returns a tuple of (h,w)
"""
if type(h_w) is not tuple:
h_w = (h_w, h_w)
if type(kernel_size) is not tuple:
kernel_size =... |
def preprocess_proxy(proxy):
"""fix proxy list to IPAddress,Port format from dictionary to ipaddress,port
Parameters
----------------
proxy : dict
proxy details form the proxy json file
Returns
---------------
dict
constaining keys ipaddress and port for the proxy
"""
... |
def weight_converter(li):
"""."""
output = []
for el in li:
if el[-1] == 'T':
output.append(int(el[:-1]) * 1000000)
if el[-1] == 'G':
if el[-2] == 'K':
output.append(int(el[:-2]) * 1000)
else:
output.append(int(el[:-1]) * 1)... |
def reverse_string(txt):
"""func defined for clarity"""
return txt[::-1] |
def get_paramstyle_symbol(paramstyle):
"""Infer the correct paramstyle for a database.paramstyle
Provides a generic way to determine the paramstyle of a database connection
handle. See `PEP-0249`_ for more information.
Args:
paramstyle (str): Result of a generic database handler's `paramstyle... |
def _dedupe_preserve_ord(lst):
"""Dedupe a list and preserve the order of its items."""
seen = set()
return [x for x in lst if x not in seen and not seen.add(x)] |
def find_largest(arr):
"""Function to find the largest number in an array
Args:
arr(list): The list/array to find the index
Returns:
largest_index(int): The index of the largest number
"""
largest = arr[0] # stores the largest value
largest_index = 0 # stores the position of the largest value
f... |
def max_col_width(lines):
"""
Iterate all lines and entries.
Returns: A list of numbers, the max width required for each
column given the data.
"""
lens = [[] for _ in lines[0]]
for line in lines:
for ind, data in enumerate(line):
lens[ind].append(len(data))
... |
def from_string( raw_bytes, offset, count = 0 ):
""" Converts a sequence of NUL-terminated bytes to a Python string. """
s_out = ""
i = 0
while True:
c = raw_bytes[ offset + i ]
if 0 == c: break
s_out += chr( c )
i += 1
if count and (i == count): break
retu... |
def make_header(ob_size):
"""Make the log header.
This needs to be done dynamically because the observations used as input
to the NN may differ.
"""
entries = []
entries.append("t")
for i in range(ob_size):
entries.append("ob{}".format(i))
for i in range(4):
entries.app... |
def get_block(row, col):
"""Determine what block provided row and col are in"""
if row <= 2:
if col <= 2:
return 0
elif col <= 5:
return 1
elif col <= 8:
return 2
elif row <= 5:
if col <= 2:
return 3
elif col <= 5:
... |
def create_dict(key_names):
"""Create a dictionary with provided keys and set values to 0.
Args:
key_names (list): Keys to be added to dictionary.
Returns:
created_dict (dict): Dictionary with key values set to 0.
"""
created_dict = {}
for item in key_names:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.