content stringlengths 42 6.51k |
|---|
def quote_and_escape(value):
"""Quote and escape a string.
Adds enclosing single quotes to the string passed, and escapes single
quotes within the string using backslashes. This is useful for passing
'extra vars' to Ansible. Without this, Ansible only uses the part of the
string up to the first whi... |
def cord(value):
"""Convert (str or int) to ord"""
if isinstance(value, str):
return ord(value)
return value |
def get_char_vocab(dataset):
"""Build char vocabulary from an iterable of datasets objects
Args:
dataset: a iterator yielding tuples (sentence, tags)
Returns:
a set of all the characters in the dataset
"""
vocab_char = set()
for words, _ in dataset:
for word in words:
... |
def sort_possibles(x):
"""Sort Key For Possibles"""
# pylint: disable=unused-variable
name, regex, search, match, conditions = x
lc = len(conditions)
if search:
span = search.span()
ls = span[1] - span[0]
else:
ls = 0
if match:
span = match.span()
lm... |
def is_considered_order(id1, id2, to_consider, order):
"""A function deciding if the resource should be considered using the order"""
main_order = order(id1, id2)
return 0.5 < order(id1, to_consider) and 0.5 < order(to_consider, id2) |
def grayscale(c):
"""Compute perceptive grayscale value"""
return int(c[0] * 0.3 + c[1] * 0.59 + c[2] * 0.11) |
def make_palindrome(n: int, base: int = 10, odd_length: bool = False) -> int:
"""Forms a palindrome in the given base, using a positive integer seed.
Args:
n: A positive integer value.
base: The base in which the resulting number will be a palindrome. Must
be at least 2.
odd... |
def is_list_entity(row_value):
"""All list entities have the following structure:
{"key": [{<data>}]}
so this function tests specifically this.
Args:
row_value: Object to test
"""
if not isinstance(row_value, dict):
return False
if len(row_value) != 1:
return ... |
def dag_paths(dag):
""" :return A frozenset containing every path (v1,v2,...,vn) such that each vi is nested within @dag and
is a direct element of at most one set.
:param @dag A nested structure of elements where each element is a string, a tuple or a frozenset. """
if dag == ():
return {()}
... |
def isDataset(inputData):
"""Check whether we're handling a block or a dataset"""
if '#' in inputData.split('/')[-1]:
return False
return True |
def _tokenize_line(line, quote_strings=False, infer_name=True):
"""
Tokenize a line:
* split tokens on whitespace
* treat quoted strings as a single token
"""
ret = []
escape = False
quote = False
tokbuf = ""
firstchar = True
ll = list(line)
while len(ll) > 0:
c =... |
def simple_1arg(hello: str):
"""This will print hello.
Args:
hello: Your name.
"""
return f"Hello {hello}" |
def format_block(block: list) -> str:
"""
Transforms [1, 2, 3, 4, 5, 6, 7, 8] -> 1 2 3
4 5 6
7 8 9
"""
return "\n".join(" ".join(str(v) for v in block[i*3:i*3+3])
for i in range... |
def formatItemRows(itemRows) -> dict:
"""
Formats array of item rows to form
{
"ITEM_TITLE[0]": "test title",
"ITEM_TITLE[1]": "test title 2"
}
:param itemRows:
:return:
"""
items = {}
for title, item in itemRows.items():
for index, value in enumerate(item... |
def remove_line_with(line, pattern):
"""
Returns an empty string if the provided string contains the provided
pattern.
"""
if pattern in line:
return ''
else:
return line |
def update_folder_body(folder_data, tenant_default_store, tenant_default_target, new_tenant):
"""
Creates the json body to update the folder permissions
Takes the existing permission data and appends the new tenant's Id
tenant_default_store in GUI as "Image Target"
tenant_default_target in GUI as "D... |
def subsets(array):
"""iterative solution"""
n = len(array)
subsets_ = []
for i in range(1<<n):
subsets_.append([array[j] for j in range(n) if i & (1<<j)])
return subsets_ |
def unprivilegify_port(port):
"""Not all operating systems allow port forwardings to be in a direct line
with the panametric privilege fan. In these cases we are forced to engage
in additive translation."""
return port + 8000 if port < 1024 else port |
def halfway_reverse_captcha(digits):
"""
Calculate the sum of all digits that are equal to the digit on the opposite
end of a circular list.
>>> halfway_reverse_captcha([1,2,1,2])
6
>>> halfway_reverse_captcha([1,2,2,1])
0
>>> halfway_reverse_captcha([1,2,3,1,2,3])
12
>>> halfway... |
def convert_star_rating(value):
"""
Converts a star rating to a 2 decimal point float.
Args:
value (float): The star rating to convert.
Returns:
float: The converted star rating.
"""
try:
return round(float(value), 2)
except ValueError:
return None |
def offsetify(*offsets):
"""Sum line offsets matched by offset_re_fragment and convert them to strings
like @+3 or @-2."""
offset = sum([int(o) for o in offsets if o is not None])
if offset < 0:
return u"@-" + str(-offset)
elif offset > 0:
return u"@+" + str(offset)
else:
... |
def recover_bitwise_flag_settings(flag, constants_dict) :
"""
@param flag : an integer value to be matched with bitwise OR options set
@param constants_dict : a dictionary containing each options' integer value
@rtype : a string summing up settings
"""
recover = ''
options =... |
def top_5(results):
"""
return the top 5 results as sorted by python
"""
return sorted(results, reverse=True, key=lambda r: r.value)[0:4] |
def _fullname(cls):
"""Return the full name of a class (including the module name)."""
return f"{cls.__module__}.{cls.__qualname__}" |
def multithreaded_parse_pdf_to_string(pdf_file_paths):
"""
:param pdf_file_paths: list() of pdf file paths to parse into strings
:return: dict in the form { 'pdf_file_path': 'parsed_pdf_string' }
"""
parsed_pdf_strings = {
}
return parsed_pdf_strings |
def getScore(msg):
""" msg is the output from denss.align.py
$ denss.align.py -f m01.mrc -ref m02.mrc -o tt
Selecting best enantiomer(s)...
Aligning to reference...
tt.mrc written. Score = 0.381
returning 1-Score to be consistent with NSD (lower value is better)... |
def dict_sub(attrs1, attrs2):
"""Remove attributes `attrs2` from `attrs1`."""
new_dict = {}
for key in attrs1:
if key in attrs2:
new_set = attrs1[key].difference(attrs2[key])
if new_set:
new_dict[key] = new_set
else:
new_dict[key] = attrs1[... |
def invalidCharacterRemover( text, validChars ):
"""its a more stupid way to condition a text
"""
conditionedText = ''
for char in text:
if char in validChars:
conditionedText += char
return conditionedText |
def convert_resource_path(resource_path: str) -> dict:
"""
convert_resource_path - Converts a pack resource path into different parts
Args:
mcfunction_path (str): The path to split
Returns:
dict: The split parts
"""
path = resource_path.split(":")
namespace = path[0]
na... |
def is_tandem(seq):
"""Check if `seq` is tandemly repetitive or not, assuming it is error-free."""
L = len(seq)
for i in range(1, int(L / 2) + 1):
if L % i != 0:
continue
if seq == seq[:i] * int(L / i):
return True
return False |
def check_alarm_input(alarm_time):
"""Checks to see if the user has entered in a valid alarm time"""
if len(alarm_time) == 1: # [Hour] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0:
return True
if len(alarm_time) == 2: # [Hour:Minute] Format
if alarm_time[0] < 24 and alarm_... |
def average(collection, function=None):
"""Calculate the average of values in a collection.
:param collection: The collection with the data to be averaged
:type collection: list | iterator
:param function:
Function used to retrieve data from each element. If not passed an
identity funct... |
def module_from_package(module, pkg, level):
"""Returns whether or not a module is from the package."""
if level == 0:
return module.startswith(pkg + ".")
elif level == 1:
return True
else:
return False |
def cm_alphadot(cm_i, ep_alpha, l_t, mac):
""" This calculates the pitching moment coefficient with respect to the
rate of change of the alpha of attack of the aircraft
Assumptions:
None
Source:
J.H. Blakelock, "Automatic Control of Aircraft and Missiles"
Wiley & Sons, Inc. N... |
def pivotIndex(nums):
"""
:type nums: List[int]
:rtype: int
"""
part1=0
part2=sum(nums)
for i,num in enumerate(nums): #enumerate is faster than range when using index
#to locate an element
part2-=num
if part1 == part2:
return i
part1+=num
return -1 |
def generate_service_selector(pod_name):
"""
| python launcher | framework controller
------------------------------------------------
regular | ab8e7a11-bff7-497f-bd6d-22a326d2c304 | 9cfb453b7afc453bb40a963be1225549-master-0
distributed | 842e9fc8-a4a1-425c-b551-4e5b4fad4337-{ps,... |
def get_class(row):
"""Attempts to give synsets a nice name."""
synset_to_cat = {
# '02691156': 'airplane',
'02933112': 'cabinet',
'03001627': 'chair',
'03636649': 'lamp',
'04090263': 'rifle',
'04379243': 'table',
'04530566': 'watercraft',
'02828884': 'bench',
'... |
def drop_excludes(s):
"""Drop sentences that have the word 'excludes' in them"""
return ".".join(frag for frag in s.split(".") if "excludes" not in frag.lower()) |
def next_power_of_two(v: int):
""" returns x | x == 2**i and x >= v """
v -= 1
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v += 1
return v |
def replace_digit(input_string):
"""
Remove all digits from an input string (Slow on large corpuses).
"""
output_string = "".join([i for i in input_string if not i.isdigit()])
return output_string |
def mean(values):
"""Computes the mean of a sequence of numeric values.
Args:
values: Sequence of numeric values.
Returns:
The mean (floating point).
"""
if len(values) == 0:
raise ValueError("Cannot determine the mode of an empty sequence")
return sum(values) / len(val... |
def divisors(integer):
"""
Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's
divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string
'(integer) is prime' (null in C#) (use Either S... |
def html_decode(s):
"""
Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like <p>.
"""
for code in (
("'", '''),
('"', '"'),
('>', '>'),
('<', '<'),
('&', '&')
): ... |
def alltrue(seq):
"""
Return *True* if all elements of *seq* evaluate to *True*. If
*seq* is empty, return *False*.
"""
if not len(seq):
return False
for val in seq:
if not val:
return False
return True |
def x2trace2(distance, interval):
"""Return the trace number closest to and less than a given distance.
Attributes:
distance <float>: the distance along a GPR line that a trace must be identified;
interval <float>: the distance interval in meters between adjacent traces.
Alternative na... |
def filterComment(comment, comment_args):
"""
Select the type of comment to display based on the command line arguments.
@param comment String The comment from the metric test
@return String The filtered comment
"""
association_dict = {
"s": "SUCCESS",
"f": "FAILURE",
"... |
def select_event(ledger, event_id):
""" Selects only those records that are belongs to the
event_id, key is tuple: (participant_address, event_id) """
return {
key[0]: value for key, value in ledger.items()
if key[1] == event_id
} |
def dict_keys_lower(d):
"""list of dictionary keys in lower case"""
return list(map(str.lower, d.keys())) |
def replace_word_choice(sentence, old_word, new_word):
"""
:param sentence: str a sentence to replace words in.
:param old_word: str word to replace
:param new_word: str replacement word
:return: str input sentence with new words in place of old words
"""
sentence = sentence.replace(old_w... |
def rename_keys(rename_dict, map_dict):
"""
Recursively rename keys in `rename_dict` according to mapping specified
in `map_dict`
returns: dict with new keys
"""
if isinstance(rename_dict, dict):
for k in list(rename_dict.keys()):
if k in map_dict:
new_label ... |
def tint_yellow(text: str) -> str:
"""Tints a given text yellow.
:param text: The text to be tinted
:type text: str
:returns: The same text but tinted yellow
:rtype: str
"""
return ("\x1b[33m%s\x1b[0m" % text) |
def get_rect(width, height, depth):
""" Enter half the width height and depth you would like """
return [
(width, height, depth),
(-width, height, depth),
(-width, -height, depth),
(width, -height, depth),
(width, height, -depth),
(-width, height, -depth),
... |
def tol(shots):
"""Numerical tolerance to be used in tests."""
if shots == 0:
# analytic expectation values can be computed,
# so we can generally use a smaller tolerance
return {"atol": 0.01, "rtol": 0}
# for non-zero shots, there will be additional
# noise and stochast... |
def is_string(x):
"""Tests if something is a string"""
return isinstance(x, str) |
def get_approximation(states_needed: set, stations: dict) -> set:
"""Returns the set of stations which cover the most of the states"""
final_stations = set()
while states_needed:
best_station = None
states_covered = set()
for station, states in stations.items():
covered = states_need... |
def ner_to_sent(sent, replaced, tag="<NE>"):
"""
Args:
- sent is the sentence that has the NER tags in them instead of
the actual named entities.
- replaced is the corresponding list of named entities that
will be inserted in the order of appearance for the tags.
- ta... |
def report_insert_error(error, msg):
"""
Returns text string with cause of the insert error
"""
if error == -3:
return "Lock timeout exceeded"
elif error == -2:
return "Duplicate entry:"+msg
elif error == -1:
return "method 'report_insert' error:"+msg
else:
return "Unknown error:"+error+";... |
def xml_get_attrs(xml_element, attrs):
"""
Returns the list of necessary attributes
Parameters:
element: xml element
attrs: tuple of attributes
Return: a dictionary of elements
"""
result = {}
for attr in attrs:
result[attr] = xml_element.getAttribute(attr)
... |
def command_description(example: str, usage: str) -> str:
"""
This method builds the header for the main screen.
"""
return f"\n\n Name:\n {example}\n\nUsage:\n {usage}" |
def per_token_accuracy(gold_seq, pred_seq):
""" Returns the per-token accuracy comparing two strings (recall).
Args:
gold_seq (`list`): A list of gold tokens.
pred_seq (`list`): A list of predicted tokens.
Returns:
`float`: Representing the accuracy.
"""
num_correct = 0
... |
def CountReordered(sequence_numbers):
"""Returns number of reordered indices.
A reordered index is an index `i` for which sequence_numbers[i] >=
sequence_numbers[i + 1]
"""
return sum(1 for (s1, s2) in zip(sequence_numbers,
sequence_numbers[1:]) if
s1 >= s2) |
def format_password(salt, hash):
"""
Format a password entry for the SCryptPasswordHasher.
"""
algorithm = "scrypt"
Nlog2 = 15
r = 8
p = 1
return "%s$%d$%d$%d$%s$%s" % (algorithm, Nlog2, r, p, salt, hash) |
def unsubscribe_instructions(watch):
"""Return instructions and link for unsubscribing from the given watch."""
return {'watch': watch} |
def parseNamespacePrefixAndTypeString(typeString):
"""Parse type string and return namespace key and type."""
# split on ':' if ':' is there
if typeString is None:
nsprefix = '*'
val = '*'
elif ':' in typeString:
(nsprefix, val) = typeString.split(':', 1)
else:
nspre... |
def parse_options(options, return_list=True):
""" Parse dictionary/json of options, and return arg list for xtb """
cmd_options = []
for key, value in options.items():
if value is not None:
txt = f"--{key} {value}"
else:
txt = f"--{key}"
cmd_options.append... |
def compare_natural(s1, s2):
""" Compare two strings in natural order (for numbers that are inside).
Args:
s1: First string
s2: Second string
Returns:
integer <0 if s1 < s2, 0 if s1 == s2, >0 if s1 > s2
"""
# Check null strings
if s1 is None:
return 0 if s2 is ... |
def format_time(time, unit, delimiter=False):
"""
A function to format a unit of time, so it is readable when it is
output to Discord.
"""
if time > 0:
if time > 1:
unit += 's'
elapsed = f"{time} {unit}"
if delimiter:
elapsed += ','
return ... |
def _is_mobile_beacon(data, mobile_beacons):
"""Check if we have a mobile beacon."""
return 'beaconUUID' in data and data['name'] in mobile_beacons |
def shrink(line):
"""
>>> shrink('""')
2
>>> shrink('"abc"')
2
>>> shrink('"aaa\\\\"aaa"')
3
>>> shrink('"\\\\x27"')
5
"""
result = 0
index = 0
while index < len(line):
character = line[index]
if character == '"' and (index == 0 or index + 1 == len(lin... |
def rawlines(s):
"""Return a cut-and-pastable string that, when printed, is equivalent
to the input. Use this when there is more than one line in the
string. The string returned is formatted so it can be indented
nicely within tests; in some cases it is wrapped in the dedent
function which has to be... |
def get_resource_bar(avail, total, text='', long=False):
"""Create a long/short progress bar with text overlaid. Formatting handled in css."""
if long:
long_str = ' class=long'
else:
long_str = ''
bar = (f'<div class="progress" data-text="{text}">'
f'<progress{long_str} max="... |
def distinct_brightness(dictionary):
"""Given the brightness dictionary returns the dictionary that has
no items with the same brightness."""
distinct, unique_values = {}, set()
for char, brightness in dictionary.items():
if brightness not in unique_values:
distinct[char] = brightnes... |
def monotonic(a):
"""Check if the first few elements of an array are strictly monotonically decreasing,
while the remaining ones are strictly monotonically increasing.
Parameters
----------
a : Array of elements
Returns
-------
boolean
Return True if the array is m... |
def print_reverse(string):
"""
returns the string in
reverse order recursively
"""
# basecase
if not string:
return ""
else:
return string[-1] + print_reverse(string[:-1]) |
def getNameFromId(obj_id):
"""Returns the name from a wsadmin object id string.
For example, returns PAP_1 from the following id:
PAP_1(cells/ding6Cell01|coregroupbridge.xml#PeerAccessPoint_1157676511879)
Returns the original id string if a left parenthesis is not found.
"""
# print "getNameFr... |
def get_size(w, h, d) -> list:
"""
Write a function that returns the total surface
area and volume of a box as an array: [area, volume]
:param w:
:param h:
:param d:
:return:
"""
volume = w * h * d
# Source: http://www.webmath.com/geo_box.html
area = 2 * (h * w) + 2 * (h * d... |
def is_ascii(s):
"""Determines if a string is encoded in ascii."""
try:
s.encode('ascii')
except UnicodeEncodeError:
return False
return True |
def my_skyline_notelists(notelist):
"""
perform a variation a the skyline algorithm by taking always the highest pitch
at each time.
*notelist* must be in the form returned by misc_tools.load_files
RETURNS :
the list of predicted labels, where 1 is for melody note and 0 is for
accom... |
def inline_code(code: str) -> str:
"""
Covert code to inline code
Args:
code (str) : code to be converted to inline code
Returns:
str: inline code
"""
return f"`{code}`" |
def str_bool(value):
"""
Convert string to boolean.
>>> str_bool("0")
False
>>> str_bool("1")
True
>>> str_bool("true")
True
>>> str_bool("false")
False
"""
if isinstance(value, str):
value = value.strip()
if value.lower() ... |
def isogram(word):
"""Determine if word is isogram.
:param: word - string.
:return: True word is isogram and False otherwise.
"""
word_list = [l for l in word.lower() if l.isalpha()]
return len(set(word_list)) == len(word_list) |
def url_path_join(*pieces): # pragma: no cover
"""Join components of url into a relative url
Use to prevent double slash when joining subpath. This will leave the
initial and final / in place
"""
initial = pieces[0].startswith("/")
final = pieces[-1].endswith("/")
stripped = [s.strip("/") f... |
def absolute_error(x0, x):
"""
Compute absolute error between a value `x` and its expected value `x0`.
:param x0: Expected value.
:param x: Actual value.
:return: Absolute error between the actual and expected value.
:rtype: float
"""
return abs(x0 - x) |
def lookupimage(usbuffer, pts):
"""
determines whether a coordinate (pts) lies with an area defined by
a usbuffer, and returns an image from the buffer if appropriate
:param usbuffer: a dictionary containing bounding box information (x0,y0,
x1,y1) and image data
:returns: True if point in ... |
def patch_channel_map(channel_map, forced_channel_map=None):
"""
For the generated channel map, adds forced identifiers
"""
forced_channel_map = forced_channel_map or {}
patched_channel_map = {}
for channel_initial_name, channel_target_name in channel_map.items():
patched_channel_n... |
def make_html_safe(s):
"""Replace any angled brackets in string s to avoid interfering with HTML attention visualizer."""
s.replace("<", "<")
s.replace(">", ">")
return s |
def get_template_params(template):
"""Parse a CFN template for defined parameters.
Args:
template (dict): Parsed CFN template.
Returns:
dict: Template parameters.
"""
params = {}
if "Parameters" in template:
params = template["Parameters"]
return params |
def simple_moment(w, l):
"""
simple_moment(w, l)
Returns the simple span moment given w and l.
"""
return w * l**2 / 8 |
def GetMaxValueFromScaffold(pos_to_Zscr_d):
"""
Args:
pos_to_Zscr_d: (d)
mean: (float)
SD: (float)
pos_to_Zscr_l: list<value_tuple>
value_tuple: (list) [position (int), ZScr_val (float)]
Returns:
[loc (int), value (int), ZScr_val (float)]
"... |
def make_record(yaml):
"""Create a dictionary object from yaml front matter"""
if 'title' in yaml:
title = yaml['title']
else:
title = "No title"
record = {
'title': title,
'updated': yaml['modified']
}
return record |
def get_next_line(lines, iline):
"""Read the next line from the file. Handles comments."""
try:
line = lines[iline].strip()
except IndexError:
line = None
return iline, line
iline += 1
igap = 0
ngap_max = 10
while len(line) == 0 or line[0] == '#':
try:
... |
def notas(*n, sit=False):
"""
-> Funcao para analisar notas e situacoes de varios alunos.
:param n: uma ou mais notas dos alunos (aceita varias)
:param sit: valor opcional, indicando se deve ou nao adicionar a situacao.
:return: dicionario com varias informacoes sobre a situacao da turma.
"""
... |
def add_tweet_to_list(tweets: list, timeLine: list) -> list:
"""
Adds tweets to the list
:param tweets: Entire list of tweets
:param timeLine: List of tweets from new batch
:return: List of tweets with new tweets added
"""
for tweet in timeLine:
tweets.append(tweet)
return tweets |
def _to_gamma(x):
"""Converts a linear value to sRGB gamma-encoded"""
if x <= 0.0031308:
return x*12.92
else:
return 1.055 * x**(1/2.4) - 0.055 |
def factors(number):
"""Return a list of all factors of number."""
factor_list = []
for i in range(1, number + 1):
if number % i == 0:
factor_list.append(i)
return factor_list |
def block(content, lang=''):
"""Returns a codeblock"""
return f"```{lang}\n{content}```" |
def intersect(list1, list2):
"""
Compute the intersection of two sorted lists.
Returns a new sorted list containing only elements that are in
both list1 and list2.
This function can be iterative.
"""
intersection = []
append = intersection.append
idx1 = 0
idx2 = 0
... |
def cube(num):
"""
Check if a number is cube
:type num: number
:param num: The number to check.
>>> cube(8)
True
"""
x = num**(1 / 3)
x = int(round(x))
return bool(x**3 == num) |
def _GetNamedNodeInfo(names, fn):
"""Calls C{fn} for all names in C{names} and returns a dictionary.
@rtype: None or dict
"""
if names is None:
return None
else:
return map(fn, names) |
def qs_checks_ssl(qs):
"""
By default, we check SSL certificate validity. If ?x-sslVerify=false is found, we don't.
We prepend x- to the option because it's non-standard in MongoDB connection strings.
"""
for check_ssl_value in qs.get("x-sslVerify", []):
if check_ssl_value == "false":
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.