content stringlengths 42 6.51k |
|---|
def parseData(_dict):
""" transform type
"""
for key in _dict:
if key == 'init_num' or key == 'iter_max':
_dict[key] = int(_dict[key])
else:
_dict[key] = float(_dict[key])
return _dict |
def task_next_bucket(iterator, partition_num):
"""
Get the next partition of incoming data depending on its size and number of
total partitions to be created left. After adding elements to new partitions,
they are deleted from the source in order to ease data transfer.
:param iterator:
:param pa... |
def intToID(idnum):
"""
Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z,
then from aa to az, ba to bz, etc., until zz.
"""
rid = ''
while idnum > 0:
idnum -= 1
rid = chr((idnum % 26) + ord('a')) + rid
idnum = int(idnum / 26)
return rid |
def spell_sql(*args,**kwargs):
"""
list=[]
"""
if len(args[0])<=0:
return None
sql="SELECT * from `emotion_data` WHERE id ={}".format(args[0][0])
for index in args[0][1:]:
sql +=" or id ={}".format(index)
return sql |
def convert_to_uint256(value):
"""
Convert an int value to a 16 bytes binary string value.
Note: the return value is not really 256 bits, nor is it of the neo.Core.UInt256 type
Args:
value (int): number to convert.
Returns:
str:
"""
return bin(value + 2 ** 32)[-32:] |
def _parse_arguments(*args):
"""Because I'm not particularly Pythonic."""
formula = None
if len(args) == 1:
date = args[0]
elif len(args) == 2:
date, formula = args
else:
date = args
return date, formula |
def test_if_reassign(obj1, obj2):
"""
>>> test_if_reassign(*values[:2])
(4.0, 5.0)
>>> sig, syms = infer(test_if_reassign.py_func,
... functype(None, [object_] * 2))
>>> types(syms, 'obj1', 'obj2')
(double, object_)
"""
x = 4.0
y = 5.0
z = 6.0
if int(obj... |
def split_list(s):
"""Split a comma-separated list, with out breaking up list elements
enclosed in backets or parentheses"""
start = 0
level = 0
elements = []
for i in range(0,len(s)):
if s[i] in ["(","[",'{']: level += 1
if s[i] in [")","]",'}']: level -= 1
if s[i] == ",... |
def listit(t):
"""Format deep tuples into deep list
Args:
t (tuple of tuples): deep tuples
Returns:
list[list]: deep list
"""
return list(map(listit, t)) if isinstance(t, (list, tuple)) else t |
def _default_scale(bound, objective):
"""`max{1.0,|objective|}`"""
# avoid using abs() as it uses the same logic, but adds
# additional function call overhead
if objective > 1.0:
return objective
elif objective < -1.0:
return -objective
else:
return 1.0 |
def is_timestamp_ms(timestamp):
"""
:param timestamp:
:return:
"""
timestamp = int(timestamp)
timestamp_length = len(str(timestamp))
if timestamp_length != 13:
raise TypeError('timestamp:({}) is not int or len({}) < 13'.format(
type(timestamp), timestamp_length))
ret... |
def _is_float(string_inp: str) -> bool:
"""Method to check if the given string input can be parsed as a float"""
try:
float(string_inp)
return True
except ValueError:
return False |
def check_config(config, warnings, errors):
"""Checks the config for consistency, returns (config, warnings, errors)"""
if 'server' not in config:
errors.append("No server specified.")
if 'user' not in config:
errors.append("No username specified.")
if ('keyfilename' in config) ^ ('certf... |
def RoundupPow2(a):
"""
Round an integer up to the nearest power of 2.
@return integer
"""
if type(a) != type(0): raise RuntimeError("Only works for ints!")
if a <= 0: raise RuntimeError("Oops, doesn't handle negative values")
next_one_up = 1
while (next_one_up < a):
next_one_... |
def device_name(device):
"""Generate a string name for the device fixture."""
name = device[0]
if device[1] is None:
name += '(all)'
else:
name += '(' + str(device[1]) + ')'
return name |
def trim(string, trim_chars = None):
"""
Strips all whitespace characters from the beginning and end of the `string`. If `trim_chars` is set, instead of whitespace, will replace only those characters.
"""
return string.strip(trim_chars) |
def split_at(collection, index, to_list):
""":yaql:splitAt
Splits collection into two lists by index.
:signature: collection.splitAt(index)
:receiverArg collection: input collection
:argType collection: iterable
:arg index: the index of collection to be delimiter for splitting
:argType ind... |
def merge(a, b):
"""
Function to merge
two arrays / separated lists
:param a: Array 1
:param b: Array 2
:return: merged arrays
"""
c = []
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.appe... |
def akaike_ic(lnl, k):
"""Akaike information criterion"""
return 2 * k - 2 * lnl |
def split_list(n,ls):
"""Split input list into n chunks, remainder of division by n goes into last chunk.
If input list is empty, returns list of n empty lists.
Parameters
----------
n : int
Number of chunks.
ls : list
List to split.
Returns
-------
list
List ... |
def int16(c):
""" Parse a string as a hexadecimal number """
return int(c, 16) |
def is_function(name):
# type: (str) -> bool
"""
Return True if a serializer/deserializer is function.
A function is prefixed with '::' so that the IDL generated code calls it as a function instead
of as a class method.
"""
return name.startswith("::") |
def map_value(x_value, in_min, in_max, out_min, out_max):
"""Maps value of the temperature to color"""
return (x_value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min |
def is_list(annotation):
"""Returns True if annotation is a typing.List"""
annotation_origin = getattr(annotation, "__origin__", None)
return annotation_origin == list |
def should_display_email(email: str) -> bool:
""" Returns true if the given email is not associated with the CCDL suers """
if not email:
return False
return not (
email.startswith("cansav09")
or email.startswith("arielsvn")
or email.startswith("jaclyn.n.taroni")
or ... |
def distribute(included_targets_as_list_size, total_scan_engines_in_pool):
"""Distribute targets to scan engines as evenly as possible. Generates a list of targets per engine. For example,
if there are 13 targets and 3 scan engines, this function will return [5, 4 ,4] - 5 targets for engine1, 4
targets fo... |
def solidsFluxPembNose(dp, db, emf, umf, us):
"""
Calculates the solids entrainment flux for the surface of a bubbling bed
with the bubble nose ejection model of Pemberton and Davidsion (Chem. Eng.
Sci., 1986, 41, pp. 243-251). This model is suitable if there is a single
bubble in the bed.
Para... |
def color_to_rgb(c):
"""Convert a 24 bit color to RGB triplets."""
return ((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF) |
def n_sigdigs_str(x, n):
"""Return a string representation of float x with n significant digits,
where n > 0 is an integer.
"""
format = "%." + str(int(n)) + "g"
s = "%s" % float(format % x)
if "." in s:
# handle trailing ".0" when not one of the sig. digits
pt_idx = s.in... |
def _get_dp_bin(dp):
"""Returns lower bin width for the given depth.
Bin width
- 0..19: 1bp
- 20..49: 5bp
- 50..199: 10bp
- 200..: = 200
"""
if dp < 20:
return dp
elif dp < 50:
return (dp // 2) * 2
elif dp < 200:
return (dp // 5) * 5
else:
re... |
def bbox_intersection_over_union(bbox_a, bbox_b) -> float:
"""Compute intersection over union for two bounding boxes
Args:
bbox_a -- format is (xmin, ymin, xmin+width, ymin+height)
bbox_b -- format is (xmin, ymin, xmin+width, ymin+height)
"""
assert (bbox_a[0] <= bbox_a[2] and bbox_a[1... |
def polevl(x, coef):
"""evaluates a polynomial y = C_0 + C_1x + C_2x^2 + ... + C_Nx^N
Coefficients are stored in reverse order, i.e. coef[0] = C_N
"""
result = 0
for c in coef:
result = result * x + c
return result |
def sanitize_string(string, size=80):
""" Remplazamos los caracteres especiales y truncamos las cadenas largas """
string = string.replace("&", "&").replace("<", "<").replace(">", ">")[:size]
string = string.strip()
return string |
def is_list_unknow_type(type_name):
"""Check if the type is a list of unknow type (Frozen or ndarray or python) "[]"
Parameters
----------
type_name : str
Type of the property
Returns
-------
is_list : bool
True if the type is a list of unknow type
"""
return type_n... |
def clean_value(value):
"""
Trims values
"""
return value.replace("''", "'").strip().rstrip("\0").strip() |
def _to_frac(timestamp, n=32):
"""Return the fractional part of a timestamp.
Parameters:
timestamp -- NTP timestamp
n -- number of bits of the fractional part
Retuns:
fractional part
"""
return int(abs(timestamp - int(timestamp)) * 2**n) |
def _ppbv_to_kg_conversion(GHG):
"""
Convert the radiative efficiency from ppbv normalization to kg normalization.
References
--------------
IPCC 2013. AR5, WG1, Chapter 8 Supplementary Material. p. 8SM-15.
https://www.ipcc.ch/report/ar5/wg1/
"""
# kg per kmol
molecular_weight = {"c... |
def delete_row(a, rownumber):
"""
Return the matrix a without row rownumber
If rownumber is not correct (between 0 et len(a)-1) the function return the a matrix without modification
:param a: a 2 dimensional array
:param rownumber: an int between 0 et len(a)-1
:return: a 2 dimensional array
... |
def dict_get(d, *args):
"""Get the values corresponding to the given keys in the provided dict."""
return [d[arg] for arg in args] |
def dict_bool(x):
"""Implementation of `dict_bool`."""
return len(x) != 0 |
def even_occuring_element(arr):
"""Returns the even occuring element within a list of integers"""
dict = {}
for num in arr:
if num in dict:
dict[num] += 1
else:
dict[num] = 1
for num in dict:
if not dict[num] & 1: # bitwise check for parity.
... |
def index_of_coincidence(frequencies, n):
"""
Calculate the index of coincidence of a frequency
distribution relative to the text length.
Args:
frequencies: the target frequencies to compare the text to.
n: length of the text that the IC should be calculated for.
Returns:
t... |
def _make_list_of_str(arg):
"""
Convert a str to list of str or ensure a list is a list of str
:param list[str] | str arg: string or a list of strings to listify
:return list: list of strings
:raise TypeError: if a fault argument was provided
"""
def _raise_faulty_arg():
raise TypeE... |
def fix_string(string):
""" remove first line (asserts it empty)"""
lines = string.splitlines()
assert not lines[0]
return "\n".join(lines[1:]) |
def concat(*args):
""":yaql:concat
Returns concatenated args.
:signature: concat([args])
:arg [args]: values to be joined
:argType [args]: string
:returnType: string
.. code::
yaql> concat("abc", "de", "f")
"abcdef"
"""
return ''.join(args) |
def mapif(predicate, function, list):
"""
"""
result = list.copy()
for i, x in enumerate(list):
if predicate(x):
result[i] = function(x)
return result |
def calculate_order(params, xc, yc):
"""
Calculate spectral order centre.
Calculate a spectral order centre given the corresponding coefficients and the centre
of the zeroth-order image.
Parameters
----------
params : dict
Dictionary of coefficients. Contains 6 coefficients la... |
def swap_16b(val):
""" Swap 16b val
:param val: 16b value
:return: swapped 16b """
tmp = (val << 8) | (val >> 8)
return tmp & 0xFFFF |
def prune_dict(my_dict):
"""
Remove all keys associated to a null value.
Args:
my_dict (dict): any dictionary
Returns:
pruned_dict (dict): pruned dictionary
"""
# Start from empty dict
pruned_dict = dict()
# Add all entry of dict1 that does not have a null value
... |
def getStatusCode(statusWord):
"""Returns the status code from the status word. """
try:
return ['ordered', 'wished', 'owned'].index(statusWord)
except ValueError:
return -1 |
def counting_sort(items, key=None, max_key=None, min_key=None):
"""
Sorts an array of items by their integer keys, using counting_sort.
Implemented as a stable sort.
This is a modified version of the code described on Wikipedia:
https://en.wikipedia.org/wiki/Counting_sort
Parameters
------... |
def validate_byr(value: str) -> bool:
"""Birth year must be 1920-2002"""
try:
return int(value) in range(1920, 2003)
except (TypeError, ValueError):
return False |
def get_both_marks(record, course_code):
""" (str, str) -> str
Return a string containing the course mark and final mark respectively,
separated by a single space, corresponding to a particular course code
from the record. If the course code is absent from the record
then return an empty stri... |
def fibonacci_iterative(n):
"""
Args:
n (int):
Returns:
int: the n-th fibonacci number
References:
http://stackoverflow.com/questions/15047116/iterative-alg-fib
CommandLine:
python -m utool.util_alg fibonacci_iterative
Example:
>>> # ENABLE_DOCTEST
... |
def pretty_print_shortcut(raw_string):
"""
A custom Jinja 2 filter that formats the list.toString that we get in the frontent for the keyboard shortcut for
the buttons.
Is registered for Jinja in __main__
:param raw_string: the list.toString() string form js
:return: a beautified version of the ... |
def med_product(l):
"""Takes a list of numbers and returns their product. A list of length 1 should return its sole element, and a list of length 0 should return 1."""
return 1 if not l else l[0] * med_product(l[1:]) |
def get_pos(i):
""" return key positions in N253 (1..10) from Meier's Table 2:
0 = blank, if you want to use the peak in the cube
11 = map center, the reference position of N253
"""
pos = [ [], # 0 = blank
['00h47m33.041s', '-25d17m26.61s' ], ... |
def Length(expr):
"""
Returns number of elements in the expression just as SymPy's len.
Examples
========
>>> from sympy.integrals.rubi.utility_function import Length
>>> from sympy.abc import x, a, b
>>> from sympy import cos, sin
>>> Length(a + b)
2
>>> Length(sin(a)*cos(a))
... |
def num_to_str(num, precision=2):
"""
Converts num into a string with `precision` number
of decimal places.
Args:
num (float or int)
precision (int)
Returns:
a string
"""
return '%.{0}f'.format(str(precision)) % num |
def is_multiple(x, y):
"""Determine if the two values passed are multiples/divisors"""
# There were many cases that had to be checked
# If both x and y are 1, they are multiples, but if only 1 coefficient
# is the value 1, then they are not truly multiples.
if x == 1 and y == 1:
... |
def num_from_str(s):
"""Return a num computed from a string."""
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
raise ValueError("Can not convert the string into a numeric value.") |
def create_ref(*parts):
"""Create a reference from `parts`
For example:
assert create_ref("#", "definitions", "foo") == "#/definitions/foo"
:param Tuple[str] parts:
:rtype: str
"""
return "/".join(parts) |
def count_some_palindromes(n, word):
""" list all substrings which are
palindromes repeating the same character like 'aaa' and not 'abcba'
palindromes of uneven length like 'aacaa' and not 'abba'
it is sufficient to look at the last 3 letters read from the string
(l0, l1, l2)
l0 =... |
def total_cost(J_content, J_style, alpha = 10, beta = 40):
"""
Computes the total cost function
Arguments:
J_content -- content cost coded above
J_style -- style cost coded above
alpha -- hyperparameter weighting the importance of the content cost
beta -- hyperparameter weighting the im... |
def _cleanup_non_fields(terms):
"""Removes unwanted fields and empty terms from final json"""
to_delete = 'closure'
tids2delete = []
for termid, term in terms.items():
if not term:
tids2delete.append(termid)
else:
if to_delete in term:
del term[to_... |
def intersect(a,b):
"""Intersect two lists"""
return [val for val in a if val in b] |
def fibonacci1(n):
"""
Recursive descendant version.
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci1(n - 1) + fibonacci1(n - 2) |
def tokenize_phoneme(phoneme):
"""
tokenizer for phoneme
"""
return phoneme.split() |
def logistic(x, r):
"""Logistic map, with parameter r."""
return r * x * (1 - x) |
def show_post(post_id):
"""
show the post with the given id, the id is an integer
@param post_id:
@return:
"""
return 'Post %d' % post_id |
def parse_exclude_patterns(raw_pattern_list):
"""
:param list[str] raw_pattern_list:
:return:
"""
if not raw_pattern_list:
return []
# line no cast to int. because comparing easily.
return [(x.split(":")[0], int(x.split(":")[1])) for x in raw_pattern_list] |
def isNumber(txt):
"""
>>> isNumber('1 2 3')
False
>>> isNumber('- 156.3')
False
>>> isNumber(' 29.99999999 ')
True
>>> isNumber(' 5.9999x ')
False
"""
# use for loop to search
if not isinstance(txt, str) or len(txt) == 0:
... |
def string_from_arsdkxml(_input):
"""
This is an utility function that convert any string (or object) coming from arsdkparser to
a unicode string where ascii escape sequences have been processed (ex:"\\n" -> "\n").
"""
if not _input:
# Handles empty string and None (we don't actually handle ... |
def find_ips_supporting(ips, support_check):
"""Find IPs fulfilling support_check function."""
return [ip for ip in ips if support_check(ip)] |
def ortho_line_cf(a, b, x0, y0):
"""
get orthogonal line to y = ax * b
"""
if a is None: # x=const
a2 = 0
b2 = y0
elif abs(a - 0.0) < 1e-6: # y=const
a2 = None
b2 = x0
else:
a2 = -1.0 / a
b2 = y0 - a2 * x0
return a2, b2 |
def saddle_points(matrix):
"""
Return coordinates of all saddle points
"""
if len({len(row) for row in matrix}) > 1:
raise ValueError("irregular matrix")
result = []
for i, row in enumerate(matrix):
for j, cell in enumerate(row):
if cell == max(row):
... |
def int_to_hex(value):
"""Convert integer to two digit hex."""
hex = '{0:02x}'.format(int(value))
return hex |
def category(char):
"""Classify `char` into: punctuation, digit, non-digit."""
if char in ('.', '-'):
return 0
if char in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):
return 1
return 2 |
def is_profile_flag(flag):
""" return true if provided profile flag is valid """
return flag in ('cpu', 'mem', 'block', 'trace') |
def list_has_duplicates(values):
"""
https://www.dotnetperls.com/duplicates-python
"""
# For each element, check all following elements for a duplicate.
for i in range(0, len(values)):
for x in range(i + 1, len(values)):
if values[i] == values[x]:
return True
return False |
def _correct_url_number(text):
"""Checks that the schema definition contains only one url definition.
Args:
text (str): The schema definition.
Returns:
bool: Whether only one url is defined.
"""
url_count = text.count("@url")
return url_count == 1 |
def any_of(*args):
"""
Matches to any of the specified arguments with == operator
"""
class AnyOfMatcher:
def __init__(self, values):
self.values = values
def __eq__(self, other):
return any(map(lambda v: v == other, self.values))
def __ne__(self, other)... |
def linear_map(xs, palette, low=None, high=None):
"""Map (linearly) a sequence of real values to the given palette.
Parameters:
xs - A list of numbers, in the range [low, high]
palette - A list of colors
Returns:
A list of the same size of xs, with the color of each sample
... |
def _is_not_empty(value):
"""Check if value is empty value or a tuple of empty values."""
if isinstance(value, tuple):
return any(bool(elem) for elem in value)
return bool(value) |
def is_list_of_list(value):
"""
Check if all elements in a list are tuples
:param value:
:return:
"""
return bool(value) and isinstance(value, list) and all(isinstance(elem, list) for elem in value) |
def _extract_feature_values(eopatches, feature):
""" A helper function that extracts a feature values from those EOPatches where a feature exists.
"""
feature_type, feature_name = feature
return [eopatch[feature] for eopatch in eopatches if feature_name in eopatch[feature_type]] |
def set_defaults(lvm_data):
"""dict: Sets all existing null string values to None."""
for l in lvm_data:
for k, v in lvm_data[l].items():
if v == '':
lvm_data[l][k] = None
return lvm_data |
def image_proc_desaturate( image ):
"""
Desaturate the image.
The function uses Rec. 709 luma component factors:
OUT = 0.2989 R + 0.587 G + 0.114 B
"""
output_image = []
for row in image:
output_row = []
for pixel in row:
output_row.append( 0.2989 * pixel[0] + ... |
def percent_of(value, arg):
"""Removes all values of arg from the given string"""
return round(value/arg *100) |
def get_base_venv_path(pyversion: str) -> str:
"""Return the base virtual environment path relative to the current directory."""
pyversion = str(pyversion).replace(".", "")
return f".riot/.venv_py{pyversion}" |
def _get_job_dir(jenkins_directory, job_name):
"""
Returns the directory for a job configuration file relative
to the jenkins home directory.
"""
return jenkins_directory + '/jobs/' + job_name |
def make_full_endpoint(endpoint, url_param_names, fn_args):
"""
Args:
- endpoint: (str) e.g. "/survey/{survey_id}"
- url_param_names: (list of str) e.g. ["survey_id"]
- fn_args: (list) e.g. ["id_1"]
Returns: (str) the endpoint interpolated with the given args
e.g. "/sur... |
def join(*paths):
"""Like os.path.join but doesn't treat absolute RHS specially"""
import os.path
return os.path.normpath("/".join(paths)) |
def _calculate_parcel_grain_diameter_post_abrasion(
starting_diameter, pre_abrasion_volume, post_abrasion_volume
):
"""Calculate parcel grain diameters after abrasion, according to Sternberg
exponential abrasion.
Parameters
----------
starting_diameter : float or array
Starting volume o... |
def convertDBZtoGranizo(dbz):
"""
Funcion para convertir el valor de dbz a granizo
param: dbz : valor
"""
if dbz >= 55:
granizo = ((10**(dbz/10))/200)**(5/8)
if granizo <= 1:
return 0
else:
return granizo
else:
return 0 |
def split_host_and_port(host):
"""
Splits a string into its host and port components
:param host: a string matching the following patern: <host name | ip address>[:port]
:return: a Dictionary containing 'host' and 'port' entries for the input value
"""
if host is None:
host_and_port = None
else:
... |
def list_scanner(array_list, index=0):
"""
scanner list.
:param array_list: <tuple>
:param index: <int> the index to search the array list from.
:return: <tuple> array of 3 tuples of XYZ values.
"""
if index == 0:
return array_list[index], array_list[index], array_list[index + 1],
... |
def flatten_path(path):
"""Returns the file name in the path without the directory before"""
return path.split("/")[-1] |
def remove_special_characters(value, remove_spaces=True):
"""
Removes all special characters from a string, so only [a-Z] and [0-9] stay.
:param value: The value where the characters need to be removed from.
:type value: str
:param remove_spaces: If true the spaces are also going to be removed.
... |
def get_resource_suffix(params):
"""
This function generates the part of suffix of result folders that pertains to resource cap(s).
Parameters
----------
params : dict
Parameters that are needed to run the indp optimization.
Returns
-------
out_dir_suffix_res : str
The pa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.