content stringlengths 42 6.51k |
|---|
def filter_feature_table(qza: str, new_qza: str, meta: str) -> str:
"""
:param qza:
:param new_qza:
:param meta:
:return:
"""
cmd = '\nqiime feature-table filter-samples \\\n'
cmd += '--i-table %s \\\n' % qza
cmd += '--m-metadata-file %s \\\n' % meta
cmd += '--o-filtered-table %s... |
def link_data(link_dict):
"""Data for creating link as in request.data."""
data = link_dict.copy()
del data["user"]
return data |
def flatten(l):
"""Return list `l` flattened."""
flat = []
for x in l:
flat += flatten(x) if isinstance(x, list) else [x]
return flat |
def lng180(lng):
"""Returns a longitude in degrees between {-180, 180] given a longitude in degrees."""
newlng = float(lng)
if lng <= -180:
return lng + 360
if newlng > 180:
return lng - 360
return lng |
def issue_command_deterministic(policy):
""" Issue a migration command according to the policy PMF p.
:param policy: A policy PMF.
:type policy: list(number)
:return: A migration command.
:rtype: bool
"""
return len(policy) == 0 |
def has_tag(tags, target) -> bool:
"""
Verifies that the `target` tag is present in a query set.
@param tags: tags to be checked
@param target: the tag searched for
@return: True if the target is present, False otherwise
"""
for tag in tags:
if tag.tag == target:
return T... |
def get_up(row):
"""Get the value of 'upmulticolor' based on an annotation :row:"""
check = True
for k,v in row.items():
if k.startswith("up") and k!="up" and v==2:
check = False
return check |
def basename(name: str) -> str:
"""Get base name."""
sname = name.rsplit('.', maxsplit=1)
if len(sname) == 1:
return name
else:
return sname[1] |
def convert_archive_posts(archive_posts):
"""Convert a list of SQL post rows to the format used for display within the post archive."""
converted_archive = [];
current_year = ""
current_month = ""
for post in archive_posts:
# If the posts created year is not the current year being parsed, ... |
def get_safe_name(name: str) -> str:
""" Returns the safe version of a username. """
return name.lower().replace(' ', '_') |
def get_github_repository_data(initial_data, header, resources=[]):
"""
Get's the repository data.
Parameters
----------
initial_data: list
The initial data
header: dict
The gitHub authorization header
resources: list
The user's resources
Returns
-------
... |
def get_other_props(all_props,reserved_props):
"""
Retrieve the non-reserved properties from a dictionary of properties
@args reserved_props: The set of reserved properties to exclude
"""
if hasattr(all_props, 'items') and callable(all_props.items):
return dict([(k,v) for (k,v) in all_props.items() if k n... |
def pd_to_sd(pd):
"""
Converts a device name from Windows' physical device ID (ie: pd0) to
Linux's sda notation. Handles up to 'pd675' = 'sdzz'.
###Args:
* **pd (int):** Physical device ID number.
##Returns:
* **(str):** Linux-style 'sd_' device name.
"""
try:
pd = int(pd)
... |
def get_common_name(names):
"""Find left substring common to all names, by splitting names on spaces,
and possibly ignoring certain common words.
>>> get_common_name([
'Polyfield Soft Vinyl Patient Pack with small gloves',
'Polyfield Soft Vinyl Patient Pack with medium gloves',
'Pol... |
def lower_dict_keys(origin_dict):
""" convert keys in dict to lower case
Args:
origin_dict (dict): mapping data structure
Returns:
dict: mapping with all keys lowered.
Examples:
>>> origin_dict = {
"Name": "",
"Request": "",
"URL": "",
... |
def _parse_freeze(text):
"""Parse a freeze into structured data.
:param text: The output from a pip freeze command.
:return: A list of (package, version) tuples.
"""
result = []
for line in text.splitlines():
line = line.strip()
if line.startswith('-'):
raise Excepti... |
def pad_encryption_key(
encryption_key: bytes, length: int, fill: bytes = b"\x00"
) -> bytes:
"""
Right-pad an encryption key to meet a certain length requirement.
This lets us use 128-bit keys with the required 256-bit algorithm (for shorter URLs).
"""
if len(encryption_key) > length:
r... |
def invert_dict(d):
""" Generate a new dictionary with the key/value relationship inverted """
newd = {}
for k in d:
newd[d[k]] = k
return newd |
def underline(text: str) -> str:
"""
Return the *text* surrounded by underline HTML tags.
>>> underline("foo")
'<u>foo</u>'
"""
return f"<u>{text}</u>" |
def reduceFloatValue(m):
""" Seems to be an int/float value, so get rid of the
appended unit in the string.
"""
sl = m.split()
if len(sl) == 2:
value = sl[0]
else:
value = m
# Also reduce trailing zeros
while value.endswith('00'):
value = value[:-1]
retu... |
def get_salary_continuous(x):
""" returns the int value for the ordinal salary
"""
if x == '>50K':
return 1
else:
return 0 |
def hms_string(sec_elapsed: int) -> str:
"""Nicely formatted time string.
Args:
sec_elapsed (int): Integer number of seconds.
Returns:
str: h:m:s formatted string.
"""
h = int(sec_elapsed / (60 * 60))
m = int((sec_elapsed % (60 * 60)) / 60)
s = sec_elapsed % 60
return "... |
def print_name(name, word_count_threshold=7, break_point_ratio=0.6):
"""Splits name of item in legend into 2 lines
if word count exceeds threshold"""
words = name.split(" ")
word_count = len(words)
if word_count > word_count_threshold:
position = round(word_count*break_point_ratio)
... |
def format_property(obj, name):
"""
Format an object property's dotted name.
:param obj: The object that owns the property.
:param name: The name of the property (a string).
:returns: The dotted path (a string).
"""
return "%s.%s" % (obj.__class__.__name__, name) |
def split_string_with_commas(value):
"""
Splits a passed value to a list. The comma is delimiter.
Note all whitespaces will be removed before the splitting.
Example:
incoming value "a, b, c"
output value ["a", "b", "c"]
"""
return value.replace(" ", "").split(",") if value else... |
def cipher(map_from, map_to, code):
""" map_from, map_to: strings where each contain
N unique lowercase letters.
code: string (assume it only contains letters also in map_from)
Returns a tuple of (key_code, decoded).
key_code is a dictionary with N keys mappi... |
def argument(*name_or_flags, **kwargs):
"""Convenience function to properly format arguments to pass to the
subcommand decorator.
"""
args = list()
for arg in name_or_flags:
args.append(arg)
return args, kwargs |
def reverseNumberv1(num):
"""assumes num is a int
returns an int, the reverse of num"""
return int(str(num)[::-1]) |
def make_extra_vars(arguments):
"""
convert from name=value;name=value into dictionary
:param arguments:
:return: dictionary of name/value pairs
"""
extra_vars = {}
if arguments:
for item in arguments.split(u";"):
if item.strip(u' '):
k, v = item.split(u"=... |
def check_perun_integration(subdirs):
"""Helper function for determining the existence of perun wrapper over the underlaying vcs
:param str subdirs: list of subdirectories located in the repository
:return: str depending on the status
"""
for name in subdirs:
if name == '.perun':
... |
def tolist(item):
"""
Converts the item to a list, or just returns the list
"""
return item if type(item) == list else list(item) |
def qscleaner(w):
"""
Just remove ? character from a word.
"""
w=w.replace('?','')
return w |
def find_result_sentiment(words, word_sentiments):
"""Compute average sentiment for a result represented as a list of words.
Words not in word_sentiments are ignored.
If we don't have sentiment for any wd in words, return None.
"""
word_ratings = [word_sentiments[wd] for wd in words
... |
def smcpToC2scName( smcpname ):
"""Turns 'aacute.smcp' into 'Aacute.c2sc'."""
if smcpname[0:2] in ["ae","oe","ij"]:
glyphname = smcpname[0:2].upper() + smcpname[2:smcpname.find(".")]
else:
glyphname = smcpname[:smcpname.find(".")].title()
suffix = smcpname[smcpname.find("."):].replace("smcp", "c2sc")
return gl... |
def lower_in(string, matches):
"""
This function returns if ``string`` lowercase is in ``matches``.
Args:
string(str): The string to check.
matches(Iterable): The list of matches to check against.
Returns:
bool: Whether ``string`` lowercase is in ``matches``.
"""
return strin... |
def bar_2(x, greeting='hello'):
"""bar greets its input"""
return f'{greeting} {x}' |
def condense_stem_pairs(stem_pairs):
"""
Given a list of stem pairs, condense them into stem definitions
I.e. the pairs (0,10),(1,9),(2,8),(3,7) can be condensed into
just the ends of the stem: [(0,10),(3,7)]
:param stem_pairs: A list of tuples containing paired base numbers.
:returns: A list... |
def trim_trailing(s, trailer):
"""
Trim *trailer* from the end of *s* (if present) and return it.
:param s: string to trim from
:type s: string
:param trailer: string to trim
:type trailer: string
"""
tl = len(trailer)
if s[-tl:] == trailer:
return s[:-tl]
else:
... |
def get_case_value (my_case, dict_cases) :
"""Get the case value"""
if my_case in dict_cases:
return dict_cases[my_case]
return 0 |
def _bisect_value(min_, max_):
"""Return value half way between min and max."""
return min_ + 0.5 * (max_ - min_) |
def matrix_size2ind(matrix_size):
"""SR index segmentation."""
r = []
for i in range(0, len(matrix_size) + 1):
r.append(sum(matrix_size[:i]))
return list(zip(r, r[1:])) |
def prev_good(bad_samples_idx, i):
"""
Find the index of the previous good item in the list.
:param bad_samples_idx: List of the indices of the bad samples.
:param i: Index of the current item.
:return: Index of the previous good item.
"""
while True:
i -= 1
if i < 1:
... |
def decode_mode(mode):
"""
JJ2 uses numbers instead of strings, but strings are easier for humans to work with
CANNOT use spaces here, as list server scripts may not expect spaces in modes in port 10057 response
:param mode: Mode number as sent by the client
:return: Mode string
"""
if... |
def Query(month,year):
"""
args : month name and year
output : query to search gold price
"""
return "gold-price-"+month+'-'+str(year)+'.php' |
def echo(request, data):
"""
This is a function that we will expose.
"""
# echo data back to the client
return data |
def to_league_name(league_name):
"""Maps league name to the league name used by Understat for ease of use.
"""
league_mapper = {
"epl": "EPL",
"la_liga": "La_liga",
"bundesliga": "Bundesliga",
"serie_a": "Serie_A",
"ligue_1": "Ligue_1",
"rfpl": "RFPL"
}
... |
def truncate(expr, precision):
""" Truncate number to precision
Examples
--------
>>> from blaze import symbol, compute
>>> x = symbol('x', 'real')
>>> compute(x.truncate(10), 123)
120
>>> compute(x.truncate(0.1), 3.1415) # doctest: +SKIP
3.1
"""
return expr // precision * ... |
def reverseStringStackv1(a_string):
"""assumes a_string is a string
returns a string, the reverse of a_string"""
letters_list = list(a_string)
reversed_letters_list = []
for i in range(len(letters_list)):
reversed_letters_list.append(letters_list.pop())
return "".join(reversed_letters_li... |
def parse_db_arguments(string):
"""Return a list of db arguments parsed from string.
Split string into arguments, strip whitespace from them, and return a list of
the resulting arguments.
"""
arguments = string.split(',')
arguments = [argument.strip() for argument in arguments]
return a... |
def longest_palindrome(text):
""" Find the maximum length of a palindrome subsequence
Dynamic Programming approach on solving the longest palindromic sequence.
Time complexity: O(n^2), n = length of text.
Args:
text: string which will be processed
Returns:
Integer of maximum palind... |
def teaser(s, delimiter='<!-- more -->'):
""" Returns the portion of the string `s` before `delimiter`,
or an empty string if `delimiter` is not found. """
index = s.find(delimiter)
if index == -1:
return ''
else:
return s[:index] |
def gen_test_id(test_id: str) -> str:
"""
Convenience function to print test identifier as URI
:param test_id: test suite identifier
:returns: test identifier as URI
"""
return f'http://wis.wmo.int/2012/metadata/conf/{test_id}' |
def is_suspicious(transaction: dict) -> bool:
"""Simple condition to determine whether a transaction is suspicious."""
return transaction["amount"] >= 900 |
def ergscmum_to_mjy(flux, lambda_microns):
"""
From erg/s/cm^2/um to mJy
"""
#flux = u.Quantity(flux, u.erg*u.s**(-1)*u.cm**(-2)*(u.um))
#lambda_microns = u.Quantity(lambda_microns*(u.um))
dflux = flux*(lambda_microns**2)*1e26/3e14
return dflux |
def xor_cipher_decrypt(text, key):
"""Decrypts the text using an XOR cipher where the key is provided
as a byte array. The key cannot be an empty byte array. Where the
key is shorter than the text to be encrypted, the same key will
continually be reapplied in succession. The input text must be in
th... |
def increment(x):
"""adds 1 to x"""
return(x+1) |
def format_port(port):
"""Render port option."""
return '-p {}'.format(port) if port else '' |
def calculate_per_activity_average(total_value, total_activities):
"""
Calculate the average for a list of items.
"""
if total_activities == 0:
return 0
activity_average = total_value / total_activities
return round(activity_average, 2) |
def sizeof_fmt(num):
"""Make an amount of bytes humanreadable with the correct unit.
Args:
num (int): amount of bytes
Returns
str: formated amount of bytes with unit
"""
for unit in ['', 'Ki', 'Mi']:
if abs(num) < 1024.0:
return '{:3.2f}{}B'.format(num, unit)
... |
def longest_palin_substring(str1):
"""
dp[size][i] = dp[size-2][i+1] if str[i] == str[j]
else
dp[size][i] = False
where dp[size][i] = If substring of size `size` starting at index `i` is palindrome or not.
Answer = max of all (j-i+1) where dp[i][j] is True.
"""
str_len = len(str1)
is... |
def does_dominate(g1, g2, delta1, delta2):
"""
Returns true if g1 dominates g2 with the given relaxation.
Parameters
----------
g1 : tuple of float
Objective values of a point
g2 : tuple of float
Objective values of a point
delta1 : tuple of float
Relaxation of 'g1'
... |
def should_scrolling_continue(rule_conf):
"""
Tells about a rule config if it can scroll still or should stop the scrolling.
:param: rule_conf as dict
:rtype: bool
"""
max_scrolling = rule_conf.get('max_scrolling_count')
stop_the_scroll = 0 < max_scrolling <= rule_conf.get('scrolling_cycle'... |
def smartconvert(data_string):
"""
Attempts to convert a raw string into the following data types, returns the first successful:
int, float, str
"""
type_list = [int, float]
for var_type in type_list:
try:
converted_var=var_type(data_string.strip())
#Check for... |
def linfunc(x, a, b):
"""Linear fitting function of first order."""
return a*x + b |
def provn_structure(content):
"""Surround contend with provn header and footer"""
content = content.strip()
if not content.startswith("document"):
content = "document\ndefault <http://example.org/>\n" + content
if not content.endswith("endDocument"):
content = content + "\nendDocument"
... |
def index2bitstring(i, length):
""" Turns an index into a bitstring of a given length. """
if i >= 2 ** length:
raise ValueError("Index should be less than 2 ** length.")
if not i and not length:
return ()
return tuple(map(int, '{{:0{}b}}'.format(length).format(i))) |
def to_list_of_lists(lofl):
"""Converts an iterable of iterables to a list of lists, needed
for some tests (e.g. when one has a tuple of lists, a list of tuples, ...)
:param lofl: an iterable of iterables
:return: a list of lists"""
return [[el for el in l] for l in lofl] |
def _readable_duration(duration):
"""Convert a duration in seconds to a human-readable duration.
Parameters
----------
duration : int
A duration in seconds.
Returns
-------
str
A human-readable duration.
"""
rounded_duration = round(duration)
if rounded_durati... |
def toDict(cles,valeurs):
"""
- cles = "cle1 cle2 cle3 ..."
- valeurs = "val1 val2 val3...", les valeurs sont des entiers ou des reels
retourne un dictionnaire cle,valeurs
"""
d={}
for key,value in zip(cles.split(),valeurs.split()) :
try: w=int(value)
except ValueError : w=fl... |
def insert_timeline_csv_data(csvdata, timeline):
"""
Given a list of strings (CSV data),
insert the timeline value at the
front of each line (first column).
"""
new_csvdata = []
for line in csvdata:
new_csvdata.append(f"{timeline},{line}")
return new_csvdata |
def REVERSE_ARRAY(expression):
"""
Accepts an array expression as an argument and returns an array with the elements in reverse order.
See https://docs.mongodb.com/manual/reference/operator/aggregation/reverseArray/
for more details
:param expression: Any valid expression as long as it resolves to a... |
def sum_fields(values, numbers):
"""
Sum values of fields with given numbers
Arguments:
- values: list of values
- numbers: list of fields to sum
Return sum of fields with given numbers
"""
total = 0
for i in numbers:
total += values[i]
return total |
def application(environ, start_response):
"""The web application."""
response_body = ""
for key, value in environ.items():
response_body += "<p>{} : {}\n</p>".format(key, value)
# Set up the response status and headers
status = '200 OK'
response_headers = [
('Content-Type', 'te... |
def reduce(function, iterable, initial):
"""
Functional reduce function.
Take an iterable and apply the specified function to each element.
The result is fed into the next function call.
"""
accumulator = initial
for (index, item) in enumerate(iterable):
accumulator = function(accum... |
def sanitize_str_xml(text, no_newlines=False):
"""Returns an instance of the input text with all characters
which comply with the xml1.0 charset specification. ie. no
NULL characters, ASCII control characters (except newline), etc.
text : str input text
"""
def is_valid_xml_char(c):
c = ... |
def update_registration(scopeURL: str) -> dict:
"""
Parameters
----------
scopeURL: str
"""
return {
"method": "ServiceWorker.updateRegistration",
"params": {"scopeURL": scopeURL},
} |
def str_to_ord(a):
"""
Allows indexing into a string or an array of integers transparently.
Generic utility function.
"""
if type(a) == type(b'') or type(a) == type(u''):
a = ord(a)
return a |
def as_key(key):
"""Strips any / prefix and/or suffix from a supplied key (path) string.
Most uses of the asset path as a key (other than validation by
is_path_allowed) expect any leading and trailing / URL path
separators have been removed.
"""
return key.lstrip('/').rstrip('/') |
def show_help(obj):
"""Abre os ficheiro de ajuda da pasta help"""
code = 'Sem Ficheiro de ajuda!'
filename = '/var/www/core/help/' + obj + '.html'
try:
with open(filename, 'r') as open_file:
code = open_file.read()
except:
pass
return code |
def merge(ds):
"""This function merges a set of DAGs into a DAG.
"""
return {k: v for d in ds for k,v in d.items()} |
def _extract_name_arg(args, kwargs, name_index):
"""Extracts the parameter `name` and returns `(args, kwargs, name_value)`."""
if name_index < 0:
name_value = None
elif name_index < len(args):
name_value = args[name_index]
args = args[:name_index] + args[name_index + 1:]
else:
name_value = kwarg... |
def next_marker_by_id(collection, limit, marker):
"""
Returns the next marker based on the limit-1 item in the collection
:param collection: an iterable containing the collection to be paginated
:param limit: the limit on the collection
:marker: the current marker used to obtain this collection
... |
def to_binary(x):
"""Convert a binary field to 1's and 0's"""
if x == None:
return 0
else:
return 1 |
def reduce_datetimes(row):
"""
Receives a row, converts datetimes to strings.
"""
row = list(row)
for i, iterrow in enumerate(row):
if hasattr(iterrow, 'isoformat'):
row[i] = iterrow.isoformat()
return tuple(row) |
def quaternion_to_rotation_matrix_rows(w, x, y, z):
"""Returns a tuple of three rows which make up a 3x3 rotatation matrix.
It is trival to turn this into a NumPy array/matrix if desired."""
x2 = x*x
y2 = y*2
z2 = z*2
row0 = (1 - 2*y2 - 2*z2,
2*x*y - 2*w*z,
2*x*z + 2*w*y)... |
def get_chars_from_guesses(guesses):
"""
gets characters from guesses (removes underscores), removes duplicates and sorts them in an array which is returned.
example guess: "__cr_"
"""
guesses_copy = guesses.copy()
guesses_copy = "".join(guesses_copy)
return sorted("".join(set(guesses_copy.r... |
def extract_history(history_list: list, field: str) -> list:
"""Extract the historical measurements contained in the alerts
for the parameter `field`.
Parameters
----------
history_list: list of dict
List of dictionary from alert['prv_candidates'].
field: str
The field name for ... |
def print_format_creator(type_spec, length):
"""
returns string format spec, to print a list of items. Each item in the list should be of the same type.
:param type_spec: data sample, to determine type from.
:param length: amount of items to be printed.
:return: format string.
"""
if type(ty... |
def validate_parcel_data(data):
"""validate parcel delivery orders details"""
try:
# check if description is empty
if data["descr"] is False:
return "parcel description required"
elif isinstance(data["descr"], int) is True:
return "Description must be a string"
... |
def precision_and_recall_stat(gold_nodes_list, pred_nodes_list):
"""
Return:
- the number of correctly labeled items
- the number of gold standard items
- the number of predicted items
>>> gold_nodes_list = [[('S', 0, 11), ('NP', 0, 2), ('VP', 2, 9), ('VP', 3, 9), ('NP', 4, 6), ('PP', 6, 9... |
def conv_output_dim(input_dim, kernel_size, stride, padding,
transpose=False):
"""
Parameters
----------
input_dim : int
input size. may include padding
kernel_size : int
filter size
stride : int
stride length
padding : int
length ... |
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
new_list = [0] * len(line)
ind = 0
for ele in line:
if ele == 0:
continue
elif new_list[ind] == 0:
new_list[ind] = ele
elif new_list[ind] == ele:
new_list[i... |
def _top_shape(x_shape): # pylint: disable=invalid-name
"""Helper: shape of top element of a stack."""
if isinstance(x_shape[0], (list, tuple)):
return x_shape[0]
return x_shape |
def _get_params_prefix(opname, layer_num):
"""Makes the params prefix name from opname and layer number."""
return str(opname) + str(layer_num) |
def code_block(message, lang=None, name=None, lines=None, isBad=False):
"""Return a string code block.
Note that the code block should start on a new line and will insert
a blank line at the start and end of itself. If there is already a
preceeding blank line then the block will not display correctly.... |
def get_size(bytes, suffix="B"):
"""Scale bytes to its proper format, e.g. 1253656 => '1.20MB'"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{bytes:.2f} {unit}{suffix}"
bytes /= factor |
def get_between_tags(line):
""""Returns portion of line between xml tags."""
return line.split('>', 1)[1].rsplit('<', 1)[0] |
def color_code(word, match, color):
"""Returns the LaTeX command used to color a word
Keyword arguments:
word -- Word that must be colored
match -- Pattern that will be replaced with a LaTeX command
color -- Color to be used
"""
code = r'\BDT' + color + '{'+word+'}'
match = match.replace(word, code)
retur... |
def get_display_name(record):
"""Get the display name for a record.
Args:
record
A record returned by AWS.
Returns:
A display name for the task definition.
"""
return str(record["family"]) + ":" + str(record["revision"]) |
def flatten_lists(listoflists):
"""
Flatten a python list of list
:param listoflists: (list(list))
:return: (list)
"""
return [el for list_ in listoflists for el in list_] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.