content stringlengths 42 6.51k |
|---|
def make_row(values, val_bufs, breaks=[]):
"""Creates a row for the results table."""
row = "|" + "|".join([str(values[i]) + " " * val_bufs[i] for i in range(len(values))]) + "|"
for i in range(len(breaks)):
row = row[:breaks[i]+i] + "\n" + row[breaks[i]+i:]
return row |
def get_library_name(library_name):
"""
Utility to split between the library name and version number when needed
"""
name = library_name
for sign in ['!=', '==', '>=', '~=']:
name = name.split(sign)[0]
return name.strip() |
def flatten(lis):
"""Given a list, possibly nested to any level, return it flattened."""
new_lis = []
for item in lis:
if type(item) == type([]):
new_lis.extend(flatten(item))
else:
new_lis.append(item)
return new_lis |
def pax_to_human_time(num):
"""Converts a pax time to a human-readable representation"""
for x in ['ns', 'us', 'ms', 's', 'ks', 'Ms', 'G', 'T']:
if num < 1000.0:
return "%3.3f %s" % (num, x)
num /= 1000.0
return "%3.1f %s" % (num, 's') |
def split_str(str):
"""
:param str: str
:return: list-> odd as coordinate location, even as value
"""
seps = str.split('\n')
repeat = 3
for j in range(repeat):
for i, sep in enumerate(seps):
if '\r' in sep:
seps[i] = sep[:-1]
if sep == '':
... |
def check_conditions(directory, conditions):
"""
Function to check if a condition is known and accounted for.
Parameters
----------
directory : string
the name of a directory that is the condition to check for
conditions : list of strings
a list of known and account... |
def signed_is_negative(num, nbits=32):
""" Assuming the number is a word in 2s complement, is it
negative?
"""
return num & (1 << (nbits - 1)) |
def news_dictionary_maker(articles_list:list) -> list:
"""
Description:
Function to make a smaller list which doesn't contain the 'seen' key
Arguments:
articles_list {list} : list contains dictionary's with the 'seen' and 'articles' keys
Returns:
news_list {list} : list cont... |
def binary_add(first, second):
"""Binary voodoo magic."""
if second == 0:
return first
elif first == 0:
return second
xor = first ^ second
carry = (first & second) << 1
return binary_add(xor, carry) |
def upper(s: str) -> str:
"""
Return a copy of the string with all the characters converted to uppercase
"""
return s.upper() |
def get_bg_len(offset_ms, samplerate):
"""
Return length of samples which belongs to no-beacon signal part
"""
return int((- offset_ms) / 1000.0 * samplerate) |
def _parse_cigar(cigartuples):
"""Count the insertions in the read using the CIGAR string."""
return sum([item[1] for item in cigartuples if item[0] == 1]) |
def startswith_strip(s, startswith='http://', ignorecase=True):
""" Strip a prefix from the beginning of a string
>>> startswith_strip('HTtp://TotalGood.com', 'HTTP://')
'TotalGood.com'
>>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False)
'HTtp://TotalGood.com'
"... |
def construct_cpe(vendor, product, version):
"""
Construct a Common Platform Enumeration (CPE) for a given software.
Args:
vendor (str): The vendor name of the software.
product (str): The product name of the software.
version (str): The software version.
Returns:
str: ... |
def bytesfilter(num, suffix='B'):
"""Convert a number of bytes to a human-readable format."""
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.0f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.0f %s%s" % (num, 'Yi', suffix) |
def get_extra_options_appropriate_for_command(appropriate_option_names, extra_options):
"""
Get extra options which are appropriate for
pipeline_printout
pipeline_printout_graph
pipeline_run
"""
appropriate_options = dict()
for option_name in appropriate_option_names:
... |
def get_run_name_nr(_run_name: str, _run_nr: int) -> str:
"""
Args:
_run_name: e.g. 'runA'
_run_nr: e.g. 1
Returns:
_run_name_nr: e.g. 'runA-1'
"""
return f"{_run_name}-{_run_nr}" |
def ith_byte_block(block_size: int, i: int) -> int:
"""
Return the block to which the byte at index i belongs.
:param block_size: The block size.
:param i: The index of the interesting byte.
:return: The index of the block to which the byte at index i belongs.
"""
assert block_size > 0
a... |
def get_number_and_percentage(total, n, percentage):
"""n takes priority
"""
if n == -1:
return (total, 1.0)
elif n is not None and n > 0:
if n >= total:
return (total, 1.0)
else:
return (n, float(n) / total)
else:
assert isinstance(percentage,... |
def __calculate_variance(profile_jsons, feature_name):
"""
Calculates variance for single feature
Parameters
----------
profile_jsons: Profile summary serialized json
feature_name: Name of feature
Returns
-------
variance : Calculated variance for feature
"""
feature = prof... |
def af_to_ip_header_fields(address_family, header_field):
"""Return the correct header name for an IP field with similar IPv4 and IPv6 usage.
Keyword arguments:
address_family -- desired address-family
header_field -- header field name (use the IPv4 one)
"""
headers = {"ipv6": {"tos": "tc", "id... |
def calc_G(y, symbol_values):
"""
Calculates the shear modulus from the provided modulus and another elastic quantity in the
provided symbol_values dictionary.
Returns:
(float): value of the shear modulus or None if the calculation failed.
"""
if "K" in symbol_values.keys():
k = ... |
def replace_space(target_str):
"""
:params target_str: str
return: str
"""
new_str = target_str.replace(" ", "20%")
return new_str |
def legendre(a: int, p: int) -> int:
"""
Calculate value of Legendre symbol (a/p).
:param a: Value of a in (a/p).
:param p: Value of p in (a/p).
:returns: Value of (a/p).
"""
return pow(a, (p - 1) // 2, p) |
def revpad(s):
"""
This function is to remove padding.
parameters:
s:str
string to be reverse padded
"""
k=ord(s[-1])
temp=0 #temporary variable to check padding
for i in range (1,k): #for loop to check padding
if(s[-i]!=s[... |
def _nth_digit(i, n):
"""
Determine the nth digit of an integer, starting at the right and counting
from zero.
>>> [_nth_digit(123, n) for n in range(5)]
[3, 2, 1, 0, 0]
"""
return (i // 10**n) % 10 |
def get_idx_set(i, sets):
"""
find out the idx of set where `i is an element
"""
idxs = []
for j, set_j in enumerate(sets):
if i in set_j: idxs.append(j)
return idxs |
def pluralize(n, text, suffix='s'):
# type: (int, str, str) -> str
"""Pluralize term when n is greater than one."""
if n != 1:
return text + suffix
return text |
def fix_carets(expr):
"""Converts carets to exponent symbol in string"""
import re as _re
caret = _re.compile('[\^]')
return caret.sub('**',expr) |
def get_unit(quantity_name):
"""
Returns the unit string corresponding to QUANTITY_NAME, or None if an error
occurs during name extraction.
"""
if not quantity_name:
return None
if ("power" in quantity_name):
unit = "kW"
elif ("energy" in quantity_name):
unit = "... |
def clean_lines(lines):
"""removes blank lines and commented lines"""
lines2 = []
for line in lines:
line2 = line.split('#')[0].strip()
if line2:
lines2.append(line2)
return lines2 |
def lookup_next_stage_start(stage_boundaries, t):
"""
Returns the next stage start timestamp from a list/set of stage
boundaries and current time.
"""
next_boundaries = [x for x in stage_boundaries if x > t]
if len(next_boundaries) == 0:
return None
else:
return mi... |
def normalized(name, feed_entries, start):
"""Returns a list of normalized kvstore entries."""
data = []
for feed_entry in feed_entries:
if 'indicator' not in feed_entry or 'value' not in feed_entry:
continue
# Make the entry dict.
entry = feed_entry.copy()
entry... |
def rgb2hex(rgb):
"""Converts an RGB 3-tuple to a hexadeximal color string.
EXAMPLE
-------
>>> rgb2hex((0,0,255))
'#0000FF'
"""
return ('#%02x%02x%02x' % tuple(rgb)).upper() |
def ignore_this_demo(args, demo_reward, t, last_extras):
"""In some cases, we should filter out demonstrations.
Filter for if t == 0, which means the initial state was a success.
Also, for the bag envs, if we end up in a catastrophic state, I exit
gracefully and we should avoid those demos (they won't ... |
def simple_compression(string):
""" Simple way to compress string. """
compressed_string = "";
last, n = ("", 1)
for cha in string:
if cha==last:
n+=1
else:
if n>1:
compressed_string += str(n)
compressed_string += cha
last, ... |
def add_result(return_value, confusion_matrix, instance_specific_pixel_information, instance_specific_instance_information):
"""
Add the result of one image pair to the result structures.
"""
result, pixel_information, instance_information = return_value
if confusion_matrix is None:
confusi... |
def get_default_ext(delim):
"""Retrieves the default extension for a delimiter"""
if delim == ',':
return "csv"
if delim == '\t':
return "tsv"
return "txt" |
def extract_content(last_metadata_line, raw_content):
"""Extract the content without the metadata."""
lines = raw_content.split("\n")
content = "\n".join(lines[last_metadata_line + 1 :])
return content |
def indent(level):
""" Indentation string for pretty-printing
"""
return ' '*level |
def line_parameters_xy(pt_1, pt_2):
"""
Used in lines_intersection
from:
https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines-in-python
"""
a=(pt_1[1]-pt_2[1])
b=(pt_2[0]-pt_1[0])
c=(pt_1[0]*pt_2[1]-pt_2[0]*pt_1[1])
return a, b,-c |
def aes_key_pad(key):
"""
Return padded key string used in AES encrypt function.
:param key: A key string.
:return: Padded key string.
"""
if not key:
raise ValueError('Key should not be empty!')
aes_key_length = 32
while len(key) < aes_key_length:
key += key
retur... |
def join_url(*sections):
"""
Helper to build urls, with slightly different behavior from
urllib.parse.urljoin, see example below.
>>> join_url('https://foo.bar', '/rest/of/url')
'https://foo.bar/rest/of/url'
>>> join_url('https://foo.bar/product', '/rest/of/url')
'https://foo.bar/product/re... |
def hanoi(disks: int) -> int:
"""
The minimum number of moves to complete a Tower of Hanoi is known as a Mersenne Number.
"""
return 2 ** disks - 1 |
def calc_word_score(word, letters_count, letters_score):
"""Evaluate word's score. If the word contains letters outside provided scope,
the output will be \infty.
"""
output = 0
# keep track of the used letters
letters_remaining = dict(letters_count)
for w in word:
if w not in lett... |
def _set_vce_type(vce_type, cluster, shac):
""" Check for argument conflicts, then set `vce_type` if needed. """
if vce_type not in (None, 'robust', 'hc1', 'hc2', 'hc3', 'cluster',
'shac'):
raise ValueError("VCE type '{}' is not supported".format(vce_type))
# Check for con... |
def _get_message_mapping(types: dict) -> dict:
"""
Return a mapping with the type as key, and the index number.
:param types: a dictionary of types with the type name, and the message type
:type types: dict
:return: message mapping
:rtype: dict
"""
message_mapping = {}
entry_index = ... |
def check_not_errors_tcp(requets_raw, response_raw, consulta):
"""
Chequea si hay errores en la trama, formato TCP
:param requets_raw: trama con la cual se hizo la solicitud
:type requets_raw: bytes
:param response_raw: trama de respuesta
:type response_raw: bytes
:return: True si la no hay... |
def get_users(username, public_key):
"""This function returns part of user-data which is related
to users which should be created on remote host.
:param str username: Username of the user, which Ansible will use to
access this host.
:param str public_key: SSH public key of Ansible. This key wil... |
def stripReverse(s):
"""Returns the string s, with reverse-video removed."""
return s.replace('\x16', '') |
def validate_pixels(pixels):
"""
Checks if given string can be used as a pixel value for height or width.
Height or Width or assumed to never surpass 10000
"""
try:
pixels = int(pixels)
except:
return False
return 0 < pixels < 10000 |
def cleaning_space(string_inst):
"""arg : instruction line
return : (string) instruction line cleared of space and tab before and after """
while string_inst[0] == ' ' or string_inst[0]== "\t":
string_inst = string_inst[1:]
while string_inst[-1] == ' ' or string_inst[-1] == '\t':
str... |
def get_jaccard_score(a, s):
"""
Function that computes the jaccard score between two sequences
Input: two tuples; (start index of answer, length of answer). Guaranteed to overlap
Output: jaccard score computed for the two sequences
"""
a_start = a[0]
a_end = a[0]+a[1]-1
start = s[0]
... |
def map2dict(darray):
""" Reformat a list of maps to a dictionary
"""
return {v[0]: v[1] for v in darray} |
def one(iter):
""" Returns True if exactly one member of iter has a truthy value, else False.
Args:
iter (iterable): an iterable containing values that can be evaluated as bools.
Returns:
(bool): True if exactly one member is truthy, else False.
>>> one({"a", None, True})
False
... |
def group(l):
"""
Group a list into groups of adjacent elements. e.g.
> group(list("AAABBCCDBBBBA"))
[("A", 3), ("B", 2), ("C", 2), ("D", 1), ("B", 4), ("A", 1)]
"""
result = []
previous = None
count = 0
for elem in l:
if previous is None:
previous = elem
... |
def poly2(k, x):
""" line function """
return k[0] * x * x + k[1] * x + k[2] |
def _component_name(idx):
"""Helper to get the name of a component."""
return "component_%i" % idx |
def xml_has_javascript(data):
"""
Checks XML for JavaScript. See "security" in :doc:`customization <../../customization>` for
additional information.
:param data: Contents to be monitored for JavaScript injection.
:type data: str, bytes
:return: ``True`` if **data** contains JavaScript tag(s), ... |
def filter_availability(availability, start_date, end_date):
"""
Removes dates that are not in the range of start_date.day to end_date.day
"""
filtered_availability = []
for time_range in availability:
if time_range["start"] < start_date:
continue
if time_range["end"] <= ... |
def reformat_slice(
sl_in: slice,
limit_in: int,
mirror: bool) -> slice:
"""
Reformat the slice, with optional reverse operation.
Note that the mirror operation doesn't run the slice backwards across the
same elements, but rather creates a mirror image of the slice. This is
... |
def stringify_dict(d):
"""
If a dict contains callable (functions or classes) values, stringify_dict replaces them with their __name__ attributes.
Useful for logging the dictionary.
"""
str_d = {}
for k,v in d.items():
if isinstance(v, dict):
str_d[k] = stringify_dict(v)
... |
def encrypt(input_string: str, key: int) -> str:
"""
Shuffles the character of a string by placing each of them
in a grid (the height is dependent on the key) in a zigzag
formation and reading it left to right.
>>> encrypt("Hello World", 4)
'HWe olordll'
>>> encrypt("This is a message", 0)... |
def translate_precision_to_integer(precision: str) -> int:
"""This function translates the precision value to indexes used by wikidata
Args:
precision (str): [description]
Returns:
int: wikidata index for precision
"""
if isinstance(precision, int):
return precision
prec... |
def build_openlibrary_urls(isbn):
"""Build Open Library urls."""
url = "https://covers.openlibrary.org/b/isbn"
return {
"is_placeholder": False,
"small": "{url}/{isbn}-S.jpg".format(url=url, isbn=isbn),
"medium": "{url}/{isbn}-M.jpg".format(url=url, isbn=isbn),
"large": "{url... |
def remove_emoticon(entry):
""" Remove emoticon from tweet (use in pd.df.apply)
Args:
entry (entry of pandas df): an entry of the tweet column of the
tweet dataframe
Returns:
output: tweet with emoticon remove
"""
output = entry.encode('ascii', 'ignore').decode('asc... |
def map_per_image(label, predictions):
"""Computes the precision score of one image.
Parameters
----------
label : string
The true label of the image
predictions : list
A list of predicted elements (order does matter, 5 predictions allowed per image)
Returns
-------... |
def hasgetattr(obj, attr, default=None):
""" Combines hasattr/getattr to return a default if hasattr fail."""
if not hasattr(obj, attr):
return default
return getattr(obj, attr) |
def get_nearest_n(x, n):
"""Round up to the nearest non-zero n"""
rounded = -(-x // n) * n
return rounded if rounded else n |
def get_type(value):
"""
Get the type of a Python object.
"""
return type(value).__name__ |
def is_int(value):
""" Return true if can be parsed as an int """
try:
int(value)
return True
except:
return False |
def is_bool(target: bool) -> bool:
"""Check target is boolean."""
if not isinstance(target, bool):
return False
return True |
def getTweetUserLocation(tweet):
""" If included, read the user from the tweet and return their self-supplied location"""
if 'user' in tweet and \
tweet['user'] is not None and \
'location' in tweet['user'] :
return tweet['user']['location']
else :
return None |
def create_variant_slider_filter(min_variant_group: int, max_variant_group: int) -> dict:
"""
Create a variant slider filter to be used in a trace filter sequence.
Args:
min_variant_group:
An integer denoting the variant group on the lower bound.
max_variant_group:
A... |
def _partition_2(list_, i, j):
"""Rearrange list_[i:j] so that items < list_[i] are at
the beginning and items >= list_[i] are at the end,
and return the new index for list_[i].
@param list list_: list to partition
@param int i: beginning of partition slice
@param int j: end of partition slice
... |
def leap_year(year):
"""Check whether given year is a leap year."""
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 |
def rgb_to_hex(*args: float) -> str: # pragma: no cover
"""Convert RGB colors into hexadecimal notation.
Args:
*args: percentages (0% - 100%) for the RGB channels
Returns:
hexadecimal_representation
"""
red, green, blue = (
int(255 * args[0]),
int(255 * args[1]),
... |
def element(e, **kwargs):
"""Utility function used for rendering svg"""
s = "<" + e
for key, value in kwargs.items():
s += " {}='{}'".format(key, value)
s += "/>\n"
return s |
def quantization_error(t_ticks, q_ticks):
"""
Calculate the error, in ticks, for the given time for a quantization of q ticks.
:param t_ticks: time in ticks
:type t_ticks: int
:param q_ticks: quantization in ticks
:type q_ticks: int
:return: quantization error, in ticks
:rtype: int
... |
def merge(args_array, cfg, log):
"""Function: merge_repo
Description: This is a function stub for merge_repo.merge_repo.
Arguments:
args_array -> Stub argument holder.
cfg -> Stub argument holder.
log -> Stub argument holder.
"""
status = True
if args_array and cf... |
def check_unit(number):
"""
The function that check the number and return the unit
Parameter:
number (float) : the answer from calculation
Return:
The unit of the answer
"""
# check if the values is greater than one.
if(number > 1):
# return the unit with "s"
... |
def clean_float_value_from_dict_object(dict_object, dict_name, dict_key, post_errors, none_allowed=False, no_key_allowed=False):
"""
This function takes a target dictionary and returns the float value given by the given key.
Returns None if key if not found and appends any error messages to the post_errors ... |
def skip_mul(n):
"""Return the product of n * (n - 2) * (n - 4) * ...
>>> skip_mul(5) # 5 * 3 * 1
15
>>> skip_mul(8) # 8 * 6 * 4 * 2 * 0
0
"""
if n == 0:
return 0
else:
return n * skip_mul(n - 2) |
def column_to_list(data, index):
"""Return a list with values of a specific column from another list
Args:
data: The list from where the data will be extracted
index: The index of the column to extract the values
Returns:
List with values of a specific column
"""
column_list = []
... |
def escape_formatting(username: str) -> str:
"""Escapes Discord formatting in the given string."""
return username.replace("_", "\\_").replace("*", "\\*") |
def resource_from_path(path):
"""Get resource name from path (first value before '.')
:param path: dot-separated path
:return: resource name
"""
index = path.find('.')
if index == -1:
return path
return path[:index] |
def determine_edit_type(values, previous_values):
""" Determine whether an edit is editorial (0) or content (1).
This is dependent on whether there are substantial additions in content volume.
It is only a content contribution if:
1) both text and links/urls are added (not text in isolation)
2) images are ad... |
def ph_color_code(value):
"""
:param value: This is a pH value which is having its color multiplexed.
Description:
This takes a pH value as input and returns a color to be used in the form of a string.
"""
if value > 12.6:
return 'navy'
elif value >11.2:
return 'blue'
elif value >9.8:
return 'dodgerb... |
def parse_spec(spec):
"""Return parsed id and arguments from build spec."""
if isinstance(spec, dict):
return spec['type'], spec.get('args', {})
if isinstance(spec, (tuple, list)) and isinstance(spec[0], str):
return spec[0], {} if len(spec) < 2 else spec[1]
if isinstance(spec, str):
... |
def type_match(node_a, node_b):
""" Checks whether the node types of the inputs match.
:param node_a: First node.
:param node_b: Second node.
:return: True if the object types of the nodes match, False otherwise.
:raise TypeError: When at least one of the inputs is not a dictionary
... |
def my_function(lhs: int, rhs: int) -> int:
"""Add two numbers together
Parameters
----------
lhs: int
first integer
rhs: int
second integer
Raises
------
value errror if lhs == 0
Examples
--------
>>> my_function(1, 2)
3
>>> my_function(0, 2)
... |
def _len(L):
"""
Determines the length of ``L``.
Uses either ``cardinality`` or ``__len__`` as appropriate.
EXAMPLES::
sage: from sage.misc.mrange import _len
sage: _len(ZZ)
+Infinity
sage: _len(range(4))
4
sage: _len(4)
Traceback (most recent c... |
def str_between(string, start, end=None):
"""(<abc>12345</def>, <abc>, </def>) -> 12345"""
content = string.split(start, 1)[-1]
if end is not None:
content = content.rsplit(end, 1)[0]
return content |
def _get_nested_vulnerability(data, key_path=None):
"""Get nested vulnerability."""
if key_path:
for component in key_path.split('.'):
data = data[component]
return data |
def search(target: int, prime_list: list) -> bool:
"""
function to search a number in a list using Binary Search.
>>> search(3, [1, 2, 3])
True
>>> search(4, [1, 2, 3])
False
>>> search(101, list(range(-100, 100)))
False
"""
left, right = 0, len(prime_list) - 1
while left <=... |
def get_max_value(register):
"""Get maximum value from register."""
return max(register.values()) |
def _scalarise(value):
""" Converts length 1 lists to singletons """
if isinstance(value, list) and len(value) == 1:
return value[0]
return value |
def iterate(source, *keys):
"""Iterate a nested dict based on list of keys.
:param source: nested dict
:param keys: list of keys
:returns: value
"""
d = source
for k in keys:
if type(d) is list:
d = d[int(k)]
elif k not in d:
d[k] = {}
else:
... |
def predict_callback(data):
"""
user defined
:param data: dict
:return:
"""
kwargs = data.get('kwargs')
# print(kwargs)
num = kwargs.get('num')
if num > 10:
return True
return False |
def floatToFixed(value, precisionBits):
"""Converts a float to a fixed-point number given the number of
precisionBits. Ie. int(round(value * (1<<precisionBits))).
"""
return int(round(value * (1<<precisionBits))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.