content stringlengths 42 6.51k |
|---|
def read_str(data, start, length):
"""Extract a string from a position in a sequence."""
return data[start:start+length].decode('utf-8') |
def label(language='en', value=''):
"""Create and return a label (dict)"""
return {language: {'language': language, 'value': value}} |
def drude(x, x0=4.59, gamma=0.90, **extras):
"""Drude profile for the 2175AA bump.
:param x:
Inverse wavelength (inverse microns) at which values for the drude
profile are requested.
:param gamma:
Width of the Drude profile (inverse microns).
:param x0:
Center of the Dr... |
def bindigits(n:int, bits:int)->str:
"""Convierte a binario un numero de complemento A2 en caso de negativo, normal en caso de ser positivo
Args:
n (int): E.g 7
bits (int): eg 3
Returns:
str: E.g '001'
"""
s = bin(n & int("1"*bits, 2))[2:]
return ("{0:0>%s}" % (bits)).f... |
def get_center(x_min: int,y_min: int,x_max:int,y_max:int):
"""Get center of bounding box.
Args:
x_min (int): Minimum x value in pixels.
y_min (int): Minimum y value in pixels.
x_max (int): Maximum x value in pixels.
y_max (int): Maximum y value in pixels.
Returns:
t... |
def is_stored(self):
"""
Checks if the given model is stored in a previously defined
secondary storage system.
For the base model it's always considered (by default) to be
not stored (transient).
:rtype: bool
:return: If the current model is stored in the hypothetical
seconda... |
def dict_update(fields_list, d, value):
"""
:param fields_list: list of hierarchically sorted dictionary fields leading to value to be modified
:type fields_list: list of str
:param d: dictionary to be modified
:type d: dict
:param value: new value
:type value: any type
:return: updated ... |
def count_if(iterable, pred, first=0, last=None):
"""
Count the number of elements in an iterable that satisfy a condition
Parameters
----------
iterable: an iterable object with __get_item__
pred: a unary predicate function
first: first element to check
last: one past last element to c... |
def is_tool(name):
"""Check whether `name` is on PATH and marked as executable."""
from shutil import which
return which(name) is not None |
def str_to_bool(s):
"""Convert string boolean values to bool.
The conversion is case insensitive.
:param val: input string
:return: True if val is 'true' otherwise False
"""
return str(s).lower() == 'true' |
def _parse_ipv4(ip):
""" Parse an ipv4 address and port number. """
addr, port = ip.split(':')
return addr, port |
def to_field_name(mp_name):
"""Get the field name for the Materialized Property named `mp_name`
"""
return '_' + mp_name |
def get_post_data(start_year, _ID_BenefitSurtax_Switches=True, quick_calc=False):
"""
Convenience function for posting GUI data
"""
data = {'has_errors': ['False'],
'start_year': str(start_year),
'data_source': 'PUF',
'csrfmiddlewaretoken':'abc123'}
if _ID_Benefit... |
def row_button_width(row_buttons):
"""
returns the width of the row buttons
"""
if not row_buttons:
return 0
n = len(row_buttons)
return n * 25 + (n - 1) * 5 |
def delete_behavior_validator(value):
"""
Property: SchemaChangePolicy.DeleteBehavior
"""
valid_values = [
"LOG",
"DELETE_FROM_DATABASE",
"DEPRECATE_IN_DATABASE",
]
if value not in valid_values:
raise ValueError("% is not a valid value for DeleteBehavior" % value)... |
def get_moment(at):
"""Get moment value from one at type value:
>>> get_moment('minute.1')
1
:param at: One at type value.
"""
return int(at[at.find('.') + 1:]) |
def int2bin6(num):
"""
Converts the given integer to a 6-bit binary representation
"""
return "".join(num & (1 << i) and '1' or '0' for i in range(5, -1, -1)) |
def unlistify(x):
"""
Converts 1-element list to x.
"""
# The isinstance() built-in function is recommended over the type() built-in function for testing the type of an object
if isinstance(x, list):
if len(x)==1:
return x[0]
else:
return x
else:
r... |
def load_token(token_name):
""" Read supplementary text file for Scopus API key
Args:
token_name: the name of your Scopus API key file
"""
try:
with open(token_name, 'r') as file:
return str(file.readline()).strip()
except EnvironmentError:
print(f'Erro... |
def get_middle(s):
"""This will find the middle character(s)."""
i = (len(s) - 1) // 2
return s[i:-i] or s |
def get_status( object ):
"""
Gets the lower Status information
Args:
object: The object containing Status
Returns:
The state within Status (None if not found)
The health within Status (None if not found)
"""
state = None
health = None
if "Status" in object:
... |
def args_idx(x):
"""Get the idx of "?" in the string"""
return x.rfind('?') if '?' in x else None |
def infant_action_valuation(signals):
"""
Parameters
----------
signals : dict
"""
count = 0
for signal in signals:
if signals[signal] == "still":
count += 1
return max(count / float(4), 0.1) |
def extract_transcript_annotations_from_GTF(tab_fields):
""" Extracts key-value annotations from the GTF description field
"""
attributes = {}
description = tab_fields[-1].strip()
# Parse description
for pair in [x.strip() for x in description.split(";")]:
if pair == "": continue
... |
def get_syst ( syst , *index ) :
"""Helper function to decode the systematic uncertainties
Systematic could be
- just a string
- an object with index: obj [ibin]
- a kind of function: func (ibin)
"""
if isinstance ( syst , str ) : return syst
elif syst and hasattr ( syst , '... |
def collect_doc(ori_doc):
"""
mysql> describe document; original documents (should not be changed in the whole process);
+----------+----------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------------+------+-----+---------+-----... |
def _intenum_converter(value, enum_klass):
"""Convert a numeric family value to an IntEnum member.
If it's not a known member, return the numeric value itself.
"""
try:
return enum_klass(value)
except ValueError:
return value |
def get_init_partition(nodes):
"""
Parameters
----------
nodes : arr_like.
Vertices of the netlist's graph.
Returns
-------
list, list
Nodes in partition 1 and 2.
"""
return list(nodes[:len(nodes)//2]), list(nodes[len(nodes)//2:]) |
def ifb(bites):
"""
ifb is a wrapper for int.from_bytes
"""
return int.from_bytes(bites, byteorder="big") |
def linear_oversample_list(alist, factor=2):
"""Linearly oversample a list: Calculate intermediate values between the list entries using the
given oversampling factor. The default factor of two fills the medians into the list.
Parameters
----------
alist : list
Input list that should be ove... |
def find_missing_integer(lst):
"""Returns the first missing integer in an ordered list.
If not found, returns the next integer.
"""
try:
return sorted(set(range(lst[0], lst[-1])) - set(lst))[0]
except:
return max(lst) + 1 |
def endian_swap(value):
""""Given a 32-bit integer value, swap it to the opposite endianness"""
return (((value >> 24) & 0xff) | ((value >> 8) & 0xff00)
| ((value << 8) & 0xff0000) | (value << 24)) |
def replace_key(dictionary, new_key, old_key):
"""
This method is used for replace key in dictionary.
:param dictionary: dictionary object on which we wan to replace key.
:param new_key: key which will replace in dictionary
:param old_key: existing key in dictionary
:return: dict object
"""... |
def _get_ftype_from_filename(fn, ext_unit_dict=None):
"""
Returns the boundary flowtype and filetype for a given ModflowFlwob
package filename.
Parameters
----------
fn : str
The filename to be parsed.
ext_unit_dict : dictionary, optional
If the arrays in the file are specif... |
def bolditalics(msg: str):
"""Format to bold italics markdown text"""
return f'***{msg}***' |
def haskeys(d, *keys):
"""Returns True if all keys are present in a nested dict `d`."""
if len(keys) == 1:
return keys[0] in d
first = keys[0]
if first in d and isinstance(d[first], dict):
return haskeys(d[first], *keys[1:])
return False |
def uintToXaya (value):
"""
Converts a hex literal for an uint256 from Ethereum format
(with 0x prefix) to the Xaya format without.
"""
assert value[:2] == "0x"
return value[2:] |
def filter_invalid_unicode(text):
"""Return an empty string and True if 'text' is in invalid unicode."""
return ("", True) if isinstance(text, bytes) else (text, False) |
def extract_object(input_object):
"""Chunk of code to extract the inner JSON from objects.
Required to reduce unneccessary lines in HUG script & improve maintainability."""
temp_dict = {}
for item in input_object:
temp_dict[str(item)] = input_object[item]
return temp_dict |
def bits(num, width):
"""Convert number into a list of bits."""
return [int(k) for k in f'{num:0{width}b}'] |
def _ComputeEditDistance(hs, rs):
"""Compute edit distance between two list of strings.
Args:
hs: the list of words in the hypothesis sentence
rs: the list of words in the reference sentence
Returns:
edit distance as an integer
"""
dr, dh = len(rs) + 1, len(hs) + 1
dists = [[]] * dr
# initi... |
def find_magic_number_brute_force(numbers):
"""Find magic number using brute force O(n)
:param numbers array of sorted unique integers
:param magic magic number to be searched for
:return index of magic number, else -1
"""
for index in range(len(numbers)):
if numbers[index] ==... |
def DiscTag(data):
"""Extracts the disc number and formats it according to the number
of discs in the set, ie, 2 digits if there are 10 or more discs and 1
digit if there are fewer than 10 discs. Input parameter ``data`` is
expected to be a ``mutagen.flac.FLAC`` or ``mutagen.flac.VCFLACDict``,
howe... |
def create_compile_command(file_name):
"""
Creates the bash command for compiling a JUnit test.
Params:
file_name (str): The file name of the test to compile.
Return:
str: The bash command for compiling.
"""
return f"javac -d classes -cp classes/:junit-jupiter-api-5.7.0.jar:apiguardian... |
def distill_links(F1, F2):
"""
Obtains the distilled fidelity of two links assuming Werner states
:param F1: type float
Fidelity of link 1
:param F2: type float
Fidelity of link 2
:return: type float
Fidelity of the distilled link
"""
a = F1 * F2
b = (1 - F1) / 3
... |
def cb_bands(ctx, param, value):
"""
Click callback for parsing and validating `--bands`.
Parameters
----------
ctx : click.Context
Ignored.
param : click.Parameter
Ignored.
value : str
See the decorator for `--bands`.
Returns
-------
tuple
Band... |
def pack_variable_length(value, limit=True):
"""
Encode a positive integer as a variable-length number used in
Standard MIDI files.
ValueError rasied if value is over 0x0FFFFFFF (=would require >4 bytes).
Set limit=False to override this.
"""
if value < 0:
raise ValueError(f"Value is... |
def flatten_errors(error):
"""
Django's ValidationError contains nested ValidationErrors, which each have a list
of errors, so we need to flatten them.
"""
return {k: [item for items in v for item in items] for k, v in error.items()} |
def degToRad(deg):
"""
Convert deg to rad. 5 decimal places output
:param: deg(float): degrees
:output: rad(float): radians
"""
# Convert to float if int
if type(deg) == int:
deg = float(deg)
assert type(deg) == float
return round(deg * 3.14159265359 / 180, 5) |
def search(strings, chars):
"""Given a sequence of strings and an iterator of chars, return True
if any of the strings would be a prefix of ''.join(chars); but
only consume chars up to the end of the match."""
if not all(strings):
return True
tails = strings
for ch in chars:
tail... |
def list_to_table(list):
"""Convert a list to a tabulated string"""
list_to_table = ""
for row in range(len(list)):
list_to_table += str(row+2) + "\t" + str(list[row]) + "\n"
return list_to_table |
def _make_clean_col_info(col_info, col_id=None):
"""
Fills in missing fields in a col_info object of AddColumn or AddTable user actions.
"""
is_formula = col_info.get('isFormula', True)
ret = {
'isFormula': is_formula,
# A formula column should default to type 'Any'.
'type': col_info.get('type', '... |
def vis_params_rgb(bands=['R', 'G', 'B'], minVal=0, maxVal=3000, gamma=1.4, opacity=None):
"""
Returns visual parameters for a RGB visualization
:param bands: list of RGB bandnames, defaults to ['R', 'G', 'B']
:param minVal: value to map to RGB value 0, defaults to 0
:param maxVal: value to map to R... |
def sort(seq):
"""
Takes a list of integers and sorts them in ascending order. This sorted
list is then returned.
:param seq: A list of integers
:rtype: A list of integers
"""
for n in range(1, len(seq)):
item = seq[n]
hole = n
while hole > 0 and seq[hole - 1] > item... |
def reduce_shape(shape):
"""
Reduce dimension in shape to 3 if possible
"""
try:
return shape[:3]
except TypeError:
return shape |
def compute_log_pdf_ratio(potential_function, parameter_tm1, parameter_t, x_tm1, x_t):
"""
return log( \gamma_{t}(x_t) / \gamma_{tm1}(x_{tm1}))
arguments
potential_function : function
potential function (takes args x and parameters)
parameter_tm1 : jnp.array()
second... |
def format_direction(direction):
"""
Examples
--------
>>> format_direction('ra')
'ra'
>>> format_direction('el')
'alat'
>>> format_direction('az')
'alon'
"""
lowerdir = direction.lower()
if lowerdir == 'el':
return 'alat'
elif lowerdir == 'az':
return... |
def IsUnique(s):
"""
checks if the characters in the string are unique
:param s: string to be compared
:type s: str
:return: true if the string has unique chars else false
:rtype: bool
"""
s = sorted(s)
for i in range(len(s)):
if i<len(s)-1 and s[i] == s[i+1]:
ret... |
def formatBold(t: str = "", close: bool = True) -> str:
"""
Applies IRC bold formatting to the provided text (t),
optionally resetting formatting at the end of it (True by default).
"""
reset = '\x0f'
return f"\x02{t}{reset if close else ''}" |
def show_tags(context, tags):
"""Show tags"""
splits = tags.split(',')
for index, tag in enumerate(splits):
splits[index] = tag.lstrip()
return {
'tags': splits,
} |
def frequency(variant_obj):
"""Returns a judgement on the overall frequency of the variant.
Combines multiple metrics into a single call.
"""
most_common_frequency = max(variant_obj.get('thousand_genomes_frequency') or 0,
variant_obj.get('exac_frequency') or 0)
if mo... |
def RGB_TO_HSB(col):
"""
Converts a 3-tuple with RGB values (in range 0..255) into a 3-tuple
with HSB color values in range [0..1].
"""
r, g, b = col
cmax = float(max(r, g, b))
cmin = float(min(r, g, b))
delta = cmax - cmin
brightness = cmax / 255.0
saturation = (delta / cmax)... |
def GetGOFrequencies(gene2go, genes):
"""count number of each go category in gene list.
return a tuple containing:
* the total number of GO categories found.
* dictionary of counts per GO category
* dictionary of genes found with GO categories
"""
counts = {}
total = 0
found_genes =... |
def ffloat(string):
"""
In case of fortran digits overflowing and returing ********* this
fuction will replace such values with 1e9
"""
if 'nan' in string.lower():
return 1e9
try:
new_float = float(string)
except ValueError:
if '*******' in string:
new_fl... |
def write_lines(file_name, lines):
"""
Inverse of :read_lines, just do the opposite
True if written, False otherwise
"""
try:
with open(file_name, "w") as f:
f.writelines("\n".join([line.strip().replace("\n","") for line in lines
if line.str... |
def highlight_term(term, s, pattern='<strong>%s</strong>'):
"""Highlight ``term`` in ``s`` by replacing it using the given
``pattern``.
"""
term = term.lower()
term_len = len(term)
i = 0
highlighted = ''
while i < len(s):
window = s[i:i + term_len]
if window.lower() == te... |
def rpr(s):
"""Create a representation of a Unicode string that can be used in both
Python 2 and Python 3k, allowing for use of the u() function"""
if s is None:
return 'None'
seen_unicode = False
results = []
for cc in s:
ccn = ord(cc)
if ccn >= 32 and ccn < 127:
... |
def escape(text: str, *, mass_mentions: bool = False, formatting: bool = False) -> str:
"""Get text with all mass mentions or markdown escaped.
Parameters
----------
text : str
The text to be escaped.
mass_mentions : `bool`, optional
Set to :code:`True` to escape mass mentions in the... |
def get_points(result):
"""get respective points win = 3, lose = 0, draw = 1 point"""
if result == 'W':
return 3
elif result == 'D':
return 1
else:
return 0 |
def initial_policy(observation):
"""A policy that sticks if the player score is >= 20 and his otherwise
Parameters:
-----------
observation:
Returns:
--------
action: 0 or 1
0: STICK
1: HIT
"""
return 0 if observation[0] >= 20 else 1 |
def expand(sequence):
""" Permute the string """
string = str(sequence)
string_length = len(string)
return " ".join(
[string[idx:string_length] for idx in range(0, string_length)]
) |
def insert_pad(text, pad_left=True, pad_right=True, pad_symbol=' '):
"""
Inserts pads to the given text (at the start and at the end)
:rtype : string
:param text: Text to insert pads to
:param pad_left: Whether to insert or not a pad to the left
:param pad_right: Whether to insert or not a pad ... |
def pretty_str(label, arr):
"""
Generates a pretty printed NumPy array with an assignment. Optionally
transposes column vectors so they are drawn on one line. Strictly speaking
arr can be any time convertible by `str(arr)`, but the output may not
be what you want if the type of the variable is not a... |
def rle(input):
"""
Format a list as run-length encoding JSON.
"""
output = [input[0]]
for item in input[1:]:
if isinstance(output[-1], list) and output[-1][1] == item:
output[-1][0] += 1
elif output[-1] == item:
output[-1] = [2, item]
else:
... |
def remove_padding(sentence, pad_idx):
"""Removes the paddings from a sentence"""
try:
return sentence[: sentence.index(pad_idx)]
except ValueError:
return sentence |
def opv(d, func, *args):
"""
Apply func to all values of a dictionary.
:param d: A dictionary.
:param func: Callable accepting a value of `d` as first parameter.
:param args: Additional positional arguments to be passed to `func`.
:return: `dict` mapping the keys of `d` to the return value of t... |
def auto_category(name):
"""
this function helps to choose a category of file automatically
:param name:
:return:
"""
name = name.lower()
DOCUMENT = ('pdf','doc','docx','ppt','pptx','xls','xlsx','csv','mobi','epub','azw3','txt')
ARCHIVE = ('zip','bz2','gzip','tar','gz','7z','rar'... |
def normalise_bytes(buffer_object):
"""Cast the input into array of bytes."""
return memoryview(buffer_object).cast("B") |
def get_size_str(grid_width, grid_height, book_size='digest'):
"""
Get a string that matches the size of a component/composite
:param grid_width:
:type grid_width:
:param grid_height:
:type grid_height:
:param book_size:
:type book_size:
:return:
:rtype:
"""
return f"{boo... |
def get_file_name(path):
"""
:param path:
:return:
"""
parts = path.split("/")
return parts[len(parts) - 1] |
def i(n,pv,fv,pmt):
"""Calculate the interest rate of an annuity"""
i=0.0000001
a=0
while a <= fv:
a = pv*((1+i)**n) + pmt*((1+i)**n-1)/i
if a<fv:
pass
i=i+0.0000001
else:
return i
# prevent next iteration
br... |
def create_keypair(session, KeyName, DryRun=False):
"""
Returns dict with SHA-1 digest of the DER encoded private key
An unencrypted PEM encoded RSA private key
and the name of the key pair.
Args:
session(Session): boto3.session.Session object
KeyName (str): Desired name of the keyp... |
def drop_edge_punct(word):
"""
Remove edge punctuation.
:param word: a single string
>>> drop_edge_punct("'fieri")
'fieri'
>>> drop_edge_punct('sedes.')
'sedes'
"""
if not word:
return word
try:
if not word[0].isalpha():
word = word[1:]
if not ... |
def _setmovepointer(cells, offset):
"""Adds given offset to every elements in cells, except for None (normally
represents "one or more other cells")."""
result = [i + offset for i in cells if i is not None]
if None in cells: result.append(None)
return set(result) |
def all_is_None (phrase):
"""Returns TRUE if all elements in <phrase> is null"""
phrase = [x for x in phrase if not x is None]
return phrase == [] |
def StrReverse(s):
"""Reverse a string"""
lst = list(str(s))
lst.reverse()
return "".join(lst) |
def _IsDigest(url):
"""Return true if the given image url is by-digest."""
return '@sha256:' in url |
def str_to_bool(value):
"""
Convert a human readable string into a boolean.
"""
valuestr = str(value).lower()
if valuestr in ['1', 'yes', 'enable', 'true']:
return True
elif valuestr in ['0', 'no', 'disable', 'false']:
return False
else:
raise Exception("Unable to con... |
def contains(wordlist, letter):
"""Return a list of words that contain the correct letter."""
result = []
for word in wordlist:
if letter in word:
result.append(word)
return result |
def validate_user_input_to_int(user_input):
"""
validates user input against type integer & automatically converts and returns the value
: user_input --> value entered by user
"""
try:
return int(user_input)
except Exception:
return "error" |
def calc_BMI(w,h):
"""calculates the BMI
Arguments:
w {[float]} -- [weight]
h {[float]} -- [height]
Returns:
[float] -- [calculated BMI = w / (h*h)]
"""
return (w / (h*h)) |
def get_md5sum(config_file):
""" Get MD5SUM_HEADER from config file .aos """
ret = None
with open(config_file, "r") as f:
for line in f.readlines():
line = line.strip()
if "MD5SUM_HEADER" in line:
ret = line.replace("MD5SUM_HEADER=", "")
return ret |
def strictly_decreasing(L):
"""Return True if list L is strictly decreasing."""
return all(x > y for x, y in zip(L, L[1:])) |
def asset_image_aoi(gee_dir):
"""return the aoi for the reclassify tests available in our test account"""
return f"{gee_dir}/reclassify_image_aoi" |
def normalize_protocol(raw_protocol):
"""
A function to normalize protocol names between IOS and NXOS. For example, IOS uses 'C' and NXOS uses 'direct" for
connected routes. This function will return 'connected' in both cases.
:param raw_protocol: <str> The protocol value found in the route table out... |
def is_raid_valid_combination( disks, raid ):
"""
Should return True if combination is valid and False otherwise.
Test row that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
# check raid level compat... |
def b2d(n):
""" binary to decimal conversion"""
num = 0
nn = list(n)
nn.reverse()
for j in range(len(nn)):
if nn[j]==0:
continue
num = num+2**j
return num |
def checkTupleAlmostEqualIn(tup, tupList, place):
"""
check if a tuple in a list of tuples in which float items only
need to be almost equal
:type tup: tuple
:param tup: tuple to be checked
:type tupList: list of tuples
:para tupList: list of tuples that tup need to be check with
:place:... |
def update_egress_req_count_metric(mp_endpoint_names):
"""Update the metrics of the "Egress Request Count (sum)" dashboard widget"""
results = []
for mp_name in mp_endpoint_names:
endpoints = mp_endpoint_names[mp_name]
for endpoint in endpoints:
entry = ["AWS/MediaPackage",... |
def checkdeplaid(incidence):
"""
Given an incidence angle, select the appropriate deplaid method.
Parameters
----------
incidence : float
incidence angle extracted from the campt results.
"""
if incidence >= 95 and incidence <= 180:
return 'night'
elif incidence... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.