content stringlengths 42 6.51k |
|---|
def memoized_triple_step(step):
"""Find number of step combinations for maximum of three steps at a time
:param step Number of steps left
:return Number of step combinations
"""
if step < 0:
return 0
elif step == 0:
return 1
return memoized_triple_step(step - 3) + \
... |
def obs_color_hsluv(obs, subobs):
"""
Return a nice color for the given observable in HSLuv space.
Use obs_color() to obtain an RGB color.
"""
if obs in {'dNch_deta', 'pT_fluct'}:
return 250, 90, 55
if obs == 'dET_deta':
return 10, 65, 55
if obs in {'dN_dy', 'mean_pT'}:
... |
def formatting_time(float_time):
"""
Computes the estimated time as a formatted string as well
"""
if float_time > 3600: time_str = '{:.2f}h'.format(float_time / 3600);
elif float_time > 60: time_str = '{:.2f}m'.format(float_time / 60);
else: time_str = '{:.2f}s'.format(float_time);
return... |
def grid(grid_width=None,
grid_height=None,
grid_top=None,
grid_bottom=None,
grid_left=None,
grid_right=None,
**kwargs):
"""
:param series:
other chart series data
:param grid_width:
Width of grid component. Adaptive by default.
:para... |
def decorate(string, *formats):
"""Decorates a string using ANSI escape codes given some format enums.
Calling len(s) on a string which has been decorated in this manner will not
return the printed width. Call len(ansi_undecorate(s)) to achieve this.
Args:
string: string to decorate.
... |
def to_terminal_node(group):
"""Creates a terminal node value comprising of all instances present in the given group
Returns:
the majority label, i.e., the label used to classify the biggest amount of instances in the group
"""
# get the label of each instance in the group
outcomes = [row[-... |
def debatch(data):
"""
convert batch size 1 to None
"""
for key in data:
if isinstance(data[key], list):
assert len(data[key]) == 1, "can't debatch with batch size greater than 1"
data[key] = data[key][0]
return data |
def all_equal(lst):
"""Returns true if all items in the list are equal."""
return len(set(lst)) == 1 |
def snake_distance(a, b):
"""
Calculate the Manhattan distance of two vectors.
"""
distance = 0
for x, y in zip(a, b):
distance += (x - y)
return distance |
def generate_ascending_descending(power):
"""
Generates lists that have ascending and descending elements
:param power: power of 2
:return: generated lists
"""
ascending = []
for i in range(2 ** power):
ascending.append(i)
descending = ascending[::-1]
return ascending, descen... |
def orderlex(l1, l2, n1, n2):
""" lexicographic order on infinite words, returns :
0 if the n1-th shift of l1^infty is smaller than the n2-th shift of l2^infty, 1 if it is larger, and 2 if the two words coincide
(this can be determined by looking only length(l1)+length(l2) letters since u^infty = v^infty ... |
def password_check(passwd):
"""
Taken from geeksforgeeks.org/password-validation-in-python/
This method is used to restrict password for registration process.
:param passwd:
:return:
"""
SpecialSym = ['$', '@', '#', '%', '.', ',']
val = True
if len(passwd) < 6:
print('length... |
def code(value: int) -> str:
"""Constructs an ANSI code with the provided `value`."""
return f'\033[{value}m' |
def count_to_read(link_counters):
"""Find the to_read count in the counters returned by a CommunicationLink."""
for processor in link_counters.values():
if 'to_read' in processor:
return processor['to_read'] |
def get_related_topics(section_div):
"""Get topics related to the current topic.
Parameters
----------
section_div : bs4.BeautifulSoup
The BeautifulSoup object corresponding to the div with the "class"
attribute equal to "section" in the html doc file.
Returns
-------
Str:
... |
def uri_to_entity_code(uri: str) -> str:
"""Translates URIs such as http://lcsb.uni.lu/biokb/entities/BTO_0001043 to BTO:0001043
Replaces only the first underscore with colon.
Arguments:
uri {str} -- [description]
Returns:
str -- [description]
"""
return uri.split('/')[-1].repl... |
def dct_reduce(reduce_fn, dcts):
"""Similar to `reduce`, but applies reduce_fn to fields of dicts with the
same name.
>>> dct_reduce(sum, [{"a": 1}, {"a": 2}])
{'a': 3}
"""
keys = dcts[0].keys()
return {key: reduce_fn([item[key] for item in dcts]) for key in keys} |
def _get_post_processing(params: dict) -> dict:
"""
Extract and set defaults for the post processing options
"""
pp = params.get('post_processing', {})
# ids_only - shortcut to mark both skips as true and include_highlight as false.
if pp.get('ids_only') == 1:
pp['include_highlight'] = 0... |
def get_party_leads_sql_string_for_state(party_id, state_id):
"""
:type party_id: integer
"""
str = """ select
lr.candidate_id,
c.fullname as winning_candidate,
lr.constituency_id,
cons.name as constituency,
lr.party_id,
lr.max_votes,
(lr.max_votes-sr.votes) ... |
def get_db_name(db_prefix):
"""Build the SQLite DB name from the prefix."""
return '{}.sqlite.db'.format(db_prefix) |
def scale_bbox_noUB(bbox_list, width, height):
"""
Normalize a bounding box give max_x and max_y.
:param bbox_list: list of list of coodinates in format: [xmin, ymin, xmax, ymax]
:param width: image max width.
:param height: image max height
:return: list of list of normalized coordinates.
"... |
def triangle_random_points(num_points, loop_triangles):
"""
Generates a list of random points over mesh loop triangles.
:arg num_points: the number of random points to generate on each triangle.
:type int:
:arg loop_triangles: list of the triangles to generate points on.
:type loop_triangles: :... |
def check_if_file_exists_on_disk(filepath):
"""
Checks if the file exists on the disk.
Could use os.path.exists() but some its safer to do that following.
@param filepath: path to the file including the filename
"""
try :
with open(filepath) as f :
return True
except :
... |
def egcd(a, b):
"""return a tuple of three values: x, y and z, such that x is
the GCD of a and b, and x = y * a + z * b"""
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y) |
def hex_to_float(val, decimals = 0):
"""Converts hex string, int or float to float. Accepts `decimals`.
Returns a float or error (which should be handled in situ).
"""
try:
val = int(val, 16)
except:
val = val
return float(val / 10 ** decimals) |
def darsium(number) -> bool:
"""It will check whether the entered number is a darsium number or not."""
s = 0
n = number
c = 0
p = n
x = n
while(p != 0):
p = p//10
c += 1
while(n != 0):
r = n % 10
s = s+(r**c)
c = c-1
n = n//10
if(s == ... |
def without_keys(d: dict, *rm_keys):
"""Returns copy of dictionary with each key in rm_keys removed"""
return {k: v for k, v in d.items() if k not in rm_keys} |
def rules_parser(rules):
"""
Convert a list of rules to a dictionary
with predecessor as the key and successor
as its value.
Each rule must be in the form of
"[predecessor]->[successor]"
Parameter
---------
rules: list of str
A list containing production rules
... |
def _is_udp_in_ipv4(pkt):
"""If UDP is in IPv4 packet return True,
else return False. False is returned also if exception occurs."""
ipv4_type = int('0x0800', 16) # IPv4
try:
if pkt.type == ipv4_type:
if pkt.payload.proto == 17: # UDP
return True
except: # pyli... |
def get_best_snp(snp_list):
"""
This function choses the best SNP from the tested list by the max values
:param snp_list: list of SNPs with log-likelihood values
:return: name of the best SNP anf its loading value
"""
if len(snp_list) == 0:
return None, 0, 0
# Get the best SNP
sn... |
def process_kmer_string(kmer_info_string, paired_input):
"""
Process a kmer info string (last column of a Kraken 2 output file), so that
we get a dictionary mapping of tax_ids to total sum of kmer hits.
Returns:
{tax_id_#1: X kmer hits,
tax_id_#2: Y kmer hits,
...
tax_id_#N: Z kmer hi... |
def dictAsString(d):
"""Helper function that returns a string representation of a dictionary"""
s = "{"
for key, val in sorted(d.items()):
s += "%s: %s, " % (key, val)
s = s.rstrip(", ") # Nuke the trailing comma
s += "}"
return s |
def str_2_bool(value):
""" Converts 'something' to boolean.
Args:
value (str)
Returns:
True for values : 1, True, "1", "TRue", "yes", "y", "t"
False otherwise
"""
if str(value).lower() in ("yes", "y", "true", "t", "1"):
return True
else:
return False |
def squash_duplicate_values(values):
"""Remove duplicates from values.
If a value has already been defined remove future values.
Args:
values (list): List of value tuples.
Returns:
values (list): List of value tuples with duplicated removed.
"""
tmp = {}
for item in value... |
def unique_string_list(element_list, only_string=True):
"""
Parameters
----------
element_list :
only_string :
(Default value = True)
Returns
-------
"""
if element_list:
if isinstance(element_list, list):
element_list = set(element_list)
elif... |
def get_word(path):
""" extract word name from json path """
return path.split('.')[0] |
def replace_template_variables(wrangler, data):
"""
Replace variables like %foo% in template data with actual code.
"""
for group in wrangler:
for variable in wrangler[group]:
template_variable = "%{}_{}%" . format(group, variable)
data = data.replace(template_variable,
... |
def trimDocString(docstring):
"""Return properly formatted docstring.
From: https://www.python.org/dev/peps/pep-0257/
Examples
--------
>>> from pygimli.utils import trimDocString
>>> docstring = ' This is a string with indention and whitespace. '
>>> trimDocString(docstring).replace(... |
def head(list):
"""Returns the first element of the given list or string. In some libraries
this function is named first"""
for x in list:
return x |
def integrator_RK(x,step_size,function_system):
"""
Integrate with Runga Kutta
Parameters
x : state
step_size
function_system
"""
k1 = function_system(x)
k2 = function_system(x + step_size * k1 / 2)
k3 = function_system(x + step_size * k2 / 2)
k4 = function_system(x + step_s... |
def parse_ports(port_string):
"""Convert a port specification string into a list of ports."""
ports = set()
for range_string in port_string.split(","):
port_range = [int(port) for port in range_string.split("-")]
ports = ports.union(set(range(min(port_range), max(port_range) + 1)))
retur... |
def _calculate_full_regression(temp: float, rh: float) -> float:
"""
Full heat index regression, applicable when HI from simple regression is over 80
"""
return -42.379 + (2.04901523 * temp) + (10.14333127 * rh) \
- (.22475541 * temp * rh) - (.00683783 * temp * temp) - (.05481717 * rh * rh) \... |
def int_to_bits(i: int):
"""Take an integer as input and return the bits written version."""
return "{:0{}b}".format(i, i.bit_length()) |
def number_GCD(x,y):
"""GCD(x:long, y:long): long
Return the GCD of x and y.
"""
x = abs(x) ; y = abs(y)
while x > 0:
x, y = y % x, x
return y |
def class2func(path):
""" Convert a path such as 'Landroid/support/v4/app/ActivityCompat;'
into a method string 'CLASS_Landroid_support_v4_app_ActivityCompat'
so we can call d.CLASS_Landroid_support_v4_app_ActivityCompat.get_source()
"""
func = "CLASS_" + path.replace("/", "_").replace("$",... |
def __py_if_condition(statements,lineno):
"""returns a valid python if statement"""
if_condition = statements[statements.find('(')+1:statements.find(')')]
return statements[:statements.find('if')]\
+f"if {if_condition}:\n".replace('&&',' and ').replace('||',' or ').rep... |
def english_def_formatter(senses):
"""Formats the english definitions into a list separated by commas
Args:
senses (array with dict elements): an array of english definitions for a given vocabulary word
Returns:
formatted_definitions (string): a string containing formatted english definitio... |
def f_score(precision, recall, beta=1):
"""Compute F beta score
Args:
precision (float): precision
recall (float): recall
beta (float): the weight of recall, default=1
Returns:
float: f score
"""
if recall + precision*beta**2 == 0:
return 0
... |
def additive_inverse(iterable: list) -> list:
"""Find the additive inverse of the iterable."""
return [i * -1 for i in iterable] |
def b(value):
"""Returns the string 'true' if value is truthy, 'false' otherwise."""
if value:
return 'true'
else:
return 'false' |
def filter_urls(new_urls, filter_words, args_filterand):
"""Returns filtered list of URLs based on URL filtering"""
filtered_urls = []
if args_filterand != None:
for i in new_urls:
if all(x in i for x in filter_words):
filtered_urls.append(i)
filtered_urls = list(... |
def getEnumerationFromArray(arr):
"""Return the enumeration of an array"""
return list(map(lambda c: c[0], enumerate(arr))) |
def parse_n_features(n_features, total):
"""Parse either the `n_features` for forward
and backward selection. Namely
(a) if `param` is an int, ensure it lies on (0, `total`),
(a) if `param` is a float, ensure it lies on (0, 1).
Args:
n_features : int
An `n_features` parameter pa... |
def trim_resource(resource):
"""
trim_resource
"""
return resource.strip(" \t\n\r/") |
def vis14(n): # DONE
"""
O O O
OOOOOO OOOOOO OOOOOO
OOOOOO OOOOOO
OOOOOO
Number of Os:
7 13 19"""
result = 'O\n'
for i in range(n):
result += 'OOOOOO\n'
return result |
def answer(l):
"""
We start by initializing a counter for every number in the list.
This counter resembles the number of times a particular entry in the list has been a multiple of a previous number.
Each time we increment that, we can also increase our number of triplets by the factor we're currently e... |
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
i = 0
j = len(array)
if j == 0:
return 0
sum = 0
while i<j:
if i%2 == 0:
sum = array[i] + sum
i += 1
res = sum*array[-1]
return res |
def imf_salpeter(x):
""" Computes a Salpeter IMF
Keywords
----------
x : numpy vector
masses
Returns
-------
imf : numpy vector
unformalized IMF
"""
return x**(-2.35) |
def get_network_interfaces(properties):
""" Get the configuration that connects the instance to an existing network
and assigns to it an ephemeral public IP if specified.
"""
network_interfaces = []
networks = properties.get('networks', [])
if len(networks) == 0 and properties.get('network'... |
def gen_list_of_lists(original_list, new_structure):
"""Generates a list of lists with a given structure from a given list."""
assert len(original_list) == sum(
new_structure
), "The number of elements in the original list and desired structure don't match"
return [
[original_list[i + s... |
def check_exam(arr1, arr2):
"""
Marks an exam checking whether the students answers to the solution.
:param arr1: array of strings containing correct solutions.
:param arr2: array of strings containing student answers.
:return: the score for this array of answers, giving +4 for each correct answer, ... |
def CalcMacTerminalCommand(command):
"""
Calculate what to put in popen to start a given script.
Starts a tiny Applescript that performs the script action.
"""
#
# Quoting is a bit tricky; we do it step by step.
# Make Applescript string: put backslashes before double quotes and
# back... |
def _pytype_to_shape_fn_pytype(pytype: str) -> str:
"""Convert a JitOperator pytype to the type relevant in shape functions.
In particular, this converts `Tensor` to `List[int]`, along with a few
other special cases.
"""
# `Scalar` operands (which are represented with pytype "number") can
# be ... |
def digit_only(string):
"""Removes non-digit characters"""
digits = [char for char in str(string) if char.isdigit()]
return ''.join(digits) |
def get_split_message(message, max_size=4096, search_distance=410):
"""
Splits message in chunks of less than or equal to max_size symbols.
Searches for "\n\n", "\n", ". ", and " " and tries to split message by them.
:param message: message to split.
:param max_size: maximum size of a chunk.
:p... |
def last_digit_of(a,b):
""" Calculates the last digit of a^b
Args:
a (int): Base of a^b
b (int): Exponent of a^b
Returns:
(int): The last digit of a^b
"""
last_digit_a = int(str(a)[-1])
if b % 4 == 0:
exp = 4
else:
exp = b % 4
retur... |
def get_horse_images(num_horses):
""" (int) -> list
Returns a list of GIF image files.
Each image contains the same horse image, each with a unique number 1 - 10
"""
images = []
# Get all horse images
for a_horse in range(0, num_horses):
images = images + ['images/horse_{0}_image.gi... |
def TrueDiv(a1, a2, ctx=None):
"""Divides two numbers"""
if a2 == 0:
return float(f"{'-' if a1 < 0 else ''}Infinity")
return a1 / a2 |
def build_compound(compound):
"""Build a compound
Args:
compound(dict)
Returns:
compound_obj(dict)
dict(
# This must be the document_id for this variant
variant = str, # required=True
# This is the variant id
display_name = str, # required
combi... |
def count_type_changes(pattern: str):
"""Count the number of type changes in the given pattern.
The pattern is expected to describe Bloch points with single characters
where each character type represents one type of Bloch point. Example:
`iooi` -> two type changes.
"""
count = 0
for left, ... |
def get_policy_id(token_name, utxo):
"""
retrieve policy id from token name in utxo
"""
assets_id = [k.split('.') for k in utxo['balances'].keys() if len(k.split('.')) == 2 and k.split('.')[1] == token_name]
if len(assets_id) == 1:
policy_id = assets_id[0][0]
else:
policy_id = None
return policy_i... |
def cancel_dashed(guess, word, answer):
"""
:param guess: an alphabet, the right guess made by player
:param word: The word looks like that it hasn't completely been guessed correctly
:param answer: a word, the correct answer
:return: The word looks like that some of the word have been replaced by r... |
def _neo4j_sanitize(string):
"""
Auxilary functions making sure that backdashes are properly noted and managed in Python.
:param string: string to sanitize
:return:
"""
if isinstance(string, str):
return string.replace('\'', '\"').replace('\\', '\\\\')
else:
return string |
def find_number_3_multiples(x):
"""Calculate the number of times that 3 goes into x."""
mult3=x//3
return mult3 |
def darker(col, factor=0.5):
"""Function returns a darkened (by factor) color.
"""
c0 = int(col[0] * factor)
c1 = int(col[1] * factor)
c2 = int(col[2] * factor)
return (c0, c1, c2) |
def connection_failed(errno=None, errstr=None):
"""
Construct a template for SSH on connection failed
"""
tpl = { 'ssh-event': 'connection-failed' }
if errno is not None:
tpl['error-no'] = errno
if errstr is not None:
tpl['error-str'] = errstr
return tpl |
def parse_date_created(dct):
"""Helper function to parse date-created from profile."""
date = dct['date-created']
if date:
return (int(date['@year']), int(date['@month']), int(date['@day']))
else:
return (None, None, None) |
def separate_dashed_words(token):
"""Separates dashed words and returns the list of all words.
:param token: string
:return: list
"""
return token.split('-') |
def cut(value, arg):
"""Removes all values of arg from the given string."""
return value.replace(arg, '') |
def add_default_value_to(description, default_value):
"""Adds the given default value to the given option description."""
# All descriptions end with a period, so do not add another period.
return '{} Default: {}.'.format(
description,
default_value if default_value else '""'
) |
def list_to_comma_string(val):
"""
Handle array fields by converting them to a comma-separated string.
Example:
['1','2','3'] -> 1,2,3
"""
if val is None:
return ''
if isinstance(val, list):
val = ','.join(val)
return val |
def longest_common_prefix(s1, s2):
"""
Calculate the longest common prefix of two strings.
>>> longest_common_prefix('abcdefg', 'abcabcdefg')
'abc'
>>> longest_common_prefix('abcdefg', 'abcdefg')
'abcdefg'
@arg s1: The first string.
@type s1: unicode
@arg s2: The se... |
def _construct_arn(owner_id, region_name, instance_id):
"""
Args:
owner_id (str): owner id
region_name (str) : region that EC2 is deployed
instance_id (str) : instance on of the EC2
Returns:
EC2 arn
"""
return 'arn:aws:ec2:{region}:{owner}:instance/instance-id/{insta... |
def count_digits_func(input_value):
"""Return the number of digits in a number"""
return len(str(abs(input_value))) |
def percentage(numerator: float, denominator: float) -> float:
"""Calculate a percentage
Args:
numerator (float): The top of the fraction
denominator (float): The bottom of the fraction
Returns:
float: The numerator as a percentage of the denominator
"""
return (numerator ... |
def HexToRGB(hex_str):
"""Returns a list of red/green/blue values from a
hex string.
@param hex_str: hex string to convert to rgb
"""
hexval = hex_str
if hexval[0] == u"#":
hexval = hexval[1:]
ldiff = 6 - len(hexval)
hexval += ldiff * u"0"
# Convert hex values to ... |
def get_plain_text_value(input: dict) -> str:
"""
Get the value of a text input field.
"""
return input.get('value', None) |
def first_name(s):
"""
Returns the first name in s
Examples:
last_name_first('Walker White') returns 'Walker'
last_name_first('Walker White') returns 'Walker'
Parameter s: a name 'first-name last-name'
Precondition: s is a string 'first-name last-name' with one or more... |
def validar_numero(numero: int) -> bool:
"""Valida un numero si es positivo o negativo
:param numero: Numero a validar
:numero type: int
:return: True si el numero es menor igual a cero, de lo contrario
False
:rtype: bool
"""
return True if numero <= 0 else False |
def b(node):
"""
Converts a string "0" or "1" to Python's ``True`` and ``False``
"""
return bool(int(node)) |
def byte_to_megabyte(byte):
"""
Convert byte value to megabyte
"""
return byte / (1024.0**2) |
def get_conf(env, node_data):
"""Extract docker configuration from the node data.
The expected node_dafa docker config looks like this:
docker:
daemon_conf:
signature-verification: false
debug: true
all_registries:
dev:
- host: hub-dev.domain
... |
def bytes_to_gb(qty_bytes):
""" Return a GB value of bytes, rounded to 2 decimals """
bytes_in_gb = 1024 * 1024 * 1024
qty_gb = qty_bytes / bytes_in_gb
return round(qty_gb, 2) |
def self_affine_psd(q, pref, hurst, onedim=False):
"""Ideal self-affine power spectrum, dependent only on prefactor and Hurst exponent."""
exp = -2 * (hurst + 1)
if onedim:
exp = -1 - 2 * hurst
return pref * q**exp |
def strip_query_string(url):
# type: (str) -> str
"""
Strips the query string from a URL for use as tag in spans.
:param url: The URL to be stripped
:return: The given URL without query strings
"""
hqs, fs, f = url.partition("#")
h, _, _ = hqs.partition("?")
if not f:
return ... |
def clean_data(L):
"""clean list data, strip white space and reject empty string."""
i = len(L) - 1
while i >= 0:
L[i] = L[i].strip()
if L[i] == '':
del L[i]
i -= 1
return L |
def detect_archive_type(name):
"""
Tries to guess which type an archive is.
"""
# test for tar
tar_endings = ['.tbz2', '.tar.gz']
for ending in tar_endings:
if name.endswith(ending):
return 'tar'
# test for zip
zip_endings = ['.zip', '.jar']
for ending in zip_end... |
def find_possible_matches(apitools_collection_guess, apitools_collection_names):
"""Find any apitools collections that reasonably match our guess."""
possible_matches = []
for apitools_collection_name in apitools_collection_names:
split_collection_name = apitools_collection_name.split('.')
if apitools_col... |
def generate_fake_var(element):
"""Given a credential type field element, makes up something acceptable.
"""
if element['type'] == 'string':
if element.get('format', None) == 'ssh_private_key':
# this example came from the internet
return '\n'.join([
'-----BEG... |
def _quadratic_polynomial(x, y, p):
"""Quadratic polynomial that can be fitted to an isochrone.
Args:
x: Colours of points in isochrone.
y: Magnitudes of points in isochrone.
p: Coefficients for polynomial.
Returns:
Evaluated polynomial.
"""
return p[0] + p[1] * x +... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.