content stringlengths 42 6.51k |
|---|
def pad_sequence_to_length(sequence,
desired_length,
default_value = lambda: 0,
padding_on_right = True):
"""
Take a list of objects and pads it to the desired length, returning the padded list. The
original list is not modifi... |
def normalizador(matriz: list) -> list:
"""Normaliza os valores da matriz passada."""
matriz_normalizada = []
maximizante_da_matriz = matriz[-1]
for linha in matriz:
nova_coluna = []
for i, coluna in enumerate(linha):
nova_coluna.append(coluna / maximizante_da_matriz[i])
... |
def _company_total_debt(column):
""" Uses balance sheet to get company total debt rate """
long_term_debt = column["Long-term debt"]
short_long_debt = column["Short-term debt"]
return long_term_debt + short_long_debt |
def bottom_up_fib(n):
"""Compute the nth fibonaci number; bottom-up dynamic programming approach"""
memo = {}
for k in range(1, n+1):
if k <= 2:
f = 1
else:
f = memo[k-1] + memo[k-2]
memo[k] = f
return memo[n] |
def notes(*grades, situation=False):
"""
-> Receives the grades os several students and returns a dictionary with varous information regarding the grades of the class
:param grades: Receives student grades (undefined amount).
:param situation: Indicates wheter or not show the class situation.
:retur... |
def selectionsort(a):
""" selectionsort implementation
>>> selectionsort([6, 4, 8, 2, 1, 9, 10])
[1, 2, 4, 6, 8, 9, 10]
"""
for i in range(len(a)):
min = i
for j in range(i,len(a)):
if a[j] < a[min]:
min = j
a[i],a[min] = a[min], a[i]
return ... |
def subdict(o_dict, subset):
"""Method gets sub dictionary
Args:
o_dict (dict): original dictionary
subset (list): requested subset key
Returns:
dict: sub dictionary
"""
return dict((key, value) for key, value in o_dict.items() if key in subset) |
def decapitalize(s):
"""
De-capitalize a string (lower first character)
:param s:
:type s:
:return:
:rtype:
"""
return s[:1].lower() + s[1:] if s else '' |
def chunks(lst, n):
"""Expand successive n-sized chunks from lst."""
return [lst[i - n : i] for i in range(n, len(lst) + n, n)] |
def cubicCurve(P, t):
"""Evaluated the cubic Bezier curve (given by control points P) at t"""
return P[0] * (1 - t) ** 3 + 3 * P[1] * t * (1 - t) ** 2 + 3 * P[2] * (
1 - t) * t ** 2 + P[3] * t ** 3 |
def paste(x, sep=", "):
"""
Custom string formatting function to format (???) output.
"""
out = ""
for i in x:
out += i + sep
return out.strip(sep) |
def generate_probabilities(alpha, beta, x):
"""Generate probabilities in one pass for all t in x"""
p = [alpha / (alpha + beta)]
for t in range(1, x):
pt = (beta + t - 1) / (alpha + beta + t) * p[t-1]
p.append(pt)
return p |
def letter_count(num):
"""Returns the number of letters in the specified number"""
assert 0 < num <= 1000
num = str(num)
acc = 0
if len(num) > 3:
acc += len("one thousand".replace(" ", ""))
num = "0"
if len(num) > 2:
acc += (
len("hundred and".replace(" ", "")... |
def strip_dir(path):
"""Returns directory of file path.
.. todo:: Replace this with Python standard function
:param str path: path is a file path. not an augeas section or
directive path
:returns: directory
:rtype: str
"""
index = path.rfind("/")
if index > 0:
return ... |
def is_annotation(obj):
"""
An object is an annotation object if it has the attributes
help, kind, abbrev, type, choices, metavar.
"""
return (hasattr(obj, 'help') and hasattr(obj, 'kind')
and hasattr(obj, 'abbrev') and hasattr(obj, 'type')
and hasattr(obj, 'choices') and has... |
def leapfrog(theta, r, grad, epsilon, f):
""" Perfom a leapfrog jump in the Hamiltonian space
INPUTS
------
theta: ndarray[float, ndim=1]
initial parameter position
r: ndarray[float, ndim=1]
initial momentum
grad: float
initial gradient value
epsilon: float
... |
def calc_mean(values):
"""Calculates the mean of a list of numbers."""
values_sum = 0
for value in values:
values_sum += value
return values_sum / len(values) |
def insertion_sort(A):
"""do something."""
hi = 1 # upper bound
while hi < len(A):
j = hi
while j > 0 and A[j-1] > A[j]:
A[j-1], A[j] = A[j], A[j-1] # swap!
j -= 1
hi += 1
return A |
def parse_hour_spec(hour_spec):
"""Hour spec is a two-hour time-window that dictates when an hourly backup
should kick off.
Ex. h_0000_0200 is a backup off that kicks off sometime between midnight
and 2am GMT.
"""
prefix, start_window, end_window = hour_spec.split('_')
return int(start_wind... |
def dir_get(path):
"""
Returns directory portion of the path argument.
"""
import os
s = path.split(os.sep)
s.pop()
return os.sep.join(s) |
def linear_anneal(t, anneal_steps, start_e, end_e, start_steps):
"""
Linearly anneals epsilon
Args:
t: Current time
anneal_steps: Number of steps to anneal over
start_e: Initial epsilon
end_e: Final epsilon
start_steps: Number of initial s... |
def make_empty(seq):
"""
>>> make_empty([1, 2, 3, 4])
[]
>>> make_empty(('a', 'b', 'c'))
()
>>> make_empty("No, not me!")
''
"""
if type(seq) == list:
return list()
elif type(seq) == tuple:
return tuple()
elif type(seq) == str:
return str() |
def accept_use_complete_history(t, distance_function, eps, x, x_0, par):
"""
Use the acceptance criteria from the complete history to evaluate whether
to accept or reject.
This includes time points 0,...,t, as far as these are
available. If either the distance function or the epsilon criterion cann... |
def check_split_ratio(split_ratio):
"""Check that the split ratio argument is not malformed"""
valid_ratio = 0.
if isinstance(split_ratio, float):
# Only the train set relative ratio is provided
# Assert in bounds, validation size is zero
assert 0. < split_ratio < 1., (
"... |
def pad(plaintext: bytearray, block_size=16):
"""PKCS#7 Padding"""
num_pad = block_size - (len(plaintext) % block_size)
return plaintext + bytearray([num_pad for x in range(num_pad)]) |
def list_wrap_(obj):
"""
normalize input to list
Args:
obj(obj): input values
"""
return list(obj) if isinstance(obj, (list, tuple)) else [obj] |
def name_with_unit(var=None, name=None, log=False):
"""
Make a column title or axis label with "Name [unit]".
"""
text = ""
if name is not None:
text = name
elif var is not None:
text = str(var.dims[-1])
if log:
text = "log\u2081\u2080(" + text + ")"
if var is no... |
def difference(list_1, list_2):
""" Deterministically find the difference between two lists
Returns the elements in `list_1` that are not in `list_2`. Behaves deterministically, whereas
set difference does not. Computational cost is O(max(l1, l2)), where l1 and l2 are len(list_1)
and len(list_2), respe... |
def Mid(text, start, num=None):
"""Return some characters from the text"""
if num is None:
return text[start - 1:]
else:
return text[(start - 1):(start + num - 1)] |
def add_Ts(T0,T1):
"""
Merges two path dictionaries.
:param T0: A path dictionary.
:param T1: A path dictionary.
:return: A merged path dictionary.
"""
for u in T1:
if u not in T0:
T0[u] = {}
for v in T1[u]:
if v not in T0[u]:
T0[u][v... |
def argsparseintlist(txt):
"""
Validate a list of int arguments.
:param txt: argument with comma separated numbers.
:return: list of integer converted numbers.
"""
txt = txt.split(",")
listarg = [int(i) for i in txt]
return listarg |
def calchash(data, key):
"""Calculate file name hash.
Args:
data: File name data.
key: Hash key.
Returns:
Hash value.
"""
ret = 0
for c in data:
ret = (ret * key + ord(c)) & 0xffffffff
return ret |
def _getBounds(stats1, stats2):
"""
Gets low and high bounds that captures the interesting bits of the two
pieces of data.
@ In, stats1, dict, dictionary with either "low" and "high" or "mean" and "stdev"
@ In, stats2, dict, dictionary with either "low" and "high" or "mean" and "stdev"
@ Out, (low... |
def GetValueFromObjectCustomMetadata(obj_metadata,
search_key,
default_value=None):
"""Filters a specific element out of an object's custom metadata.
Args:
obj_metadata: (apitools_messages.Object) The metadata for an object.
search_k... |
def is_country_in_list(country, names):
"""Does country have any name from 'names' list among its name/name:en tags
of boundary/label.
"""
return any(
any(
country[property].get(name_tag) in names
for name_tag in ('name', 'name:en')
... |
def _get_acl_username(acl):
"""Port of ``copyAclUserName`` from ``dumputils.c``"""
i = 0
output = ''
while i < len(acl) and acl[i] != '=':
# If user name isn't quoted, then just add it to the output buffer
if acl[i] != '"':
output += acl[i]
i += 1
else:
... |
def parse_id(i):
"""Since we deal with both strings and ints, force appid to be correct."""
try:
return int(str(i).strip())
except:
return None |
def clean_spaces(txt):
"""
Removes multiple spaces from a given string.
Args:
txt (str): given string.
Returns:
str: updated string.
"""
return " ".join(txt.split()) |
def interp_bands(src_band, target_band, src_gain):
"""Linear interp from one band to another. All must be sorted."""
gain = []
for i, b in enumerate(target_band):
if b in src_band:
gain.append(src_gain[i])
continue
idx = sorted(src_band + [b]).index(b)
idx = m... |
def pretty_bytes(num):
""" pretty print the given number of bytes """
for unit in ['', 'KB', 'MB', 'GB']:
if num < 1024.0:
if unit == '':
return "%d" % (num)
else:
return "%3.1f%s" % (num, unit)
num /= 1024.0
return "%3.1f%s" % (num, 'T... |
def get_lengthfield_width_by_wiretype(wiretype):
"""
Returns the width of the length field as number of bytes depending on the
given wiretype.
"""
if wiretype is None:
raise ValueError('Wiretype needed, can not convert NoneType.')
if wiretype < 4:
return 0
elif wiretype == 5... |
def intent_slot(intent, slot_name):
"""return slot dict, avoid key errors"""
if slot_name in intent['slots'] and 'value' in intent['slots'][slot_name]:
return intent['slots'][slot_name]
return None |
def error_message(error_text: str, status_code=400):
"""Generate an error message with a status code.
Args:
error_text (str): Error text to return with the message body.
status_code (int): HTTP status code to return.
Return
dict, int: Error message and HTTP status code.
"""
... |
def _check_name_should_break(name):
"""
Checks whether the passed `name` is type `str`.
Used inside of ``check_name`` to check whether the given variable is usable, so we should stop checking
other alternative cases.
Parameters
----------
name : `Any`
Returns
-------
... |
def disjoint1(A, B, C):
"""O(n**3)"""
for a in A:
for b in B:
for c in C:
if a == b == c:
return False
return True |
def format_node(node, indent, depth, to_str=str):
"""Return string of graph node based on arguments.
Args
node: tuple of two items
indent: string of tree indentation chars
depth: int of tree depth, 0 = root
to_str: function to convert node to string, by default str
Returns
... |
def GetAllProjectsOfIssues(issues):
"""Returns a list of all projects that the given issues are in."""
project_ids = set()
for issue in issues:
project_ids.add(issue.project_id)
return project_ids |
def convertd2b__(amount, cad, decpre, binpre):
"""Return the result with the equality."""
d2b = str(amount) + " " + decpre + " = " + cad + " " + binpre
return d2b |
def basic_to_bio(tags):
"""
Convert a basic tag sequence into a BIO sequence.
You can compose this with bio2_to_bioes to convert to bioes
Args:
tags: a list of tags in basic (no B-, I-, etc) format
Returns:
new_tags: a list of tags in BIO format
"""
new_tags = []
for i,... |
def recursive_itemgetter(data_structure, keys):
"""Recursively retrieve items with getitem, for mix of lists, dicts..."""
curr_data_structure = data_structure
for curr_key in keys:
curr_data_structure = curr_data_structure[curr_key]
return curr_data_structure |
def har_request_headers(har, offset=-1):
"""helper to return specified request headers for requests call"""
return {i['name']: i['value'] for i in har['log']['entries'][offset]['request']['headers']} |
def to_ms_string(seconds, left=False):
"""
Convert seconds into a string of milliseconds. If the string is smaller
than 6 positions it will add leading spaces to complete a total of 6 chars
Args:
seconds: time in seconds expressed as float
left: reverse justification and fills blanks at ... |
def linear_scale(input, in_low, in_high, out_low, out_high):
""" (number, number, number, number, number) -> float
Linear scaling. Scales old_value in the range (in_high - in-low) to a value
in the range (out_high - out_low). Returns the result.
>>> linear_scale(0.5, 0.0, 1.0, 0, 127)
63.5
""... |
def preference_deploy(proto_commod, pref_fac, diff):
""" This function deploys the facility with the highest preference only.
Paramters:
----------
proto_commod: dictionary
key: prototype name
value: dictionary
key: 'cap', 'pref', 'constraint_commod', 'constraint'
... |
def extract_reason(openfield):
"""
Extract optional reason data from openfield.
:param openfield: str
:return: str
"""
if "," in openfield:
# Only allow for 1 extra param at a time. No need for more now, but beware if we add!
parts = openfield.split(",")
parts.pop(0)
... |
def null(n):
"""
Return the null matrix of size n
:param n: size of the null matrix to return
:return: null matrix represented by a 2 dimensional array of size n*n
"""
return [[0 for _ in range(n)] for _ in range(n)] |
def bubble_sort(array):
"""
my own implementation of the bubble sort algorithm.
Args:
array (list[int]): A unsorted list with n numbers.
Returns:
list[int]: The sorted input list.
Examples:
>>> bubble_sort([]) == sorted([])
True
>>> bubble_sort([1]) == [1]... |
def sequence_accuracy(references, hypotheses):
"""
Compute the accuracy of hypothesis tokens: correct tokens / all tokens
Tokens are correct if they appear in the same position in the reference.
:param hypotheses: list of hypotheses (strings)
:param references: list of references (strings)
:ret... |
def normalize(l):
"""
Normalizes input list.
Parameters
----------
l: list
The list to be normalized
Returns
-------
The normalized list or numpy array
Raises
------
ValueError, if the list sums to zero
"""
s = float(sum(l))
if s == 0:
raise Va... |
def _validate_port(port_value):
"""Makes sure the port value is valid and can be used by a non-root user.
Args:
port_value: Integer or string version of integer.
Returns:
Integer version of port_value if valid, otherwise None.
"""
try:
port_value = int(port_value)
except (ValueError, TypeError... |
def _is_empty(query):
"""Checks if the result table of a query is empty
Parameters
----------
query : dict
JSON of the result of the query
Returns
-------
bool
TRUE if the result table is empty, else FALSE
"""
return len(query["bindings"]) == 0 |
def _convert_freq_string_to_description(freq):
"""Get long description for frequency string."""
if freq in ('H', '1H'):
return 'hourly'
if freq in ('D', '1D'):
return 'daily'
if freq in ('W', '1W', 'W-SUN'):
return 'weekly'
if freq in ('1M', '1MS', 'MS'):
return '... |
def check_de(current_de, list_of_de):
"""Check if any of the strings in ``list_of_de`` is contained in ``current_de``."""
return any(de in current_de for de in list_of_de) |
def list_difference(list1, list2):
"""
Given two lists with alignments list1 and list2, return a new list
(new_list2) that contains all elements of list2 without elements of
list1.
"""
# Create an inverted list of alignments names in list1 to allow fast
# lookups.
inverted_l... |
def safe_issubclass(*args):
"""Like issubclass, but will just return False if not a class."""
try:
if issubclass(*args):
return True
except TypeError:
pass
return False |
def set_of_county_tuples(cluster_list):
"""
Input: A list of Cluster objects
Output: Set of sorted tuple of counties corresponds to counties in each cluster
"""
set_of_clusters = set([])
for cluster in cluster_list:
counties_in_cluster = cluster.fips_codes()
# c... |
def harmonize_url(url):
"""Harmonize the url string.
This function checks if url ends with slash, if not, add a slash to the url string.
Args:
url (str): A string of url.
Returns:
str: A string of url ends with slash.
"""
url = url.rstrip('/')
return url + '/' |
def get_relevant_parameters(feature_data, iob_type):
"""
Gets features relevant to a specific IOB type and assign them verilog
parameter names.
"""
# Get all features and make parameter names
all_features = set(
[f for data in feature_data.values() for f in data.keys()])
parameters ... |
def embed(information:dict) -> str:
"""
input: item:dict ={"url":str,"text":str}
"""
return f"[{information['url']}]({information['url']})" |
def snake_to_camel(s: str):
"""
Convert a snake_cased_name to a camelCasedName
:param s: the snake_cased_name
:return: camelCasedName
"""
components = s.split("_")
return components[0] + "".join(y.title() for y in components[1:]) |
def as_frozen(x):
"""Return an immutable representation for x."""
if isinstance(x, dict):
return tuple(sorted((k, as_frozen(v)) for k, v in x.items()))
else:
assert not isinstance(x, (list, tuple))
return x |
def check_1(sigs, exps):
"""
Repository in src-openeuler and openeuler should be managed by the single SIG.
"""
print("Repository in src-openeuler and openeuler should be managed by the single SIG.")
repositories = {}
errors_found = 0
for sig in sigs:
if sig["name"] == "Private":
... |
def split_mapping_by_keys(mapping, key_lists):
"""Split up a mapping (dict) according to connected components
Each connected component is a sequence of keys from mapping;
returned is a corresponding sequence of head mappings, each with
only the keys from that connected component.
"""
mappings =... |
def clamp(value, minval, maxval):
"""Clamp a numeric value to a specific range.
Parameters
----------
value: numeric
The value to clamp.
minval: numeric
The lower bound.
maxval: numeric
The upper bound.
Returns
-------
numeric
The clamped value. I... |
def int_node_filter(int_node_list, tol=1E-4):
"""
"""
s_list = sorted(int_node_list) # , key=lambda x:x[i])
#print('s_list', s_list)
return s_list[:1] + [t2 for t1, t2 in zip(s_list[:-1], s_list[1:]) if
(
(t1[1:] != t2[1:]) and
... |
def var_K(N_atoms, avg_momentum):
"""compute variances of kinetic energy
Args:
N_atoms (TYPE): Description
avg_momentum (TYPE): Description
Returns:
TYPE: Description
"""
return (2 * ((0.5 * 3 * N_atoms * avg_momentum **2 ) ** 2)/(3 * N_atoms) ) ** (1/2) |
def kernel_zhao(s, s0=0.08333, theta=0.242):
"""
Calculates Zhao kernel for given value.
:param s: time point to evaluate
:param s0: initial reaction time
:param theta: empirically determined constant
:return: value at time point s
"""
c0 = 1.0 / s0 / (1 - 1.0 / -theta) # normalization... |
def ghi_to_w(ghi, eff=0.19, surf=0.0568):
"""
Description of ghi_to_w
Args:
ghi (undefined): Global Horizontal Irradiance
eff=0.19 (undefined): Efficiency of solar panel
surf=0.0568 (undefined): Solar panel surface area
"""
return ghi*eff*surf |
def convert_to_spans(raw_text, tokens):
"""Convert tokenized version of `raw_text` to character spans into it.
Args:
raw_text: The raw string
tokens: The tokenized version of the string
Returns:
[list of (start, end) tuples] mapping each token to corresponding indices
in the text.
"""
cur_i... |
def temperature_convert(inputvalue, inputunits, outputunits):
"""
Converts temperature from one unit to another.
Parameters
----------
inputvalue : float
Input temperature value
inputunits : string
Input temperature units:
c = celsius
f = fahrenheit
... |
def my_isinstance(obj, class_or_tuple):
"""Same as builtin instance, but without position only constraint.
Therefore, we can partialize class_or_tuple:
Otherwise, couldn't do:
>>> isinstance_of_str = partial(my_isinstance, class_or_tuple=str)
>>> isinstance_of_str('asdf')
True
>>> isinstan... |
def q_zero(bits=8):
"""
The quantized level of the 0.0 value.
"""
return 1 << (bits - 1) |
def _FORMAT(s):
"""Helper to provide uniform appearance for formats in cmdline options"""
return ". Specified as %r" % s |
def distinct(number):
"""Checks if the digits of a natural number are distinct"""
seen = []
while number:
digit = number % 10
if digit in seen:
return False
seen.append(digit)
# Remove the last digit from the number
number //= 10
return True |
def stress_model(strain, modulus):
"""
Returns the linear estimate of the stress-strain curve using the strain and estimated modulus.
Used for fitting data with scipy.
Parameters
----------
strain : array-like
The array of experimental strain values, unitless (or with cancelled
... |
def calcite(piezometer=None):
""" Data base for calcite piezometers. It returns the material parameter,
the exponent parameter and a warn with the "average" grain size measure to be use.
Parameter
---------
piezometer : string or None
the piezometric relation
References
----------
... |
def pre_process_data(linelist):
"""Empty Fields within ICD data point are changed from Null to 0"""
for index in range(len(linelist)):
if not linelist[index]:
linelist[index] = '0'
return linelist |
def rain_attenuation(distance):
"""Calculate rain attenuation."""
attenuation = 9 * (distance / 1000) # convert from m to km
return round(attenuation, 3) |
def Ecmrel2Enm(Ecmrel, ref_wavelength=515):
"""Converts energy from cm-1 relative to a ref wavelength to an energy in wavelength (nm)
Parameters
----------
Ecmrel: float
photon energy in cm-1
ref_wavelength: float
reference wavelength in nm from which calculate the p... |
def make_definition(resources, include_sqs):
"""
Makes a definition for the demo based on resources created by the
AWS CloudFormation stack.
:param resources: Resources to inject into the definition.
:param include_sqs: When True, include a state that sends messages to an Amazon
... |
def atfile_sci(filename):
"""
Return the filename of the science image
which is assumed to be the first word
in the atfile the user gave.
"""
return filename.split()[0] |
def calc_IoU(bbox1, bbox2):
"""
Calculate intersection over union for two boxes.
Args:
bbox1 (array_like[int]): Endpoints of the first bounding box
in the next format: [ymin, xmin, ymax, xmax].
bbox2 (array_like[int]): Endpoints of the second bounding box
in the next... |
def _split_list(mylist, chunk_size):
"""Split list in chunks.
Parameters
----------
my_list: list
list to split.
chunk_size: int
size of the lists returned.
Returns
-------
list
list of the chunked lists.
See: https://stackoverflow.com/a/312466/5201771
... |
def extract_expression(expr: str) -> str:
"""Extract the sub-expression surrounded by parentheses in ``expr``."""
parenthesis_balance = 0
result = ""
for c in expr:
if c == "(":
parenthesis_balance += 1
elif c == ")":
parenthesis_balance -= 1
if parenthe... |
def sum_digits(n):
"""Recursively calculate the sum of the digits of 'n'
>>> sum_digits(7)
7
>>> sum_digits(30)
3
>>> sum_digits(228)
12
"""
"""BEGIN PROBLEM 2.4"""
return n % 10 + (0 if n < 10 else sum_digits(n // 10))
"""END PROBLEM 2.4""" |
def binary_quadratic_coefficients_from_invariants(discriminant, invariant_choice='default'):
"""
Reconstruct a binary quadratic from the value of its discriminant.
INPUT:
- ``discriminant`` -- The value of the discriminant of the
binary quadratic.
- ``invariant_choice`` -- The type of invar... |
def bool_to_text(b):
""" Changes a provided boolean into a 'Yes' or 'No' string
No test is performed on whether or not the provided variable is boolean or
not, only an 'if b: / else:' test is performed.
Parameters
----------
b: any
Object that will be tested for its evaluation to a boo... |
def preprocess_text(text):
"""Remove tags like [P], [D], [R]"""
return text[3:].strip() |
def response_loader(request):
""" Just reverse the message content.
He take dict object and return dict object
"""
res = {"message": request["message"][::-1]}
return res |
def convert_list_str(string_list, type):
"""
Receive a string and then converts it into a list of selected type
"""
new_type_list = (string_list).split(",")
for inew_type_list, ele in enumerate(new_type_list):
if type is "int":
new_type_list[inew_type_list] = int(ele)
eli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.