content stringlengths 42 6.51k |
|---|
def get_acls(plugins):
"""
Given a list of plugins, filter out the `acl` plugin
and return a formatted string
of all the acl consumer group names which are `allowed`
to access the service.
"""
if plugins is None:
return
for i in plugins:
if i["name"] == "acl":
... |
def ispow2(n):
"""Check if n is an integer power of 2."""
return ((n & (n - 1)) == 0) and n != 0 |
def result_string(result):
"""Prints out a human readable string describing the state of play.
Args:
result:
An integer in the range 0 through 4 inclusive. 0 for a white win,
1 for a black win, 2 for a draw, 3 for a game not yet concluded and 4
for an impossible boar... |
def findSubstringInList(substr, the_list):
"""Returns a list containing the indices that a substring was found at.
Uses a generator to quickly find all indices that str appears in.
Args:
substr (str): the sub string to search for.
the_list (List): a list containing the strings to se... |
def create_cart(skus):
"""
Create the cart
:param skus: list of items
:return: A dictionary representing the cart
"""
distinct_skus = list(set(skus))
_cart = {}
for sku in distinct_skus:
_cart[sku] = skus.count(sku)
return _cart |
def get_size_format(b, factor=1024, suffix="B"):
"""
Scale bytes to its proper byte format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if b < factor:
return f"{b:.2f}{unit}{suffix}"
b /... |
def extract_features_basic(label_dict, ind_label_list):
"""
Takes a dictionary of predicted labels and a list of target word and extracts different scores:
maxscorevalue_dict: the maximum score of a label contained in the target list
product_ref_dict: is a product referenced at least once
... |
def email_event_event(event_d):
"""Event part of a new/deleted event email"""
output = "Event:\n"
output += "* eventId: %i\n" % event_d['eventId']
output += "* Rule name: %s\n" % event_d['rulename']
output += "* Severity: %s\n" % event_d['severity']
output += "* attackerAddress: %s\n" % event_d[... |
def check_rgb_match(sample_rgb, target_rgb, precision):
"""Check if a triplet of some sample RGB values can be considered to be the same as a triplet of some target RGB values."""
return abs(sum(sample_rgb) - sum(target_rgb)) <= precision |
def _get_checkpoint_root(checkpoint):
"""Get root directory of checkpoint
:checkpoint: str: Checkpoint filepath
:returns: str: Checkpoint root directory
"""
components = checkpoint.split("/")
root = [c for c in components if not c.lower().startswith('checkpoint')]
return "/".join(root) |
def check(value):
"""This function is problem solving using stack structure."""
cnt = 0
for i in value:
if i == "(":
cnt = cnt+1
else:
if value[cnt-1] == "(":
cnt -= 1
else:
return "NO"
if cnt == 0:
return "YES"
... |
def split_unescape(s, delim, escape='\\', unescape=True):
"""
>>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo$,bar', ',', '$')
['foo,bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=True)
['foo$', 'bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape... |
def _attr_or_key(obj, name, _isinstance=isinstance, _dict=dict, getter=getattr):
"""Attempt to return the attr stored against the specified name from a dict or
from an attribute on an object.
:param obj: The obj to request the attribute from
:param name: The name of the attribute or key on the obj
... |
def format_config_text(config: str) -> str:
"""Delete four spaces at the beginning of each line."""
lines = config.split("\n")
lines = ((line, line[4:])[line.startswith(" ")] for line in lines)
return "\n".join(lines) |
def result_fixture(controller_state, uuid4):
"""Return a server result message."""
return {
"messageId": uuid4,
"result": {"state": controller_state},
"success": True,
"type": "result",
} |
def mimic_next_prune_rate(curr_prune_rate, prune_rate_specs):
""" Mimic the next pruning-rate from the current pruning-rate and the rate from specs. """
return curr_prune_rate + (1 - curr_prune_rate) * prune_rate_specs |
def starSC(m=5):
""" Worst case state complexity for star
:arg m: number of states
:type m: integer
:returns: state complexity
:rtype: integer"""
if m > 1:
return 3 * 2 ** (m - 2)
return 1 |
def get_next_rc_version(current_rc_version, override_tags):
"""
After finding the current rc tag of the image, adds one to it
e.g: 0.10.0-rc1 will returned as 0.10.0-rc2
:param current_rc_version: takes the current rc version of the image as input
:return: returns the next rc version of the image
... |
def get_column_width(column, table):
"""
Get the character width of a column in a table
Parameters
----------
column : int
The column index analyze
table : list of lists of str
The table of rows of strings. For this to be accurate, each
string must only be 1 line long.
... |
def cutoff_tokens(tokens, cutoff):
"""Keep only the tokens with total length <= cutoff."""
ltokens = [len(t) for t in tokens]
length = 0
stokens = []
for token, ln in zip(tokens, ltokens):
if length + ln <= cutoff:
length = length + ln
stokens.append(token)
el... |
def slugify(str_):
"""Remove single quotes, brackets, and newline characters from a string."""
bad_chars = ["'", '[', ']', '\n', '<', '>' , '\\']
for ch in bad_chars:
str_ = str_.replace(ch, '')
return str_ |
def interpolate(color1, color2, mix):
"""Interpolate between color1 and color2."""
r = (color1[0] * (1.0 - mix)) + (color2[0] * mix)
g = (color1[1] * (1.0 - mix)) + (color2[1] * mix)
b = (color1[2] * (1.0 - mix)) + (color2[2] * mix)
return (int(r), int(g), int(b)) |
def ipv4(value):
"""
Return whether or not given value is a valid IP version 4 address.
This validator is based on `WTForms IPAddress validator`_
.. _WTForms IPAddress validator:
https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
Examples::
>>> ipv4('123.0.0.7')
... |
def format_cached(formatstring, *args):
"""calls formatstring.(*args)"""
return formatstring.format(*args) |
def choose_requested_interface(nics, mac):
"""The function will return an interface based on the mac provided"""
for nic in nics:
for nic_name, nic_mac in iter(nic.items()):
if nic_mac == mac:
return nic_name
return None |
def subdivide_rate(rate, periods):
"""
Subdivide a return rate into smaller periods
:param rate:
:param periods:
:return:
"""
return (1 + rate) ** (1 / periods) - 1 |
def _call_return_indices(func, indices, *args, **kwargs):
"""Return indices of func called with *args and **kwargs.
Use with functools.partial to wrap func.
"""
values = func(*args, **kwargs)
return [values[i] for i in indices] |
def naive_hash(key):
"""Additive hashing method."""
hash_val = 0
for char in key:
hash_val += ord(char)
return hash_val |
def ping(argv, params):
"""Check is working."""
text = '@{} Meow!'.format(params.get('user_name', ['CatOps'])[0])
return text |
def generate_zeros_matrix(rows, columns):
"""
Generates a matrix containing only zeros
"""
matrix = [[0 for col in range(columns)] for row in range(rows)]
return matrix |
def ascent_between(elevation1, elevation2):
"""calculates the climb (ascent) between two elevations
@return: climb in meters (float)
"""
if elevation2 > elevation1:
ascent = elevation2 - elevation1
return ascent
else:
return 0.0 |
def cal_accuracy(label_list, classify_res):
""" calculate the accuracy"""
assert(len(label_list) == len(classify_res))
right_count = 0
for i in range(len(label_list)):
if (label_list[i] == classify_res[i]):
right_count += 1
return right_count / float(len(label_list)) |
def _StripTrailingSpaceAndNewline(text):
"""Strip trailing space and possibly a newline from a string."""
text = text.rstrip(u' \t')
if text.endswith(u'\n'):
text = text[:-1]
return text |
def str2binary(s):
"""
Transfer string to binary
:param s: string content to be transformed to binary
:return: binary
"""
return s.encode('utf-8') |
def param(str):
"""
Separates atring of comands and arguments into a
list of strings
"""
commands = []
for item in str.split():
commands.append(item)
return commands |
def recode_str(str_input):
"""
Recodes the input string in the UTF-8 coding.
Args:
str_input: the string to be decoded.
"""
dummy = str(str_input).encode(encoding='ISO-8859-1', errors='strict'). \
decode(encoding='utf-8', errors='ignore')
return dummy |
def _calculate_coord_diff(coord_a, coord_b):
"""Calculate the percentual difference between two coordinates.
It will be the maximum after comparing lon and lat coordinates.
Args:
coord_a, coord_b (list): Given coordinates [lon, lat]
"""
diff_x = abs(float(coord_a[0]) / coord_b[0] - 1)
... |
def _guessImageMime(magic):
"""Peeks at leading bytes in binary object to identify image format."""
if magic.startswith(b"\xff\xd8"):
return "image/jpeg"
elif magic.startswith(b"\x89PNG\r\n\x1a\r"):
return "image/png"
else:
return "image/jpg" |
def process_text(text):
""" process text to remove symbols
- remove symbols: '!'
"""
letters = ['!', '-', '.', ':', '/', ';', '?', '"']
for letter in letters:
text = text.replace(letter, '')
return text |
def get_fixed_or_minimized_key(one_time_crasher_flag):
"""Get the right fixed value."""
return 'NA' if one_time_crasher_flag else '' |
def lte(x, xmx):
"""LTE less-than-or-equal to function
c = lte(x, xmx)
Args:
x ([type]): a quantitity
xmn ([type]): minimum allowed value
Returns:
[type]: = c = constraint variable - 1 if x <= xmx, 0 < c < 1 if x > xmx
"""
if (x <= xmx):... |
def format_kit_descriptor(name, version, iteration):
"""
Returns a properly formatted kit 'descriptor' string in the format
<name>-<version>-<iteration>
"""
return '{0}-{1}-{2}'.format(name, version, iteration) |
def set_pause_on_exceptions(state: str) -> dict:
"""Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or
no exceptions. Initial pause on exceptions state is `none`.
Parameters
----------
state: str
Pause on exceptions mode.
"""
return {... |
def haveCommonEdge(route_1, route_2):
"""
This function receives two routes (python lists) and returns True in
case they share a common edge
"""
def returnOneEdgeAtaTime(route):
"""
This function returns on the fly the successive edges of a route
"""
for i in range(... |
def list_in_str(l, query):
"""
if an element of the list is in query raise exception <!>
"""
for ele in l:
if ele in query:
return True
return False |
def parse_str(x):
"""
Returns the string delimited by two characters.
Example:
`>>> parse_str('[my string]')`
`'my string'`
"""
return x[1:-1] if x is not None else x |
def compute_iou(box1, box2):
"""
Compute IoU between two boxes.
box1: [b1_y1, b1_x1, b1_y2, b1_x2]
box2: [b2_y1, b2_x1, b2_y2, b2_x2]
return: float
"""
# Compute intersection
b1_y1, b1_x1, b1_h, b1_w = box1
b2_y1, b2_x1, b2_h, b2_w = box2
b1_y2, b1_x2 = b1_y1+b1_h, b1... |
def serialize(root_node) -> str:
"""
Serializes the tree into a string of the form Node [LeftTree] [RightTree]
:param root_node: The root of the tree
:return: A string representing the serialized version of the tree
"""
if root_node is None:
return ""
elif root_node.left is None and root_node.right is None:
... |
def col_found(col, names):
"""
For checking, currently unused
"""
for name in names:
if col.endswith(name):
return True
return False |
def LCA(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root or root is p or root is q:
return root
left = LCA(root.left, p, q)
right = LCA(root.right, p, q)
if left and right:
return root
return left if le... |
def selectPivotIndex (ar, left, right, comparator):
"""Select pivot index for ar[left,right] inclusive using comparator."""
midIndex = (left + right)//2
lowIndex = left
if comparator(ar[lowIndex], ar[midIndex]) >= 0:
lowIndex = midIndex
midIndex = left
# when we get here, ... |
def maximum_path_sum(tri):
"""
Returns the maximum total sum from top to bottom of the triangle.
Must be formatted as a list of lists of ints.
"""
tri.reverse()
for i in range(1, len(tri)):
for j in range(len(tri[i])):
tri[i][j] += max(tri[i-1][j], tri[i-1][j+1])
return t... |
def run_batch_align_jobs(job, jobs_dict):
""" todo: clean this up """
rv_dict = {}
for chrom, chrom_job in jobs_dict.items():
rv_dict[chrom] = job.addChild(chrom_job).rv()
return rv_dict |
def get_name_pair(s):
"""Creates space separated words and space separated character in a list
Parameter
---------
s : string
the string of the name to make prediction
Returns
-------
out : list
list includes both space seperated words and space seperated character in... |
def lerp(norm, min, max):
"""
returns a normalized value at offset.
:param norm:
:param min:
:param max:
:return:
"""
return (max - min) * norm + min |
def get_key(channel_data):
"""
Determine the first key in the datastructure, which is a timestamp.
"""
return list(channel_data.keys())[0] |
def DisplayMelody(p):
"""Display a melody"""
ans = ""
i = 0
while (i < len(p)):
note, duration = p[i:(i+2)]
i += 2
ans += "%d,%0.2f " % (note, duration)
ans += "\n"
return ans |
def get_start_and_end_revision(revision_range):
"""Return start and end revision for a regression range."""
try:
revision_range_list = revision_range.split(':')
start_revision = int(revision_range_list[0])
end_revision = int(revision_range_list[1])
except:
return [0, 0]
return [start_revision, ... |
def titleize(phrase):
"""Return phrase in title case (each word capitalized).
>>> titleize('this is awesome')
'This Is Awesome'
>>> titleize('oNLy cAPITALIZe fIRSt')
'Only Capitalize First'
"""
# phrase.lower()
# answer = phrase.split(" ")
# final = ""
# for ... |
def rescale(value, in_min, in_max, out_min, out_max):
"""
Maps an input value in a given range (in_min, in_max)
to an output range (out_min, out_max) and returns it as float.
usage:
>>> rescale(20, 10, 30, 0, 100)
<<< 50.0
"""
in_range = in_max - in_min
out_range = out_max -... |
def get_month_name(month):
"""Returns the name of the month."""
if month == "1" or month == "01":
return "January"
elif month == "2" or month == "02":
return "February"
elif month == "3" or month == "03":
return "March"
elif month == "4" or month == "04":
return "Apri... |
def does_match(val, terms):
"""
>>> does_match('abc', ['a'])
True
>>> does_match('abc', ['d'])
False
"""
for t in terms:
if t.lower() in val.lower():
return True
return False |
def prefix_vaihingen(area_id: int) -> str:
"""Generates the prefix to identify each main tile in the Vaihingen dataset.
:param area_id: integer defining the tile number
:type area_id: int
:return: string named area[area_id]
:rtype: str
"""
return f"area{area_id}" |
def parse_agent_req_file(contents):
"""
Returns a dictionary mapping {check-package-name --> pinned_version} from the
given file contents. We can assume lines are in the form:
datadog-active-directory==1.1.1; sys_platform == 'win32'
"""
catalog = {}
for line in contents.splitlines():
... |
def mean_std(test_list):
"""calculate mean and std
"""
mean = sum(test_list) / len(test_list)
variance = sum([((x - mean) ** 2) for x in test_list]) / len(test_list)
std = variance ** 0.5
return mean, std |
def mode(v):
"""
Return the mode of `v`.
The mode is the list of the most frequently occuring
elements in `v`. If `n` is the most times that any element occurs
in `v`, then the mode is the list of elements of `v` that
occur `n` times. The list is sorted if possible.
.. NOTE::
The ... |
def clean_raw_filename(raw_filename: str) -> str:
"""Cleans a raw DataVault file name.
The function deal with the different specification of file names within the DataVault
platform. While COREREF, CROSSREF, CUSIP, PREMREF, REPLAY and SEDOL files have a
naming convention consisting of the arrangement: ... |
def ext_euclid(a, b):
"""Use extended Euclid algorithm to find gcd of a and b, along with
the coefficients of Bezout's identity, a*x + b*y = gcd(a, b)
The tuple(gcd(a, b), x, y) is returned.
"""
assert a > 0 and b > 0
reverse = b > a
if reverse:
r0, s0, t0 = b, 1, 0
r1, s1, t... |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: ?
Space Complexity: ?
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
now_max = 0
max_ending_he... |
def last_first(author):
"""Parse an author name into last (name) and first."""
if ',' in author:
tokens = author.split(',')
last = tokens[0].strip()
first = ' '.join(tokens[1:]).strip().replace(' ', ', ')
else:
tokens = author.split(' ')
last = tokens[-1].strip()
... |
def fib(n):
"""
Linear time iterative solution.
"""
a, b = 0, 1
for i in range(n):
a, b = b, a+b
return a |
def _flatten(lst, cls):
"""
Helper function -- return a copy of list, with all elements of
type ``cls`` spliced in rather than appended in.
"""
result = []
for elt in lst:
if isinstance(elt, cls):
result.extend(elt)
else:
result.append(elt)
return resu... |
def get_ar(bbox):
"""
:param bbox: top left, right down
:return: aspect ratio
"""
[x1, y1, x2, y2] = bbox
return (y2 - y1) / (x2 - x1) |
def longest_common_prefix(strings):
"""
Find the longest common prefix of a list of 2 or more strings.
Args:
strings (collection): at least 2 strings.
Returns:
string: The longest string that all submitted strings start with.
>>> longest_common_prefix(["abcd", "abce"])
'abc'
... |
def merge_segments(segments, exif=b"", iptc=b""):
"""Merges Exif with APP0 and APP1 manipulations.
"""
if segments[1][0:2] == b"\xff\xe0" and \
segments[2][0:2] == b"\xff\xe1" and \
segments[2][4:10] == b"Exif\x00\x00":
if exif:
segments[2] = exif
segments.pop(1... |
def format_action_row(data):
"""Check value and convert string values to int"""
formatted_data = []
formatted_data.append(data[0])
cost = 0
benefice_percent = 0
if '.' in data[1]:
cost = float(data[1])
else:
cost = int(data[1])
if '.' in data[2]:
benefice_percent = f... |
def make_abba(a, b):
"""Return the result of putting them together in the order abba.
Given two strings, a and b, return the
result of putting them together in the order abba.
e.g. "Hi" and "Bye" returns "HiByeByeHi".
"""
return f"{a}{b*2}{a}" |
def prime(num):
"""
Check if a number is a prime number.
:type num: integer
:param num: The number to check.
>>> prime(7)
True
>>> prime(1)
False
"""
if num in (2, 3):
return True
if num == 1 or num % 2 == 0 or num % 3 == 0:
return False
... |
def wrap_star_digger(item, type_str, data_name='Value'):
"""
code used to extract data from Bing's wrap star
:param item: wrap star obj
:param type_str: target type string
:param data_name: target data label, might be "Entities", "Properties", 'Value'
:return: list of all matched target, arrange... |
def add_two(arg1, arg2):
""" (float, float) -> float
Adds two numbers up
Returns arg1 + arg2
"""
try:
return arg1 + arg2
except TypeError:
return 'Unsupported operation: {0} + {1} '.format(type(arg1), type(arg2)) |
def sort_dict_by_value(inputdict):
"""Sort a dictionary by its values
Args:
inputdict: The dictionary to sort (inputdict)
Returns:
items: The dictionary sorted by value (list)
"""
items = [(v, k) for k, v in inputdict.items()]
items.sort()
items.reverse()
items = [k for... |
def common_string_sequence(s, t):
"""
Find a sequence of characters that occurs, in order, in both s and t.
The sequence need not be contiguous in either.
Doesn't necessarily return the "best" (or longest) such sequence.
"""
common = []
p = 0 # position in string t
for c in s:
... |
def metadata_v1_to_v2(metadata_dict):
""" Convert old version metadata to a new version format. """
if 'version' in metadata_dict and metadata_dict['version'] >= 2:
return metadata_dict
ret = {'version': 2, 'tools': []}
tool = {
'name': 'codechecker',
'version': metadata_dict.g... |
def val_to_list(val):
"""
Convert a single value string or number to a list
:param val:
:return:
"""
if val is not None:
if not isinstance(val, list):
val = [val]
return val |
def app_config(app_config): # pylint: disable=redefined-outer-name
"""Override pytest-invenio app_config-fixture."""
# Enable DOI minting...
app_config["DATACITE_ENABLED"] = True
app_config["DATACITE_USERNAME"] = "INVALID"
app_config["DATACITE_PASSWORD"] = "INVALID"
app_config["DATACITE_PREFIX"... |
def is_requirement(line):
"""
Return True if the requirement line is a package requirement.
Returns:
bool: True if the line is not blank, a comment, a URL, or an included file
"""
return not (
line == ''
or line.startswith('-r')
or line.startswith('#')
or lin... |
def get_diff_dict(d1, d2):
"""
return common dictionary of d1 and d2
"""
diff_keys = set(d2.keys()).difference(set(d1.keys()))
ret = {}
for d in diff_keys: ret[d] = d2[d]
return ret |
def merge_maps(dict1, dict2):
"""merge two word2id or two tag2id"""
for key in dict2.keys():
if key not in dict1:
dict1[key] = len(dict1)
return dict1 |
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item |
def lr_scheduler(epochs):
"""Multiplies learning rate by 0.1 at 100 and 150 epochs, i.e.,
new learning rate = old learning rate * 0.1"""
switch_points = [0, 99, 149]
for i in [2, 1, 0]:
if epochs >= switch_points[i]:
return 0.001 * pow(0.1, i)
#Learning rate is hyperpar... |
def nodeNameFromFullname(fullname):
"""Name of the node from a fullname
The name of the node is the first part of a fullname
Args:
fullname(str): Fullname of a node, connector or port
Returns:
The name of the node, first part of a fullname
"""
n = fullname.split(':')[0]
re... |
def true_negative(y_true, y_pred):
"""
Function to calculate true negatives
:param y_true: list of true values
:param y_pred: list of predicted values
:return: number of true negatives
"""
# intialize the counter
tn = 0
for yt, yp in zip(y_true, y_pred):
if yt == 0 and yp == ... |
def OPEN(parent, r):
"""Open an 'openable' module such as motors, butia.."""
if len(r) == 1:
module = r[0]
return parent.robot.moduleOpen(module)
return '' |
def clean_country(country):
"""Clean country data
Args:
country (str):
Returns:
country starts with capital letter
"""
# start with capial letter
return country.title() |
def is_compressed(ext):
"""Check whether file is compressed or not from the extensions."""
return ext in [".zip", ".gz", ".tar.gz", ".tgz", "bzip2", ".tar.bz2", ".tar"] |
def all_segments(N):
"""
Return (start, end) pairs of indexes that orm segments of tour of length N
"""
return [(start, start + length)
for length in range(N, 2-1, -1)
for start in range(N - length + 1)] |
def _parse_constraint(expr_string):
""" Parses the constraint expression string and returns the lhs string,
the rhs string, and comparator
"""
for comparator in ['==', '>=', '<=', '>', '<', '=']:
parts = expr_string.split(comparator)
if len(parts) > 1:
if comparator == '==':... |
def parse_execution_line_for_python_program(execution_line):
"""
Take a line ex. 'python -m service_framework -s service.py' and parse
it so it can be used by the subprocess module.
execution_line::str
return::[str]
"""
split_line = execution_line.split(' ')
execution_list = []
for ... |
def check_val_of_forecast_settings(param):
"""
Background:
This function is used to check to see if there is a value (submitted from the user in the UI) for a given Prophet Hyper Parameter. If there is no value or false or auto, return that, else we'll return a float of the param given that the value may... |
def get_scalar(default_value, init_value=0.0):
"""Return scalar with a given default/fallback value."""
return_value = init_value
if default_value is None:
return return_value
return_value = default_value
return return_value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.