content stringlengths 42 6.51k |
|---|
def check_publish(publish):
""" Convert the list of published variables to a set with unique elements.
"""
if publish is None:
publish = []
elif isinstance(publish, str):
publish = [publish]
elif isinstance(publish, (list, tuple)):
pass
else:
msg = "The publish k... |
def format_number(value, truncate_after=None):
"""
Format a number with thousands separator
:param value: number to format
:param truncate_after: if a number, will round into 1k, 15m format above this
:return: str
"""
if truncate_after is not None and value > truncate_after:
if value... |
def str2bool(cstr: str) -> bool:
"""
It compares a string with anything like true, and it returns True or False
Args:
cstr:
Returns:
Boolean value of the string
"""
return cstr in ['True', 'true', 't', True] |
def access_extra(access_rights):
"""
Check if field is related-model.
"""
return_value = []
for i in access_rights:
if "." in i:
item = i.split(".")
return_value.append(tuple(item))
return return_value |
def sum_func(n=100_000_000):
""" using built in sum function """
return sum(range(n)) |
def span_context_to_string(trace_id, span_id, parent_id, flags):
"""
Serialize span ID to a string
{trace_id}:{span_id}:{parent_id}:{flags}
Numbers are encoded as variable-length lower-case hex strings.
If parent_id is None, it is written as 0.
:param trace_id:
:param span_id:
:par... |
def checkout(skus):
"""In a normal supermarket, things are identified using Stock Keeping Units, or SKUs.
In our store, we'll use individual letters of the alphabet (A, B, C, and so on).
Our goods are priced individually. In addition, some items are multi-priced: buy n of them, and they'll cost you y pounds.
For ex... |
def is_number(s):
"""
Check a string is a int or a flot or not.
:param s:
:return:
"""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
... |
def _maybe_repeat(x, n):
"""Utility function for processing arguments that are singletons or lists.
Args:
x: either a list of n elements, or not a list.
n: repeat n times.
Returns:
a list of n elements.
"""
if isinstance(x, list):
assert len(x) == n
return x
e... |
def short_name(name, limit=20):
""" Truncate a model name to limit chars"""
return name if len(name) <= limit else f"{name[:limit - 3].rstrip('_')}..." |
def descriptor2colspecs(descriptor_str):
"""
Convert fortran format string, e.g., `2I4,4I3,3I4,2I7,F6.2,I7,
8F8.2,4F8.1,F7.2,F9.0,F6.2,2F7.2,F6.1,6F8.2,7I6,F7.2,F5.1`, to the
list of fixed columns tuples expected by :func:`pandas.read_fwf`.
"""
colspecs = []
i = 0
for tok in descriptor_s... |
def config_func(config_old, config_new):
"""
CANedge configuration update function
:param config_old: The current device configuration
:param config_new: Default new device configuration
:return: Update configuration
"""
# This is an example of a simple configuration update (without firmwar... |
def source_location(loc, pos):
""" Returns filename:line:column """
if not pos:
return str(loc)
return ':'.join([str(loc), str(pos)]) |
def pr_sha1(payload):
"""Returns the commit hash (the SHA-1)."""
return payload['pull_request']['head']['sha'] |
def format_git_describe(git_str, pep440=False):
"""format the result of calling 'git describe' as a python version"""
if "-" not in git_str: # currently at a tag
formatted_str = git_str
else:
# formatted as version-N-githash
# want to convert to version.postN-githash
... |
def get_rank(user_datum):
"""Returns the name of rank
rank {
name
}
:param user_datum: user data from site
:return: str
"""
rank_datum = user_datum['rank']
if rank_datum is None:
return None
return rank_datum['name'] |
def make_link(text):
"""Format text as reStructuredText link.
Args:
text: Text string to format.
Returns:
Formatted text string.
"""
return '`{}`_'.format(text) |
def field_provides(field, ifaces):
"""Does field provide at least one of the interfaces specified?"""
_pb = lambda iface: iface.providedBy(field)
return any(map(_pb, ifaces)) |
def db_to_power(decibel):
"""
Returns power value from a decibel value.
"""
return 10**(decibel/10) |
def formatted_headers(headers):
"""Please formatted dictionary.
Possible data types in the dictionary: numbers.Number, str, bytes,
list, dict, None (json's key can only be string, json's value may
be number, string, logical value, array, object, null).
Args:
headers (dict): The headers of ... |
def display_name_for_minimizers(names):
"""
Converts minimizer names into their "display names". For example
to rename DTRS to "Trust region" or similar.
@param names :: array of minimizer names
@returns :: the converted minimizer name array
"""
display_names = names
# Quick fix for D... |
def is_buzz(replace_array, count):
"""
This function checks whether the count is a multiple of any of the numbers in replace_array[0] are replaces the
output with the text with the same index in replace_array[1]. If it is not a multiple with any of the numbers it
will return the number as a string.
... |
def str_to_bytes(string):
"""Takes a string and returns a byte-representation"""
return str.encode(string) |
def hello(name):
"""
(aside)
Getting resources from the path. This is good for querying databases:
path parameters represent entities (tables in your DB, more or less).
"""
return "Hello {}".format(name) |
def sliding_window(frame_length, step, Xsampleslist, ysampleslist):
"""
Splits time series in ysampleslist and Xsampleslist
into segments by applying a sliding overlapping window
of size equal to frame_length with steps equal to step
it does this for all the samples and appends all the output t... |
def get_relabeled_dataset(dataset_name: str) -> str:
""" """
return dataset_name + "-relabeled" |
def is_number(something):
"""
Check if `something` is a number.
Parameters
----------
something : anything
Something to be checked.
Returns
-------
boolean
True if `something` is a number. False otherwise.
"""
try:
float(something)
return True
... |
def match_rules(rules, app, action):
"""
This will match rules found in Group.
"""
for rule in rules.split(','):
rule_app, rule_action = rule.split(':')
if rule_app == '*' or rule_app == app:
if rule_action == '*' or rule_action == action or action == '%':
ret... |
def replace_dynamic(data: dict) -> dict:
"""Replace dynamic fields with their type name."""
for key in ["id", "uuid", "dbnode_id", "user_id", "mtime", "ctime", "time"]:
if key in data:
data[key] = type(data[key]).__name__
return data |
def get_cleantracks(t_d: dict):
"""
return concise dict with song ID's and url from results returned from get_albumtrax()
can use with a corpus of albums and tracks, this is pre-processing step before
getting the lyrics for the songs
:param t_d: the raw info on album tracks returned from get_albumtr... |
def rgbfloat2rgbint(i):
"""
Convert a rgb float value (0.0-1.0) to a rgb integer value (0-255).
Args:
i (int): Float value from 0.0 to 1.0
Returns:
int: Integer values from 0 to 255
"""
return int(255 * i) |
def normalization(M):
""" Returns matrix with normalized values
M: Input matrix
"""
global max_va
max_va=[] # storing malx values of each row
m=[] # intiliating list for storing normalized values
for i in M :
max_va.append(max(i)) #storing max values for calculati... |
def get_target_ids(targetcount, targetspec):
"""Get target ids from target spec:
* a - individual item
* a:b - range a to b (non-inclusive), step 1
* a:b:c - range a to b (includes a, not b), step c (where c is
positive or negative)
"""
targetranges = []
for el in targetspec.split(","):... |
def sumy_clean_lines(lines):
"""
Compared to regular clean lines, this one preserves heading and paragraph information.
"""
new_lines = []
for line in lines:
if line.startswith("="):
new_lines.append(line.strip("=").upper())
else:
new_lines.append(line)
... |
def omt_check(grade_v, grade_i, grade_j):
"""
A check used in omt table generation
"""
return grade_v == (grade_i + grade_j) |
def binary_search(list_: list, item: int = 0):
"""Returns the index of the number to find in the SORTED list
:param list_: SORTED list to find the item
:type list_: list
:param item: The number to find the index
:type item: int
:rtype: int, else: None
:return: The index of the number foun... |
def _dynamic_inputs_creation(dynamic_io_settings):
"""Creates a list of inputs names, supplied to the Task class."""
parameters = dynamic_io_settings["TaskSettings"]["Parameters"]
if parameters["ModelType"] == "LDA":
return [f"TF({parameters['DataSource']})"]
elif parameters["ModelType"] == "NM... |
def keys_to_str(config_file):
"""
Non-string keys may break validator with patterned fields.
"""
d = {}
for k, v in config_file.items():
d[str(k)] = v
if isinstance(v, dict):
d[str(k)] = keys_to_str(v)
return d |
def get_underline(str):
"""
Return an underline string of the same length as `str`.
"""
return "="*len(str) + "\n" |
def limit_angle(angle):
"""
make sure angle is 0 <= angle <= 360
"""
while angle < 0:
angle += 360
while angle > 360:
angle -= 360
return angle |
def fold_enrichment(backgr, my_list, path):
"""
Parameters
----------
backgr = list of all the genes in the background transcriptome
my_list = my list of genes
path = list of genes belonging
Return the fold-enrichment, computed as: FE = (m/n)/(M/N)
Where N = num genes in backgr, M = num... |
def resolve_event(url_id):
"""Format the properties of the ``resolve`` event.
:param url_id: the resolve ID of the URL that was resolved
:type url_id: str
"""
return {
'url_id': url_id
} |
def get_best_action(cwnd, target):
""" Returns the best action by finding the diff percentage btw cwnd and target.
"""
return (target - cwnd) * 1.0 / cwnd |
def count_matches(a: str, b: str) -> int:
"""Returns the number of locations where the two strings are equal."""
assert len(a) == len(b)
return sum(int(i == j) for i, j in zip(a, b)) |
def format_link_header(link_header_data):
"""Return a string ready to be used in a Link: header."""
links = ['<{0}>; rel="{1}"'.format(data['link'], data['rel'])
for data in link_header_data]
return ', '.join(links) |
def make_sidenotes(text):
"""
Picks sidenotes wrapped by `!sidenote` `!endsidenote` inside
text
"""
if text.find("!sidenote") > -1:
start = text.find("!sidenote")
end = text.find("!endsidenote")
note = text[start:end].strip("!sidenote")
sidenote = r"\marginnote{"+ no... |
def is_item_iterable(item):
"""Determine if an item is iterable.
Parameters
----------
item : object
The item to test.
Returns
-------
bool
True if the item is iterable.
False otherwise.
Examples
--------
>>> is_item_iterable(1.0)
False
>>> is_i... |
def format_time(seconds):
"""Returns seconds as a formatted string.
The format is "hours:minutes:seconds.millisecond".
Arg:
A float containing a number of seconds.
Returns:
A formatted string containing the time represented by the number
of seconds passed in.
"""
hours... |
def as_attr(text):
"""Replace hyphens with underscores
>>> as_attr('this-page')
'this_page'
"""
return text.replace('-', '_').lower() |
def get_next_core_id(current_id_in_hex_str):
"""
:param current_id_in_hex_str: a hex string of the maximum core id
assigned without the leading 0x characters
:return: current_id_in_hex_str + 1 in hex string
"""
if not current_id_in_hex_str or current_id_in_hex_str == '':
return '0001'
... |
def run_threaded(non_blocking, target_func, *args, **kwargs):
"""Call a function in a thread, when specified"""
if not non_blocking:
return target_func(*args, **kwargs)
from threading import Thread
Thread(target=target_func, args=args, kwargs=kwargs).start()
return None |
def format_version(version):
"""a reverse for parse_version (obviously without the dropped information)"""
f = []
it = iter(version)
while True:
part = next(it)
if part >= 0:
f.append(str(part))
elif part == -1:
break
else:
f[-1] = f[-1... |
def _fft(x_vec, n_x, twiddle):
"""Implementation of Decimation in Time FFT, to be called by d_fft and i_fft.
x_vec is the signal to transform, a list of complex values
n_x is its length, results are undefined if n_x is not a power of 2
twiddle is a list of twiddle factors, to be used in the c... |
def clut8_rgb888(i):
"""Reference CLUT for wasp-os.
Technically speaking this is not a CLUT because the we lookup the colours
algorithmically to avoid the cost of a genuine CLUT. The palette is
designed to be fairly easy to generate algorithmically.
The palette includes all 216 web-safe colours to... |
def divisible_by_2(my_list=[]):
"""
finds all multiples of 2 in a list and returns
a list containing True / False repsective to index
"""
list_len = len(my_list)
if list_len == 0:
return None
bool_list = []
for i in range(list_len):
if my_list[i] % 2 == 0:
bo... |
def is_word_in_phrase(word: str, string: str):
"""Not case sensitive"""
return f"{word.lower()}" in f"{string.lower()}" |
def _tgrep_rel_disjunction_action(_s, _l, tokens):
"""
Builds a lambda function representing a predicate on a tree node
from the disjunction of several other such lambda functions.
"""
# filter out the pipe
tokens = [x for x in tokens if x != "|"]
# print 'relation disjunction tokens: ', tok... |
def adjust_top_mentions(mentions, subtoken_map, sent_start, sent_end):
"""
Adjusts the top mentions indices to reflect position within an individual sentence.
"""
adjusted_mentions = []
for mention in mentions:
if mention[0] >= sent_start and mention[1] <= sent_end:
adjusted_star... |
def get_event_suburb(event):
"""
Returns the second to last comma-separated portion of a Proximity Events address, which basically
appears to always be the suburb. eg. '20 Main Street, Box Hill, VIC'
"""
event_address_parts = event['event_address']['S'].split(', ')
return event_address_parts[len(event_addre... |
def parse_priority(priority):
"""
priority can sometimes be "rt" for real time, make that 99, the highest
"""
try:
return int(priority)
except:
return 99 |
def backends_mapping(custom_backend):
"""
Create custom backends with paths
- "/bin"
- "/"
"""
return {"/bin": custom_backend("backend"), "/": custom_backend("backend2")} |
def getLabels(occurence_dict):
"""
Get the associations in occurence_dict without occurence
INPUT
occurence_dict (list) : contains the associations and occurence
OUTPUT
a list of the associations in occurence_dict
"""
labels = []
for elt in occurence_dict:
labels.appe... |
def _build_string(tokens):
"""Builds string from token list."""
return ' '.join(tokens) |
def toupper(scope, strings):
"""
Returns the given string in upper case.
:type strings: string
:param strings: A string, or a list of strings.
:rtype: string
:return: The resulting string, or list of strings in upper case.
"""
return [s.upper() for s in strings] |
def triangle_area(p1,p2,p3):
"""
calculates the area of a triangle given its vertices
"""
return abs(p1[0]*(p2[1]-p3[1])+p2[0]*(p3[1]-p1[1])+p3[0]*(p1[1]-p2[1]))/2. |
def laceStrings(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
# Your Code Here
if len(s1) > len(s2):
(s1, remainder) = (s1[... |
def is_layout_changed(version, layout_data):
""" returns True if layout matrix changed or added is not zero """
# layout matrix has one less column than the flow ones, because
# it compares 2 versions. if version is zero, we assume no changes
# in the layout
if version == 0:
return True
... |
def _typesizes(types):
"""Returns declaration for array of type sizes for use in the Cfunc
declaration. The Cfunc decl needs to know the element size of each
incoming array buffer in order to do alignment and bounds checking.
"""
sizes = "{ "
for t in types:
sizes += "sizeof(%s), " % (t... |
def are_all_equal(iterable):
"""
Checks if all elements of a collection are equal.
Args:
iterable: iterator
A collection of values such as a list.
Returns:
equal: boolean
True if all elements of iterable are equal. Will also return true if
iterable is ... |
def extract_table_create_data(row_list):
"""
Extract the column information i.e. name, type and modifiers (if any) from first 3 rows of the :param row_list
:param row_list: List of all rows within a csv used during table creation, including header and body rows
:return: Table creation data map with keys... |
def get_save_function(obj, objid):
"""
Returns on_save function name the object with given ID.
:param obj: Structure containing YAML object ( nested lists / dicts ).
:param objid: YAML ID of given page.
:return: Name of onsave function.
"""
result = None
if isinstance(obj, dict):
... |
def intersection(v1, v2):
"""
Returns the intersection of v1 and v2. Note however that these are not 'bezier lines', x1, y1, x3, and y3
are all *changes* in x, not describing a point. So, rather than x0 + (x1 - x0)*t, its just x0 + x1*t.
It just made the algebra slightly easier.
list v1 = [x0, x1, y... |
def test_rgb(h, f):
"""SGI image library"""
if h[:2] == '\001\332':
return 'rgb' |
def add_multipliers(boosts, multiplier_data, user_multipliers):
"""Upload sett and user multipliers
:param test:
:param multiplier_data: sett multipliers
:param user_multipliers: user multipliers
"""
boosts["multiplierData"] = multiplier_data
for user in list(boosts["userData"].keys()):
... |
def disemvowel(string):
"""
Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels
from the trolls' comments, neutralizing the threat. Your task is to write a function that takes a string and
return a new string with all vowels removed.
:pa... |
def process_token(token, word_vocab=None, tag_vocab=None):
"""input token and return the word and tag, or None"""
if token.find('/') == -1:
return None
try:
i = token.rfind('/')
w = token[0: i]
t = token[i+1:].split('|')[0]
# w = w.lower()
t = t.u... |
def dashes(i=1, max_d=12, space=1):
"""Dashes for matplotlib."""
return i * [space, space] + [max_d - 2 * i * space, space] |
def manhattan_distance(x: int, y: int) -> int:
"""compute the manhattan distance"""
return abs(x) + abs(y) |
def get_batch_0(data, index, batch_size):
""" Return a slice of data for SGD batching (labels)"""
batch = data[index * batch_size:(index + 1) * batch_size]
return batch |
def to_int_keys(l):
"""
l: iterable of keys
returns: a list with integer keys
"""
seen = set()
ls = []
for e in l:
if not e in seen:
ls.append(e)
seen.add(e)
ls.sort()
print(ls)
index = {v: i for i, v in enumerate(ls)}
print(index)
return [... |
def _device_stack(device_link, device_stack):
"""
Link to backup device (for csv)
"""
if device_stack != None:
return device_link + str(device_stack)
else:
return None |
def create_friedman_line(point0,point1):
"""
Determines the second point needed to form the Friedman line
:param point0: First point on glenoid line, anatomically defined as a
point on the anterior margin of glenoid
:param point1: Second point on glenoid line anatomically defined as a
... |
def get_func_source(obj):
"""Get object's source code. Returns None when source can't be found.
"""
from inspect import findsource
from dis import findlinestarts
try:
lines, lnum = findsource(obj)
ls = list(findlinestarts(obj.func_code))
lstart = ls[0][1]
len... |
def valid(text, chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""Returns a copy of text than only contains characters in chars
This function is case-sensitive.
>>> valid("Barking")
'B'
>>> valid("KL754", "0123456789")
'754'
>>> valid("BEAN", "abcdefghijklmnopqrstuvwxyz")
''
""... |
def extract_target_endpoints(targets, known):
"""
There are subscribed endpoints (@known) and there are targets that a user
wants to share the resource with. This function gets a "union" of the two and
will return only those targets that are in the known state.
@param targets: a list of url... |
def rewrite_mapping_safe(pending, existing):
"""This re-writes mappings for ElasticSearch in such a way that
immutable values are kept to their existing setting, while other
fields are updated."""
IMMUTABLE = ('type', 'analyzer', 'normalizer', 'index')
# This is a pretty bad idea long-term. We need ... |
def define_enum(arg_enumKeys, arg_enumFirstValue = 0):
""" For a list of keys, create an cpp-like enum in the form of a dictionary"""
enumDict = {}
for idx, tKey in enumerate(arg_enumKeys):
enumDict[tKey] = idx + arg_enumFirstValue
return enumDict |
def FilterBlocks(blocks, filter_func):
"""Gets rid of any blocks if filter_func evaluates false for them.
Args:
blocks: [(offset1, offset2, size), ...]; must have at least 1 entry
filter_func: a boolean function taking a single argument of the form
(offset1, offset2, size)
Returns:
... |
def compare_digests(digests1, digests2):
"""
Compares two dictionaries of digests, as produced by `digest_files`.
Args:
digests1: First dictionary of digests.
digests2: Second dictionary of digests.
Return:
A sorted list of all the files with different digests.
"""
diff... |
def left_justify(words, width):
"""
Left justify words.
:param words: list of words
:type words : list
:param width: width of each line
:type width: int
:return: left justified words as list
"""
return ' '.join(words).ljust(width) |
def getIdFromOriginator(originator: str, idOnly: bool = False) -> str:
""" Get AE-ID-Stem or CSE-ID from the originator (in case SP-relative or Absolute was used) """
if idOnly:
return originator.split("/")[-1] if originator is not None else originator
else:
return originator.split("/")[-1] if originator is not... |
def escape(s, level):
"""Bash-escape the string `s`, `level` times."""
if not level:
return s
out = ''
for c in s:
if c in r"""\$'<[]""":
out += f"\\{c}"
else:
out += c
return escape(out, level-1) |
def weaksauce_encrypt(text, password):
"""Weakly and insecurely encrypt some text"""
offset = sum([ord(x) for x in password])
encoded = ''.join(
chr(min(ord(x) + offset, 2**20))
for x in text
)
return encoded |
def _repr(val):
"""Returns the representation of *val* if it's not a ``str``."""
return val if isinstance(val, str) else repr(val) |
def logNE(a, b):
"""Returns 1 if the logical value of does not equal the logical value of b, 0 otherwise"""
return (not a) != (not b) |
def hex_to_rgb(hex_color: str, alpha: float) -> str:
"""Convert color in hex to rgb and add alpha channel"""
hex_color = hex_color.lstrip('#')
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
return f"rgba({r}, {g}, {b}, {alpha:.2f})" |
def ExpandEnvVars(string, expansions):
"""Expands ${VARIABLES}, $(VARIABLES), and $VARIABLES in string per the
expansions list. If the variable expands to something that references
another variable, this variable is expanded as well if it's in env --
until no variables present in env are left."""
for k, v in ... |
def join_lines(columns, separator=''):
"""Joins an arbitrary number of multi-line strings side-by-side splitting on
the '\n' character. It pads the ends of lines with ' ' characters as needed
to preserve alignment.
Args:
columns: List of multi-line strings to join.
separator: Padding in... |
def closest_pair(point_list):
"""Gets the closest pair of points from a list of points."""
return point_list[0], point_list[1] |
def safe_numeric(string, default=0):
"""Converts string to int or float or returns default.
Args:
string: string to be converted to numeric
default: number to return in case of failure
Returns:
integer value, if possible, otherwise float or default
"""
try:
n = flo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.