content stringlengths 42 6.51k |
|---|
def search_tag(resource_info, tag_key):
"""Search tag in tag list by given tag key."""
return next(
(tag["Value"] for tag in resource_info.get("Tags", []) if tag["Key"] == tag_key),
None,
) |
def get_num_of_cycles(buckets, loop_length=False):
"""
Determine the number of cycles to redistribute the buckets until
the same configuration is seen
For a given set of buckets, find the largest (first in list wins
when lengths are the same) and distribute all elements to each of
the successiv... |
def convert_linked_customer_id_to_str(config_data):
"""Parses a config dict's linked_customer_id attr value to a str.
Like many values from YAML it's possible for linked_customer_id to
either be a str or an int. Since we actually run validations on this
value before making requests it's important to pa... |
def my_triangle(my_a, my_b):
"""Calculates the area of a right triangle given the length of the two
shorter sides of the triangle.
Keyword arguments:
my_a (float) -- Length of side a.
my_b (float) -- Length of side b.
Returns:
Float -- Area of the triangle.
"""
return ... |
def get_operating_systems(_os):
"""Helper Script to get operating systems."""
# Update and fix as more OS's converted to folder based tests
if _os:
return [_os]
return ["asa", "ios", "iosxe", "junos", "iosxr", "nxos"]
# operating_system = []
# for folder in os.listdir("./"):
# if ... |
def getLabel(line):
"""
Split by tabs and return the index of "deepTools_group" (or None)
"""
cols = line.strip().split("\t")
if "deepTools_group" in cols:
return cols.index("deepTools_group")
return None |
def simple_caesar_cypher(input_str, shift_mag):
"""
A simple implementation of a Caesar text cypher. Input text is rotated 'shift_mag'
characters to the right.
@param str input_str - Any string. Only lower-case chars 'a'-'z' are shifted.
All other characters are passed unch... |
def parse_wifi_name(wifi_name):
""" Returns wifi name and ssid """
return (wifi_name, wifi_name.split('_', maxsplit=1)[-1]) |
def updateGrade(classes, className, newGrade):
"""Updates grade for className to newGrade.
:param dict classes:
The class information. Format:
classes = {className: {"grade": grade, "credits",
numCredits}}
:param str className:
The class for which the grade is to be ... |
def get_type(element):
"""
Get the type of object as a string
:return: String
"""
return str(element.__class__.__name__).lower() |
def pretty_size(num, divisor=1024.0):
"""Given a number of bytes, determines the correct suffix and formats it
Args:
num (float): The number of bytes
divisor (int, optional): The cutoff before the next suffix is used
Returns:
str: `num` formatted with a suffix
Examples:
... |
def _attr_is_sloted(cls, attr):
"""Check if given attribute is in the given class's __slots__.
Checks recursively from the class to it's bases."""
if not hasattr(cls, '__slots__'):
return False
if attr in cls.__slots__:
return True
for base in cls.__bases__:
if base is not object and _attr_is_sloted(base,... |
def get_yt_video_id(url):
"""Returns Video_ID extracting from the given url of Youtube
Examples of URLs:
Valid:
'http://youtu.be/_lOT2p_FCvA',
'www.youtube.com/watch?v=_lOT2p_FCvA&feature=feedu',
'http://www.youtube.com/embed/_lOT2p_FCvA',
'http://www.youtube.com/v/_lO... |
def _gr_xmax_ ( graph ) :
"""Get maximal x for the points
>>> graph = ...
>>> xmax = graph.xmax ()
"""
xmx = None
np = len(graph)
for ip in range( np ) :
x , y = graph[ip]
if None == xmx or x >= xmx : xmx = x
return xmx |
def js_in_head(request, registry, settings):
"""Should ``<script>`` tags be placed in ``<head>`` or end of ``<body>``.
"""
on_demand_resource_renderer = getattr(request, "on_demand_resource_renderer", None)
if on_demand_resource_renderer and on_demand_resource_renderer.is_js_in_head(request):
r... |
def get_worst_idx(hospital, hospital_prefs, matching):
""" Find the index of the worst resident currently assigned to `hospital`
according to their preferences. """
return max(
[
hospital_prefs[hospital].index(resident)
for resident in hospital_prefs[hospital]
if... |
def YFrequencyMatrixList_to_ZFrequencyMatrixList(y_frequency_matrix_list):
""" Converts Z parameters into Y-parameters. Z-parameters should be in the form
[[f,np.matrix([[Y11,Y12],[Y21,Y22]])],...]
Returns data in the form
[[f,np.matrix([[Z11,Z12],[Z21,Z22]])],...]
inverse of ZFrequencyMatrixList_to... |
def get_catalog_record_preferred_identifier(cr):
"""
Get preferred identifier for a catalog record.
:param cr:
:return:
"""
return cr.get('research_dataset', {}).get('preferred_identifier', '') |
def transform_output_arg(dir: str) -> str:
""" Build youtube-dl '--output' option from directory selected by user. """
dir = dir.strip('"')
return rf'{dir}\%(title)s.%(ext)s' |
def S_get_all_peaks_values(_data_list, _level=0.5, _step=1, _valley=False):
"""
Returns all the peaks available in the data based on height differences between points next to each other as set by level parameter
step defines the number of points to skip for checking the level difference
"""
ds = le... |
def bucket_validate(name):
""" Check for valid bucket name """
if name.startswith("."):
print("Bucket names cannot start with '.'")
return False
if name.endswith("."):
print("Bucket names cannot end with '.'")
return False
if ".." in name:
print("Bucket names cann... |
def nip(string):
"""
Rather than escaping special chars like above, this simply deletes them.
For use in CSS classes and other restrictive environments.
N.B. THIS ALSO PUTS EVERYTHING IN LOWERCASE FOR CONSISTENCY
"""
out = ""
for char in string.lower():
if char.isalnum() or char in ... |
def str_to_pos(string_id):
"""
chrom:start-end
"""
arr1 = string_id.split(":")
arr2 = arr1[1].split("-")
return arr1[0],arr2[0],arr2[1] |
def get_padding_value(padding, kernel):
"""Returns padding value for kernel."""
if padding == "valid":
return 0
elif padding == "same":
return kernel // 2
elif padding == "full":
return kernel - 1
raise ValueError("accepted paddings are 'valid', 'same' or 'full', found " +
pad... |
def strl2f(filename, strl, clobber=True, EOL='\n'):
"""Write a list of strings to the specified filename.
:INPUTS:
filename: string, name of file to write to
strl: list, to be written to specified file.
Returns the filename
:Note: this is only designed for single-depth lists
... |
def merge_dicts(dict1, dict2, keys=None, merge_lists=True):
"""
Recursively merge dict2 into dict1, returning the new dict1.
keys -- keys to care about when checking for conflicts. Other keys take
the value from the second dict.
merge_lists -- whether to ignore conflicts between list values an... |
def PowersetList(initial_set):
"""Computes the power set of a given set.
If the input is null, it returns the empty set.
"""
# The power set of the empty set has one element, the empty set.
result = [[]]
if initial_set:
for x in initial_set:
result.extend([subset + [x] for subset in result])
r... |
def adex_adaptation(V, w, c):
""" Calculate the new adaptation current """
term1 = c['a']*(V-c['E'])
term2 = w
return w + (c['dt']/c['tau'])*(term1-term2) |
def isValidMoney(money):
"""Finds the valid input for the money variable. Makes sure that the only symbol entered is the "$" symbol
Parameters:
money: the user's input from the question
Return:
If the user input value is valid"""
for i in range(0, len(money)):
if (money[i] != '$... |
def score_by_malware_files(event, attributes):
""" Score based on indicators of malware recorded """
score = 0
for attribute in attributes:
if (attribute["category"] == "Payload installation") or (attribute["category"] == "Payload delivery"):
ty = attribute["type"]
if ty == ... |
def divide_round_up(a, b):
"""Calculates a / b rounded up to the nearest integer"""
if a % b < b / 2:
return a // b
else:
return (a // b) + 1 |
def make_list(obj):
"""Returns obj if it is a list, otherwise returns a list of one element
containing obj. This is due to AWS's inconsistent use of JSON arrays."""
if isinstance(obj, list):
return obj
return [obj] |
def generate_md_code_str(code_snippet: str, description: str = 'Snippet') -> str:
"""The normal ``` syntax doesn't seem to get picked up by mdv. It relies on indentation based code blocks.
This one liner accommodates for this by just padding a code block with 4 additional spaces.
Hacky? Sure. Effective? Yu... |
def filter_claims_by_date(claims_data, from_date, to_date):
"""Return claims falling in the specified date range."""
return [
claim for claim in claims_data
if (from_date <= claim.clm_from_dt <= to_date)
] |
def tanh_prime(Y):
"""define the derivative of the activation function tanh"""
return 1 - Y ** 2 |
def php_extensions(extensions, php_version):
"""
Creates a dict containing php extensions links for CLI and FPM variants and their targets
:extensions: dict containing extension name, priority and source path
:php_version: string containing the supported php version
:returns: dict with links and ta... |
def transform_in_list(list_in, list_type=None):
"""Transform a 'String or List' in List"""
if list_in is None:
list_in = ''
if not list_in == list(list_in):
list_in = list_in.split()
if list_type:
print(list_type, list_in)
return list_in |
def extractdata(line):
"""For each line, return the x and y values, check whether there is reference value
and if so return the reference value, otherwise return a reference value of 1 """
newArray = (line.split(',')) #
if len(newArray) == 8:
# convert the strings to floats
xv... |
def merge(LL, RL):
"""
One truth about LL and RL: they are always sorted
"""
c = []
while len(LL) != 0 and len(RL) != 0:
if LL[0] < RL[0]:
c.append(LL.pop(0))
else:
c.append(RL.pop(0))
while len(LL) != 0:
c.append(LL.pop(0))
while len(RL) != ... |
def _reg2float(reg):
"""Converts 32-bit register value to floats in Python.
Parameters
----------
reg: int
A 32-bit register value read from the mailbox.
Returns
-------
float
A float number translated from the register value.
"""
if reg == 0:
... |
def ks(capacity_left, n, weights, values):
"""
capacity_left (int): remaining storage capacity of a bag
n (int): current item position
weights (list): list of item weights
values (list): list of item values
"""
if n == -1 or capacity_left == 0:
# No more items to add... |
def Bin10(x : int):
"""Integer of base 10 to base 2"""
if not int(x) == float(x):
raise TypeError("{} cannot be interperetd as {}".format(type(x),int))
cdiv : int = x
MODS = []
while cdiv != 1:
div,mod = divmod(cdiv,2)
MODS.append(mod)
cdiv = div
MODS.append(cdiv)... |
def calculate_distance(P1, P2):
"""Calculates the distance of given points (1D to infinity-D)."""
if len(P1) != len(P2):
raise ValueError('Different dimension of given points.')
square_sum = 0
for i in range(len(P1)):
square_sum += (P1[i] - P2[i])**2
return square_sum**(1 / 2) |
def read_touchscreen(box, filename, X, Y): # required by Whand
"""
Tests contact with target image on screen (not implemented)
box is 0 to Boxes-1
filename is the file containing the target image (as in display_image) or None
X and Y is where the image is supposed to have been d... |
def fib(n):
"""return the nth number in Fibonacci sequence.
Args:
n: a non-negative integer
Return:
the nth number in Fibonacci sequence, starting with 1, 1, ...
"""
if n <= 0:
return -1
i = j = 1
for _ in range(n - 1):
i, j = j, i + j
return i |
def build_recurrent_mask_inference(num_features, hidden_size, num_layers, bidirectional,
dropout, num_sources, mask_activation, num_audio_channels=1,
rnn_type='lstm', normalization_class='BatchNorm',
normalization_a... |
def _format_basic_message(message):
"""Formats a basic message
Returns a single string with embedded newlines
"""
if message.get('error', False):
resp = '\n- Error: {}'.format(message.get('message'))
else:
resp = '\n- Info: {}'.format(message.get('message'))
return resp |
def RectCurve(type=1, a=1.0, b=0.5, c=1.0):
"""
RectCurve( type=1, a=1.0, b=0.5, c=1.0 )
Create square / rectangle curve
Parameters:
type - select type, Square, Rounded square 1, Rounded square 2
(type=int)
a - a scaling parameter
(type=float)
b - b scal... |
def one_hot_encoding(number):
"""
:param number: label 0 - 9
:return:
"""
assert 0 <= number <= 9
encoding = [0] * 10
encoding[number] = 1
return encoding |
def mean(numbers):
"""Returns the arithmetic mean of a numeric list.
found at: http://mail.python.org/pipermail/python-list/2004-December/253517.html"""
return float(sum(numbers)) / float(len(numbers)) |
def check_available_cell(map, curr_point):
""" checks if a cell was visited before
"""
return map[curr_point[0]][curr_point[1]] not in [1, 4] |
def isleap(year):
"""Return 1 for leap years, 0 for non-leap years."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) |
def add_attributes(rsrc_id, manifest):
"""Add additional attributes to the manifest."""
proid = rsrc_id[0:rsrc_id.find('.')]
environment = 'prod'
updated = {
'proid': proid,
'environment': environment
}
updated.update(manifest)
return updated |
def get_filter_arg_socket_domain(f, arg):
"""Convert integer to socket domain string."""
arg_types = {
0: "AF_UNSPEC",
1: "AF_UNIX",
2: "AF_INET",
3: "AF_IMPLINK",
4: "AF_PUP",
5: "AF_CHAOS",
6: "AF_NS",
7: "AF_ISO",... |
def msg_origin(msg):
""" Mensagem privada ou mensagem de grupo"""
return msg["chat"]["type"] |
def parse_tcp_uri(uri):
"""Parse tcp://<host>:<port>.
"""
try:
if uri[:6] != 'tcp://':
raise ValueError
address, port = uri[6:].split(':')
return address, int(port)
except (ValueError, TypeError):
raise ValueError(
f"Expected URI on the form tc... |
def space_size(bounds):
""" calculates total number of elements in space defined by bounds.
Optimization for small search spaces.
"""
spacesize = 1
for b in bounds.values():
if b['type'] == 'real':
spacesize = spacesize * 1000
elif b['type'] == 'integer':
... |
def lookUpFieldType(field_type):
""" Converts the ArcGIS REST field types to Python Types
Input:
field_type - string - type of field as string
Output:
Python field type as string
"""
if field_type == "esriFieldTypeDate":
return "DATE"
elif field_type == "esr... |
def _reverse(lis, reverse = False):
"""Returns a reversed list if if reverse is true
Args:
lis: The list to be potentially reversed
reverse: If True the provided list will be reversed
"""
if reverse:
return reversed(lis)
else:
return lis |
def getfileextensions(filename):
"""
uses file name to get extension
:param filename:
:return:
"""
a = filename.rfind('.')
return filename[a:] |
def dms2dd(degrees, minutes, seconds):
"""
Convert latitude/longitude of a location that is in degrees, minutes, seconds to decimal degrees
Parameters
----------
degrees : degrees of latitude/longitude
minutes : minutes of latitude/longitude
seconds : seconds of latitude/longitude
Retu... |
def _lookup_response_str(status_code):
"""
Simple function to return a response string for a Ping StatusCode
:param status_code: int:
:return: str: Response string
"""
status_msg = {0: 'Success',
11001: 'Buffer Too Small',
11002: 'Dest Net Unreachable',
... |
def get_neighbours(x_coord, y_coord):
""" Returns 8-point neighbourhood of given point. """
return [(x_coord - 1, y_coord - 1), (x_coord, y_coord - 1), (x_coord + 1, y_coord - 1), \
(x_coord - 1, y_coord), (x_coord + 1, y_coord), \
(x_coord - 1, y_coord + 1), (x_coord, y_coord + 1), (x_... |
def wildcard_is_subset(first, second):
""" Check if first is a subset of second. """
# We ask the question does the first wildcard include packets not in the
# second? If that is ever true for any tbit then it cannot be a subset.
return not (first & ~second) |
def clenshaw_curtis_rule_growth(level):
"""
The number of samples in the 1D Clenshaw-Curtis quadrature rule of a given
level.
Parameters
----------
level : integer
The level of the quadrature rule
Return
------
num_samples_1d : integer
The number of samples in the qu... |
def loadFeaturesFromFile(fileName):
""" Loads features from a file into a list """
features = []
rawData = open(fileName).read().split('\n')
for f in rawData:
#if f.replace(".","").isdigit():
if f != '':
features.append(float(f))
return features |
def _is_page_404(soup: str) -> bool:
"""Checks if a 404 page is returned
Parameters
----------
soup : str
html content from a webpage; will attempt to
coerce to str if not str
Returns
-------
bs4 object
hrml content from bs4 html parser
"""
if 'str' not... |
def required_roles(product, config):
""" Get a list of roles using the specified product from the config dictionary
"""
# First find all roles that use the product. Then check if these roles are started on any node.
expected_roles = []
started_roles = []
for key, value in config.items():
... |
def not_safe_gerone(a, b, c):
"""
Compute triangle area from valid sides lengths
:param float a: first side length
:param float b: second side length
:param float c: third side length
:return: float -- triangle area
>>> not_safe_gerone(3, 4, 5)
6.0
"""
p = (a+b+c)/2
return ... |
def replace_hyphens(olddict):
""" Replaces all hyphens in dict keys with an underscore.
Needed in Django templates to get a value from a dict by key name. """
newdict = {}
for key, value in olddict.items():
key = key.replace('-', '_')
newdict[key] = value
return newdict |
def distro_is_supported(distro_name):
"""
An enforcer of supported distros that can differ from what ceph-deploy
supports.
"""
supported = ['centos', 'redhat', 'ubuntu', 'debian']
if distro_name in supported:
return True
return False |
def ackermann(m, n):
"""
http://en.wikipedia.org/wiki/Ackermann_function
"""
if m == 0:
return n+1
if n == 0:
return ackermann(m-1, 1)
return ackermann(m-1, ackermann(m, n-1)) |
def closest_number(val, num_list):
"""
Return closest element to val in num_list.
Parameters
----------
val: integer, float,
value to find closest element from num_list.
num_list: list,
list from which to find the closest element.
Returns
-------
A element of num_list... |
def task_check() -> dict:
"""Run flake8/mypy/pydocstyle/docs tasks."""
return {
'actions': None,
'task_dep': ['flake8', 'mypy', 'pydocstyle', 'docs']
} |
def get_api_title(specs):
"""Fetch the API title
:param: specs: the JSON smartapi specs
"""
return specs['info']['title'] |
def disable() -> dict:
"""Disables reporting of execution contexts creation."""
return {"method": "Runtime.disable", "params": {}} |
def ordinal_indicator_option(text):
""" Captures the ordinal indicator of a number.
Use this type by annotating your variable with the ``ordinal_indicator``.
**Usage**
::
@then('the user chooses the {option:d}{ordinal:ordinal_indicator}')
def test_method(context, option, ordinal):
... |
def get_markup_type(filename):
"""Return markdown or rest or None"""
extension = filename.rsplit('.', 1)[-1].lower()
mapping = dict(
markdown={'md', 'markdown', 'mdown'},
rest={'rst', 'rest'},
)
for markup_type, possible_extensions in mapping.items():
if extension in possible... |
def collect(iterator, only_no_facts = False):
""" Collects the records of this iterator.
Returns a 3-tuple (list, int, float) with predicates, count and total.
"""
predicates = []
count = 0
total = float(0)
for (pred, time, facts) in iterator:
if facts == 0 or not only_no_facts:... |
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
... |
def monomial_min(*monoms):
"""Returns minimal degree for each variable in a set of monomials.
Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`.
We wish to find out what is the minimal degree for each of `x`, `y`
and `z` variables::
>>> from sympy.polys.monomialtoo... |
def list_to_str(l):
"""
convert a list into a string in a better way than original python
"""
return str(l).replace("'","").replace(",","")[1:-1] |
def read_part_data(stream, size, part_data=b'', progress=None):
"""Read part data of given size from stream."""
while len(part_data) < size:
bytes_to_read = size - len(part_data)
if bytes_to_read > 16384:
bytes_to_read = 16384
data = stream.read(bytes_to_read)
if not ... |
def _rep_time(width: int, depth: int, sweeps: int, reps: int) -> float:
"""Estimated time of executing repetitions.
This includes all incremental costs of executing a repetition and of
sending data back and forth from the electronics.
This is based on an approximate rep rate for "fast" circuits at abo... |
def get_model_by_name(models, name):
"""
Little helper function to return a TinyShield model from a list of models
given the model's name. Returns None if the model was not found.
"""
for model in models:
if model.get("name") == name:
return model
return None |
def html_listbox(name, labels, values):
"""
@param name: Name of html listebox
@param listb: List of values list and option list
@return: Html code to listbox
"""
lines = ""
for idx, label in enumerate(labels):
value = values[idx]
lines = "".join([lines, '\t<op... |
def me2po(RE,Z):
"""
me2po converts geometric altitude to geopotential altitude -- the US
standard atmosphere works in geopotential altitudes, which approximates the
altitude of a pressure surface above the mean sea level.
The reasoning for this is as follows: A change in geometric altitude wil... |
def transform_list_dict(mapping):
"""
Transform a dictionary of lists to a
list of dictionaries.
E.g.
{
'result1': array([10, 11, 12]),
'result2': array([20, 21, 22]),
'result3': array([30, 31, 32])
}
will be transformed to
[
{
'result1': 10,... |
def get_imperatives(tokens):
"""Identify, color and count imparative forms"""
imperatives = [t for t in tokens if t.full_pos.endswith('IMP')]
for t in imperatives:
t.mode_color.append('Imperatives')
return len(imperatives) |
def std_dev(x):
"""Takes a list x of floating point numbers, and computes and returns the corrected sample
standard deviation of the floating point numbers in the list x."""
import statistics
return statistics.stdev(x) |
def isWall(mapObj, x, y):
"""Returns True if the (x, y) position on
the map is a wall, otherwise return False."""
if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):
return False # x and y aren't actually on the map.
elif mapObj[x][y] in ('#', 'x'):
return True # wall is blocki... |
def is_valid_orcid_id(orcid_id: str):
"""adapted from stdnum.iso7064.mod_11_2.checksum()"""
check = 0
for n in orcid_id:
check = (2 * check + int(10 if n == "X" else n)) % 11
return check == 1 |
def parity(x):
"""."""
result = 0
while x:
result ^= 1
x &= x - 1
return result |
def mmedian(lst):
"""
get the median value
"""
sortedLst = sorted(lst)
lstLen = len(lst)
if lstLen==0:
return 0.0
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0 |
def skip_pred(p):
""" probably don't need to use this """
return False
#if 'ConnectionDetermined' in p:
#return True |
def format_album(index, data):
"""Returns a formatted line of text describing the album."""
return "{}. {artist} - {album} - {year} - {rating}\n".format(index, **data) |
def verify_dlg_sdk_proj_env_directory(path):
"""
Drive letter is not allowed to be project environment.
Script checks in parent of 'path': a drive letter like C: doesn't have a parent.
"""
if (path.find(":\\") + 2 >= len(path)): # If no more characters after drive letter (f.e. "C:\\").
retu... |
def _compare(t_sum, t_max, d_sum, d_max, alg='SP-SUM'):
"""
"""
if alg == 'SP-SUM':
return t_sum < d_sum
elif alg == 'SP-MAX':
return t_max < d_max
elif alg == 'SP-COMB':
return (t_max, t_sum) < (d_max, d_sum)
else:
raise Exception("alg not recognized. Should be o... |
def latex_table(rows, caption=None, label=None):
"""Given a list of lists, converts into a LATEX table."""
num_cols = max([len(row) for row in rows])
string_list = ["\\begin{adjustbox}{max width=\\textwidth}\n"]
string_list += ["\\begin{tabular}{|", "c|" * num_cols, "}\n\\hline\n"]
for row in rows... |
def min_filter(seq, default=None):
"""Returns the min value from the sequence."""
if len(seq):
return min(seq)
return default |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.