content stringlengths 42 6.51k |
|---|
def split_by_unicode_char(input_strs):
"""
Split utf-8 strings to unicode characters
"""
out = []
for s in input_strs:
out.append([c for c in s])
return out |
def GetBgpRoutingMode(network):
"""Returns the BGP routing mode of the input network."""
return network.get('routingConfig', {}).get('routingMode') |
def removeWhitespaceChars(s):
"""
Removes whitespace characters
@ In, s, string, to remove characters from
@ Out, s, string, removed whitespace string
"""
s = s.replace(" ","")
s = s.replace("\t","")
s = s.replace("\n","")
#if this were python3 this would work:
#removeWhitespaceTrans = "".make... |
def _parameters_exists_in_docstring(docstring: str) -> bool:
"""
Get boolean of whether Parater part exists in docstring
or not.
Parameters
----------
docstring : str
Docstring to be checked.
Returns
-------
result_bool : bool
If exists, True will be set.
"""
... |
def cutadapt_cut(s, cut_para=True):
"""
recognize para: cut for cutadapt
eg: cut=6, cut=-3, cut=6,-3
"""
if ',' in s:
n = s.split(',')
if len(n) > 2:
raise ValueError('illegal ad_cut: %s' % s)
else:
c1, c2 = (int(n[0]), int(n[1]))
if c1 < 0... |
def vector_subtraction(p1, p2):
"""
Returns the difference between 2 vectors
p1 and p2 are vectors in 2d space
@param: tuple: (int,int), tuple: (int,int)
@return: tuple(int, int)
"""
return (
p1[0] - p2[0],
p1[1] - p2[1]
) |
def trapmf(x, a, b, c, d):
"""
Trapezoidal membership function generator.
Parameters
========
x : single element array like
abcd : 1d array, length 4
Four-element vector. Ensure a <= b <= c <= d.
Returns
========
y : 1d array
Trapezoidal membership function.
"""
... |
def variation_string_to_dict(variation_string, separator="="):
"""Helper function to convert a list of "="-separated strings into a dictionary
Returns
-------
dict
"""
var_data = variation_string.split()
variation_dict = {}
for var in var_data:
pos_eq = var.find("=")
var... |
def merge_fields(*fields):
"""
Provided as a convenience to merge multiple groups of fields. Equivalent
to: `fields.update(**other_fields)`. Dictionaries are processed in order
and overwrite fields that are already present.
Parameters
----------
fields : *args
Field dictionaries ... |
def merge(a, b):
""" merge two already sorted lists """
s = []
index_a = 0;
index_b = 0;
while index_a < len(a) and index_b < len(b):
if a[index_a] < b[index_b]:
s.append(a[index_a])
index_a += 1
else:
s.append(b[index_b])
index_b += 1... |
def parse_gff_attributes( attr_str ):
"""
Parses a GFF/GTF attribute string and returns a dictionary of name-value
pairs. The general format for a GFF3 attributes string is
name1=value1;name2=value2
The general format for a GTF attribute string is
name1 "value1" ; name2 "value2"
The ... |
def to_pc(val):
"""Convert float value in [0, 1] to percentage"""
return r'%.2f\%%' % (val * 100) |
def find_dupes(facts):
"""Find hosts with duplicate SSH host keys from PuppetDB output"""
hosts_by_key = {}
for fact in facts:
hosts_by_key.setdefault(
fact['value'],
set(),
).add(fact['certname'])
return {
k: v
for k, v in hosts_by_key.items()
... |
def isblankstr(line):
"""
check for blank string
:param line:
:return bool:
"""
return len(line.strip()) == 0 |
def mean_free_path(T, P, lamb_0=67.3, T_0=296.15, P_0=101325, S=110.4):
""" calculates mean free path of the aerosol particles
Parameters
----------
T : float
measurement temperature
P : float
measurement pressure
lamb_0 : float
reference mean free path
T_0 ... |
def fpack(f,*args,**kwargs):
"""
Pack a function and its arguments into the format:
Tuple#2:
f
Tuple#2:
arguments,keyword arguments
"""
return (f,args,kwargs) |
def _remove_none_from_post_data_additional_rules_list(json):
"""
removes hidden field value from json field "additional_rules" list,
which is there to ensure field exists for editing purposes
:param json: this is data that is going to be posted
"""
data = json
additional_rules = json.get... |
def _merge_majorana_terms(left_term, right_term):
"""Merge two Majorana terms.
Args:
left_term (Tuple[int]): The left-hand term
right_term (Tuple[int]): The right-hand term
Returns:
Tuple[Tuple[int], int]. The first object returned is a sorted list
representing the indices ... |
def first_in_dict(d):
"""Grabs the value returned by the first value in d.keys()"""
if len(d) > 0:
k = d.keys()[0]
return d[k]
return None |
def makes10(a: int, b: int) -> bool:
"""Determine if the sum or if either a,b is 10."""
return (a + b == 10 or a == 10 or b == 10) |
def ytb_rss(user):
"""Return the url for the rss format."""
return "http://gdata.youtube.com/feeds/base/users/{0}/uploads?alt=rss".format(user) |
def format_obj_value(obj, default='-'):
"""common formatting object field"""
if not obj:
return default
return obj |
def clean_url(url, leading_slash=False):
"""
remove trailing slash if it exists
:param url:
:return: url without training slash
"""
new_url = url[:-1] if url.endswith("/") else url
if leading_slash:
new_url = new_url[1:] if new_url.startswith("/") else new_url
return new_url |
def filter_credit_score(credit_score, bank_list):
"""Filters the bank list by the mininim allowed credit score set by the bank.
Args:
credit_score (int): The applicant's credit score.
bank_list (list of lists): The available bank loans.
Returns:
A list of qualifying bank loans.
... |
def aggregate_customers_sessions(sessions):
"""
Receives as input what products customers interacted with and returns their final
aggregation.
Args
----
sessions: list of list of dicts.
List where each element is a list of dict of type: [{'action': '', 'sku': ''}]
... |
def str2bool(s):
"""Convert string to bool."""
return s.strip().lower() == "true" |
def change_speed(body, speed=1):
"""Change the voice speed of the wave body."""
if speed == 1:
return body
length = int(len(body) * speed)
rv = bytearray(length)
step = 0
for v in body:
i = int(step)
while i < int(step + speed) and i < length:
rv[i] = v
... |
def parse_throttle_response(event, resp, key_name):
"""
Parse the get_metric_statistics() response.
Adds the key specified by key_name to the event dictionary. The value is
True if write throttles detected in the last minute.
Args:
event (dict): Event dictionary passed to lambda function... |
def replace_xml(content_list):
"""Replaces XML entities in notes with HTML tags."""
return [c.replace("extref", "a") for c in content_list] |
def get_project_variant_rules(config, variant, rule):
"""The rules we want to check are specified in nested dictionaries. They all follow the same
structure, so this is a short helper to fetch a list of functions, corresponding to the
rules evaluated for a given project and variant.
:type project... |
def complex_delete(a_dictionary, value):
"""Delete keys with a specific value in a dictionary."""
while value in a_dictionary.values():
for k, v in a_dictionary.items():
if v == value:
del a_dictionary[k]
break
return (a_dictionary) |
def short_information(title, index=0):
"""
Takes in track information and returns everything as a short formatted String.
Args:
title (str): track title string
index (str): optional track number string
Returns:
A short formatted string of all track information.
"""
if ... |
def filter_data(data_, flag):
"""
Set flag = False for oxygen generator & flag = True for CO2 scrubber
"""
data = data_.copy()
ind = 0
while len(data) > 1:
count_zero = 0
for s in data:
count_zero += s[ind] == '0'
ch = '0' if count_zero > len(data) - count_zer... |
def download_speed(kbytes_per_second):
"""Returns HTML markup for KB/s."""
if not kbytes_per_second: # includes None and 0 intentionally.
return 'N/A'
if kbytes_per_second < 1024:
return '%s KB/s' % kbytes_per_second
else:
return '%.2f MB/s' % (float(kbytes_per_second) / 1024) |
def to_bits(_bytes: bytes) -> list:
"""Convert bytes to a bit list"""
bits = []
offset = 0
for byte in _bytes:
for i in range(8):
bits.insert(0+offset,(byte >> i) & 1)
offset += 8
return bits |
def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
""" Returns a human readable string reprentation of bytes"""
return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:]) |
def to_camel_case(snake_case_str: str) -> str:
""" Convert snake_case_str to camelCaseStr """
parts = snake_case_str.split('_')
return parts[0] + ''.join(w.capitalize() or '_' for w in parts[1:]) |
def fill_template(params, structure, template):
"""
Fill template using structured params.
:param params:
:param structure:
:param template:
:return:
"""
try:
structured_params = structure(*params)
except TypeError: # params may be a single value
structured_params = ... |
def date_formats(request):
"""
date_formats
"""
return {
'date_format_long': 'l j F Y',
} |
def label_map(x): # pylint: disable=function-redefined
"""Mapping the original labels."""
if x == 1:
return 1
else:
return -1 |
def try_string_to_number(string_in):
"""This function attempts to convert a string to either an integer
or a float. If both conversions fail, the string is simply
returned unmodified."""
try:
myout = int(string_in)
except:
try:
myout = float(string_in)
except:
... |
def split_role(role):
"""
Return a tuple of cluster, type, and id
If no cluster is included in the role, the default cluster, 'ceph', is used
"""
cluster = 'ceph'
if role.count('.') > 1:
cluster, role = role.split('.', 1)
type_, id_ = role.split('.', 1)
return cluster, type_, id_ |
def is_valid(username: str) -> bool:
"""
Return True if specified username is valid, False otherwise.
>>> is_valid("BarackObama")
True
>>> is_valid("b.23")
False
>>> is_valid("Helloworld ")
False
"""
for char in username:
if (97 <= ord(char) <= 122) or (65 <= ord(char) ... |
def unify_linebreaks(text):
"""Helper to return a string with all line breaks converted to LF.
Args:
text: a string.
Returns:
A string with all line breaks converted to LF.
"""
return text.replace('\r\n', '\n').replace('\r', '\n') |
def replace_nth_column_of_matrix(column_vector, M, column_num):
"""
Replace a column in an existing matrix
:param column_vector: The new column vector
:param M: The matrix needing column update
:param column_num: The location of the column in M
:return: The matrix with the colum... |
def get_indicator_type_value_pair(field):
"""
Extracts the type/value pair from a generic field. This is generally used on
fields that can become indicators such as objects or email fields.
The type/value pairs are used in indicator relationships
since indicators are uniquely identified via their ty... |
def split_url_path(path):
"""
Separates URL path to repository name and path.
# Parameters
path (str): The path from URL.
# Return
tuple (str, str): The repository name and the path to be listed.
"""
separator = "/"
parts = path.split(separator)
return separator.join(parts[0:2... |
def GetAlleleString(allele):
"""Get string representation of allele
If it is a sequence, return upper case sequence
If _SV type, return string representation
Parameters
----------
allele : ALT allele from vcf.Record
Returns
-------
str_allele : str
String representa... |
def text_var(name, value, desc=None):
"""Create a variable NAME with a given VALUE.
Primarily for output to LaTeX.
Returns a string."""
return "".join(['Note: ', str(name), ' is ', str(value)] + ([' (', desc, ')'] if desc else [])) |
def fp(obj):
"""render_formula parameters"""
return {
"const_separator": ".",
"repeat_type_name_for_enums": True,
"enum_separator": ".",
"inhibit_fqn_for_parent": obj,
} |
def sec2year(seconds):
"""
Convert seconds into decimal Julian years.
Julian years have 365.25 days.
Parameters:
* seconds : float
Time in seconds
Returns:
* years : float
Time in years
Example::
>>> print sec2year(31557600)
1.0
"""
return ... |
def get_var(data, var_name, not_found=None):
"""Gets variable value from data dictionary."""
try:
for key in str(var_name).split('.'):
try:
data = data[key]
except TypeError:
data = data[int(key)]
except (KeyError, TypeError, ValueError):
... |
def _get_type_to_speed(cfs):
"""Given a list of charging functions, returns an object whose keys
are the CS types and values are speed rank.
Speed rank is a CS type's (0-indexed) position in the ordered list of fastest CS types.
"""
# compute max charge rates by type
result = [{
'cs_ty... |
def parabolic_backtrack(f0, g0, x1, f1, b1=0.1, b2=0.5):
"""
Safeguarded parabolic backtracking function
Equation provided in Nocedal & Wright, 2006 ??
:type f0: float
:param f0: initial misfit function value
:type g0: float
:param g0: slope
:type x1: float
:param x1: step length va... |
def is_int(val):
"""Checks if type can be cast to numeric value"""
try:
if float(val).is_integer():
return True
else:
return False
except ValueError:
return False |
def nestifyMatrix(listeddata, rowcount, colcount):
"""
Performs the inverse function of listifymatrix() method.
"""
clist = listeddata
nested = []
for _i in range(rowcount):
nested.append(clist[0:colcount])
del clist[0:colcount]
return nested |
def match_list_class(a_list, a_base):
"""
Every element of `a_list' that start with the same character of
`a_base'.
"""
result = []
for element in a_list:
if a_base.upper() == element[:len(a_base)].upper():
result.append(element)
return result |
def validate_bibleplay_address_format(address):
""" ensures that the address given looks like a valid biblepay address """
# the addresses are always 34 chars long
if len(address) != 34:
return False
# real addresses start with a B, testnet with an y
if not address[0] in ['B'... |
def product(numbers):
"""Return the product of the numbers, e.g. product([2, 3, 10]) == 60"""
result = 1
for x in numbers:
result *= x
return result |
def check_tag_exist(tags: list, tag_key: str, tag_value: str = '') -> bool:
"""
Checks whether a specified tag is in the list of given tags.
"""
for tag in tags:
if tag_value:
if tag.get('Key') == tag_key and tag.get('Value') == tag_value:
return True
else:
... |
def is_kind_of_class(obj, a_class):
"""returns
True if the object is an instance of, or if the object is an
instance of a class that inherited from, the specified class ;
otherwise False.
Arguments:
obj (obj) -- obj.
a_class (class) -- class.
Returns:
boolean -- True / ... |
def sigmoid_derivative(x):
"""Derivative to the Sigmoid function"""
return x * (1 - x) |
def nside_for_nbsrc(nbsrc):
"""
Chooses the best suited NSIDE value according
to the number of sources
"""
if nbsrc>1e8:
return 256
elif nbsrc>1e7:
return 128
elif nbsrc>1e6:
return 64
else:
return 32 |
def divide(data, params=None):
"""
Divide function aggregation.
Example config:
.. code-block:: python
config = {
...
'fields': ['timestamp', 'energy'],
'aggregations': [
{
'func': 'divide',
'field': '... |
def generate_server_args_str(server_args):
""" Create a server args string to pass to the DBMS """
server_args_arr = []
for attribute, value in server_args.items():
value = str(value).lower() if isinstance(value, bool) else value
value = f'={value}' if value != None else ''
arg = f'-... |
def circular_distance(a: int, b: int, C: int) -> int:
"""
Finds the shortest distance between two points along the perimeter of a circle.
arguments:
a: a point on a circle's circumference.
b: another point on the cicrle.
C: the total circumference of the circle.
return:
... |
def getCleanNamespace(namespace):
"""Clean the namespace that is inferred from a directory structure.
Args:
namesapce: the namespace
Returns:
Clean namespace
"""
nslevels = namespace.split(".")
finalLevel = len(nslevels)
for i in range(len(nslevels) - 1, -1, -1):
... |
def perimeterRect(length: float, breadth: float) -> float:
"""Finds perimeter of rectangle"""
perimeter: float = 2 * (length + breadth)
return perimeter |
def get_genome_build(variant_case_obj):
"""Find genom build in `variant_case_obj`. If not found use build #37"""
build = variant_case_obj.get("genome_build")
if build in ["37", "38"]:
return build
return "37" |
def value_ordered_keys(dic):
"""
Return the keys of a dictionary order by its values. Useful to get the
inverse mapping of an id to offset dictionary.
"""
return [k for k, _ in sorted(dic.items(), key=lambda p: p[1])] |
def tags_from(element):
"""Receive element from dataset and return separated tags"""
tags = list(map(lambda token: token[1], element["tags"]))
return tags |
def check_dup_contig_overlap(blast_start, blast_end, contig_len, threshold):
""" Checks if the blast hit covers a certain amount of the contig length
"""
overlap = 0
blast_len = blast_end - blast_start
if(contig_len != 0):
overlap = float(blast_len) / float(contig_len) * 100
# I... |
def _to_io_meta(shape_meta, valid_keys, key_mappings):
"""
Make metadata compatible with a specific IO by filtering and mapping
to its valid keys.
Parameters
----------
shape_meta : dict
A meta attribute of a `regions.Region` object.
valid_keys : list
The valid keys of a pa... |
def build_tweet_url(screen_name, tweet_id):
"""Builds the url to a tweet"""
return f'https://twitter.com/{screen_name}/status/{tweet_id}' |
def get_model_constructor(config):
"""Return default model constructor."""
default_type = 'DefaultModelConstructor'
default_args = {}
default_args['model_type'] = config['type']
if 'args' in config:
default_args['args'] = config['args']
return {'type': default_type, 'args': default_args} |
def param_name(p):
"""Extract parameter name from attributes.
Examples
--------
- ``fix_x`` -> ``x``
- ``error_x`` -> ``x``
- ``limit_x`` -> ``x``
"""
prefix = ["limit_", "error_", "fix_"]
for prf in prefix:
if p.startswith(prf):
i = len(prf)
return ... |
def mod_list_as_str(str_list, add=None, remove=None, prefix='', suffix='', ignore=[]):
"""Function to take a delimited strings, and add or remove anything in the
list add or the list remove... Can also add prefixes or suffixes to items in str list.
Ignore is a list of items in the list not to add a pre... |
def list2cmdline(seq):
"""
Modified version of the original from subprocess.py
"""
result = []
needquote = False
for arg in seq:
bs_buf = []
# Add a space to separate this argument from the others
if result:
result.append(' ')
needquote = (" " in arg) or ("\t" in arg) or (";" in arg) or not arg
if ... |
def set_ranks(taxonomy):
"""Set ranks for species/subspecies creation."""
default_ranks = [
"genus",
"family",
"order",
"class",
"subphylum",
"phylum",
]
taxon_rank = None
if "subspecies" in taxonomy:
ranks = ["species"] + default_ranks
... |
def run_pipeline_on(pipeline, item, **kwargs):
"""
Helper function for running the pipeline on the item, returns the processed item.
:param pipeline: pipeline or Pr
:param item: item to be processed
:param kwargs: the keyword arguments to pass on to the Prs
:return: processed item
"""
if... |
def example(data):
"""
example function returns string
Returns:
str: simple string
"""
return f'{data} world!' |
def force_bytes(value):
"""
Forces a Unicode string to become a bytestring.
"""
if isinstance(value, str):
value = value.encode("utf-8", "backslashreplace")
return value |
def get_data_flows(blocks):
"""
Given a block dictonary from bifrost.proclog.load_by_pid(), return a list
of chains that give the data flow.
"""
# Find out what rings we have to work with and which blocks are sources
# or sinks
rings = []
sources, sourceRings = [], []
sinks, sinkRi... |
def x_distance(coordinate_tuple):
"""Intake a coordinate tuple, return the net x vector value"""
x1 = coordinate_tuple[0]
x2 = coordinate_tuple[2]
return x2-x1 |
def maximum69Number(num):
"""
:type num: int
:rtype: int
"""
res = ""
res_l = []
str_num = str(num)
for i in range(len(str_num)):
if str_num[i] == "9":
res = str_num[:i] + "6" + str_num[i + 1:]
elif str_num[i] == "6":
res = str_num[:i] + "9" + str_... |
def good_power(x,n):
"""Compute the value x**n for integer n."""
if n==0:
return 1
else:
partial = good_power(x, n // 2)
result = partial *partial
if n%2 == 1:
result *= x
return result |
def josephus(n, k):
"""
josephus(n, k) = (josephus(n-1, k) + k) % n
josephus(1, k) = 0
After the first person (kth from beginning) is killed, n-1 persons are left
So we call josephus(n-1, k) to get the position with n-1 persons. But the
position returned by josephus(n-1, k) will consider the po... |
def get_short_module_name(module_name, obj_name):
""" Get the shortest possible module name """
parts = module_name.split('.')
short_name = module_name
for i in range(len(parts) - 1, 0, -1):
short_name = '.'.join(parts[:i])
try:
exec('from %s import %s' % (short_name, obj_nam... |
def _infer_casing(string):
"""Guesses the case of a string."""
# Acceptable cases
cases = ['lower', 'title', 'capitalize', 'upper']
found_cases = [case for case in cases
if getattr(str, case)(string) == string]
return found_cases |
def merge_dict2(d1: dict, d2: dict) -> dict:
"""
Merges exactly 2 dicts (For use when the syntax can't be remembered to
do it inline as {**d1, **d2}
NB: If the same key exists in both then d2 takes precedence
:param d1: Dict 1
:param d2: Dict 2
:return: {**d1, **d2}
"""
return {**d1,... |
def _profile_hook(name, func, *args):
"""
Call `func(*args)` and return its result. This function is replaced by
:func:`_real_profile_hook` when :func:`enable_profiling` is called. This
interface is obsolete and will be replaced by a signals-based integration
later on.
"""
return func(*args) |
def oxy_ml_to_umolkg(oxy_mL_L, sigma0):
"""Convert dissolved oxygen from units of mL/L to micromol/kg.
Parameters
----------
oxy_mL_L : array-like
Dissolved oxygen in units of [mL/L]
sigma0 : array-like
Potential density anomaly (i.e. sigma - 1000) referenced to 0 dbar [kg/m^3]
... |
def eachAsArgs(listOfArgs, f):
"""eachAsArgs(f, listOfArgs)
Answers [f(*args) for args in listOfArgs]"""
return [f(*args) for args in listOfArgs] |
def reverse(graph):
"""replace all arcs (u, v) by arcs (v, u) in a graph"""
rev_graph = [[] for node in graph]
for node, _ in enumerate(graph):
for neighbor in graph[node]:
rev_graph[neighbor].append(node)
return rev_graph |
def get_param(tess_profile:dict):
"""
Read the parameters for the api func call
:param tess_profile:
:return:
"""
# Set Parameters
parameters = {}
if 'parameters' in tess_profile:
for param in tess_profile['parameters']:
if param != "":
if "tessdata-di... |
def get_name(metadata):
"""Return the name of an object based on the dictionary metadata. By preference: long_name, short_name, 'Unnamed'
"""
name = metadata.get("long_name", None)
if name is not None:
return name
name = metadata.get("short_name", None)
if name is not None:
retu... |
def mapv(f, *colls):
"""Returns a list consisting of the result of applying f to the
set of first items of each coll, followed by applying f to the set
of second items in each coll, until any one of the colls is
exhausted. Any remaining items in other colls are ignored. Function
f should accept number-of-colls arg... |
def fallbackSeries(requestContext, seriesList, fallback):
"""
Takes a wildcard seriesList, and a second fallback metric.
If the wildcard does not match any series, draws the fallback metric.
Example:
.. code-block:: none
&target=fallbackSeries(server*.requests_per_second, constantLine(0))
... |
def merge_mappings(m1, m2, path):
"""Recursively merge the contents of m2 into m1"""
if type(m1) is not type(m2): raise ValueError("Cannot merge %s and %s" % (type(m1), type(m2)))
if type(m1) is str:
if m1 == m2: return m1 # Attempting to merge "foo" into "foo" just produces "foo"
# Actually.... the Valve-provid... |
def get_byte(byte_str):
"""
Get a byte from byte string
:param byte_str: byte string
:return: byte string, byte
"""
byte = byte_str[0]
byte_str = byte_str[1:]
return byte_str, byte |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.