content stringlengths 42 6.51k |
|---|
def checkInputDir(inputDir):
"""
function to set the default value for inputDir
Args:
inputDir: String of the path to the directory where the binaries are stored
Returns:
String representation of the path to the input directory
"""
if inputDir is None:
retu... |
def subnet_id_lookup(session, subnet_domain):
"""Lookup the Id for the Subnet with the given domain name.
Args:
session (Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
subnet_domain (string) : Name of S... |
def _boolean(string_int):
"""returns True or False, for 1 or 0"""
if int(string_int) == 0:
return(False)
elif int(string_int) == 1:
return(True)
else:
raise ValueError("Only 0 or 1 allowed") |
def get_mock_response(obj, request_type, url, headers, params=None, body=None):
"""
:param obj:
:param request_type:
:param url:
:param headers:
:param params:
:param body:
:return:
"""
return {
"content": {
"request_type": request_type.upper(),
"... |
def validate_rule_type(value):
"""Raise exception if rule_type not one of the allowed values."""
if value and value not in ["FORWARD", "SYSTEM", "RECURSIVE"]:
return "satisfy enum value set: [FORWARD, SYSTEM, RECURSIVE]"
return "" |
def ishex(obj):
"""
Tests if the argument is a string representing a valid hexadecimal digit
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(isinstance(obj, str) and
(len(obj) == 1) and
(obj.upper() in '0123456789ABCDEF'))
) |
def o(model: str, **kwargs):
"""Return a simulated model after being parsed."""
root = ("name" in kwargs and kwargs["name"]) or "undefined_name"
return {root: {model: kwargs}} |
def _partition(results):
"""
.. warning::
Internal API.
Splits a list of value results into a two lists of objects for reporting
"""
lhs_vals = []
rhs_vals = []
for result in results:
key, match, lhs, rhs = result
if key:
lhs_vals.append((key, match, lhs))... |
def lcb(fmin, mu, std, kappa=1.96):
"""
Returns lower confidence bound estimates.
fmin (float): (not used): Minimum value of the objective function known
thus far.
mu (numpy array): Mean value of bootstrapped predictions for each y.
std (numpy array): Standard deviation of b... |
def apply_needed_defaults(provided_args, defaults):
"""
@brief Applies defaults to the provided ags list (for keys which do not exist)
@param provided_args The provided arguments
@param defaults The defaults
@return dict
"""
for default in defaults:
... |
def float_int_extraction(number):
"""
Extracting the float and int part from the passed number. The first return
is the part before the decimal point and the rest is the fraction.
"""
_number = str(number)
if "." in _number:
return tuple([int(x) for x in _number.split(".")])
else:
... |
def sign_extend(value: int, orig_size: int, dest_size: int) -> int:
"""
Calculates the sign extension for a provided value and a specified destination size.
:param value: value to be sign extended
:param orig_size: byte width of value
:param dest_size: byte width of value to extend to.
:return:... |
def is_prime_trial_division(n):
"""Determing whether the given integer `n` is prime by trial division.
"""
assert n > 0
if n < 2:
return False
else:
for i in range(2, n):
if i * i > n:
break
elif n % i == 0:
return False
... |
def load_balance(arr):
"""
:type arr: List[int]
:rtype: bool
"""
if len(arr) < 5:
return False
p_sum = [arr[0]] # Calc prefix sum
for i in range(1, len(arr)):
p_sum.append(p_sum[-1]+arr[i])
low = 1
high = len(arr)-1
while low < high:
lower = p_sum[low-... |
def parse_response_float(response):
"""Handles the parsing of a string response representing a float
All responses are sent as strings. In order to convert these strings to
their python equivalent value, you must call a parse_response_* function.
Args:
response (str): response string to parse ... |
def hamming_weight(x):
"""
Per stackoverflow.com/questions/407587/python-set-bits-count-popcount
It is succint and describes exactly what we are doing.
"""
return bin(x).count('1') |
def fitness_fn(turns, energy, isDead):
"""Fitness function that scores based on turns and energy.
Provides a score to a creature, with 3 times the amount of turns
plus the energy, with a bonus for surviving.
Args:
turns: number of turns a creature survived.
energy: amount of energy lef... |
def __charge_to_sdf(charge):
"""Translate RDkit charge to the SDF language.
Args:
charge (int): Numerical atom charge.
Returns:
str: Str representation of a charge in the sdf language
"""
if charge == -3:
return "7"
elif charge == -2:
return "6"
elif charge ... |
def int_division_ceil(i: int, n: int) -> int:
"""
Perform i / n and ceil the result.
Do not perform any floating point operation,
that could result in an overflow with
really big numbers.
:param i: The dividend.
:param n: The divisor.
:return: ceil(i / n)
"""
if i % n == 0:
... |
def names_to_indices(names, series):
"""translate names to indices"""
if isinstance(names, str):
indices = series.index(names)
elif isinstance(names, list) and isinstance(names[0], str):
# translate each row name to index
indices = [series.index(astr) for astr in names]
else:
... |
def is_valid_ip_prefix(ip_prefix):
"""Validates given string as IPv4 prefix.
Args:
ip_prefix (str): string to validate as IPv4 prefix.
Returns:
bool: True if string is valid IPv4 prefix, else False.
"""
if not ip_prefix.isdigit():
return False
ip_prefix_int = int(ip_pr... |
def escape(s):
"""Escapes backslashes and double quotes in strings.
This does NOT add quotes around the string.
"""
return s.replace('\\', '\\\\').replace('"', '\\"') |
def readPrevExecutedRoster(prevRoster_file):
"""Retrieve lifetime stats from config file."""
statstomergeList = []
return statstomergeList |
def _rescale_ratio(auth, nodes):
"""Get scaling denominator for log lists across a sequence of nodes.
:param nodes: Nodes
:return: Max number of logs
"""
if not nodes:
return 0
counts = [
len(node.logs)
for node in nodes
if node.can_view(auth)
]
if count... |
def create_df(dass_words, dfcp_words):
"""
this function creates a dictionary, that keeps track of each occurance of a word in a 'dass' context and 'dfcp' context
it returns this dictionary
"""
dass = {}
dfcp = {}
data = [dass, dfcp]
for listed_values in dass_words: # acces single list... |
def avgCl(lst):
"""return the average RGB of a RGB list"""
c1=c2=c3=0
n = len(lst)
for c in lst:
c1+=c[0]
c2+=c[1]
c3+=c[2]
c1,c2,c3=c1/n,c2/n,c3/n
return [c1,c2,c3] |
def get_uri(path: str, ip: str, port=None) -> str:
"""
Calculates a CoAP URI path.
:param path: the path to the resource (e.g. 'temp')
:param ip: the ip address of the device (e.g. '192.168.1.12')
:param port: [opt] the port of the device (e.g. '5683')
:return: calculated CoAP URI.
"""
... |
def decode_str(obj, encoding="utf-8", errors="strict"):
"""Decode the input byte object to a string.
Parameters
----------
obj : byte object
encoding : string
Default is `utf-8`.
errors : string
Specifies how encoding errors should be handled. Default is `strict`.
"""
re... |
def first_last(list_words):
"""This function returns the first and the last words in dictionary order."""
return print(min(list_words), "&", max(list_words)) |
def compare_dates(
rest_data,
db_data
):
"""compare dates between two data sets
Args:
rest_data (:obj:`list`): data from the internet
db_data (:obj:`list`): data from database
Returns:
(:obj:`list`) mismatched values
"""
rest_dates = []
for row in r... |
def pretty_bytes(byte_value, base_shift=0):
"""Pretty-print the given bytes value.
Args:
byte_value (float): Value
base_shift (int): Base value of byte_value
(0 = bytes, 1 = KiB, 2 = MiB, etc.)
Returns:
str: Pretty-printed byte string such as "1.00 GiB"
Examples:
:... |
def dprint(obj, depth=2, obj_key='', indent=''):
""" for debugging purposes d(ebug)print """
if depth >= 0:
if hasattr(obj, '__dict__') or type(obj) == dict:
if type(obj) == dict:
items = obj.items()
else:
items = obj.__dict__.items()
... |
def _binarize(a, positive):
"""Return values mapped to 1 or 0.
Map values in positive to 1 and others to 0.
"""
return [1 if i in positive else 0 for i in a] |
def _slope(xi, zi, xj, zj):
"""
Slope between the two points only if the pixel is higher
than the other
20150603 Scott Havens
"""
return 0 if zj <= zi else (zj - zi) / (xj - float(xi)) |
def zfsr32(val, n):
"""zero fill shift right for 32 bit integers"""
return (val >> n) if val >= 0 else ((val + 4294967296) >> n) |
def remove_hyphens(isbn):
"""
Remove hyphens from the given string.
"""
result = ""
for letter in isbn:
if letter == "-":
continue
else:
result += letter
return result |
def shouldAvoidDirectory(root, dirsToAvoid):
"""
Given a directory (root, of type string) and a set of directory
paths to avoid (dirsToAvoid, of type set of strings), return a boolean value
describing whether the file is in that directory to avoid.
"""
subPaths = root.split('/')
for i, sub... |
def discount_rewards(rewards, gamma=0.99):
"""Discounts an array of rewarwds, generally used after
an episode ends and before training.
Args:
rewards (:obj:`list` of float): The rewards to be discounted.
gamma (float, optional): Gamma in the reward discount function.
Higher gamm... |
def _GetFloatStringPrecision(floatString):
"""
Gets the floating point precision specified by floatString.
floatString can either contain an actual float in string form, or it can be
a frame placeholder. We simply split the string on the dot (.) and return
the length of the part after the dot, if a... |
def unescape_PTB(s):
"""Return string with Penn treebank escape sequences replaced with text."""
return s.replace("-LRB-", "(").replace("-RRB-", ")").replace("-LSB-", "[").replace("-RSB-", "]").replace("-LCB-", "{").replace("-RCB-", "}").replace('``', '"'). replace("''", '"').replace('\\/', '/') |
def has_needsinfo(labels):
"""Assess if the issue has a needsinfo label."""
needsinfo = False
if 'status-needsinfo' in labels:
needsinfo = True
return needsinfo |
def search_for_duplicates(ALPHABET):
"""
Returns true if the alphabet contains any duplicate
Returns false if all character are unique in the alphabet
"""
AMOUNT_CHAR_OCCURENCES = {}
for CHAR in ALPHABET:
if CHAR not in AMOUNT_CHAR_OCCURENCES:
AMOUNT_CHAR_OCCURENCES[CHAR] = 1
else:
AMOUN... |
def calc_precision(tp: float, fp: float) -> float:
"""
:param tp: true positive or hit
:param fp: false positive or false alarm
:return: precision
"""
if tp + fp != 0:
return tp / (tp + fp)
else:
return 0 |
def test_bit(value, offset):
"""Test a bit at offset position
:param value: value of integer to test
:type value: int
:param offset: bit offset (0 is lsb)
:type offset: int
:returns: value of bit at offset position
:rtype: bool
"""
mask = 1 << offset
return bool(value & mask) |
def generate_room(width: int, height: int) -> list:
"""Generate a rectangular room with given width and height"""
room = []
for i in range(height):
string = ""
for j in range(width):
if i in (0, width - 1):
string += "-"
else:
if j in ... |
def GetEVFlags(debug_arg):
""" Return the EV Flags for the given kernel debug arg value
params:
debug_arg - value from arg member of kernel debug buffer entry
returns:
str - string representing the EV Flag for given input arg value
"""
out_str = ""
if debug_arg &... |
def compare_version(old_map: dict, new_map: dict) -> list:
"""
Compare two dictionaries where the key is a method name and the value
is the class containing the method.
Either of old_map or new_map may be None, which case a message is
printed and no further processing is done. If both dict args are... |
def get_won_faceoffs(list_of_faceoffs, player_id):
"""
Retrieves number of faceoffs in specified list won by player with given id.
"""
return len(list(
filter(lambda d: d['winner']['id'] == player_id, list_of_faceoffs))) |
def turn_clockwise(x):
"""function returning the next compass point in the clockwise direction"""
res = {"N":"E", "E":"S", "S":"W", "W":"N"}
ans = res.get(x, None)
return ans |
def ceil(a, b):
"""
Returns a/b rounded up to nearest integer.
"""
return -(-a//b) |
def noindex_create_dicts(rows, columns):
""" creating dictionary from dictonary table"""
details_dict = {}
for row in rows:
strid = row[0]
inner_dict = dict(zip(columns[0::], row[0::]))
details_dict[strid] = inner_dict
# breakpoint()
return details_dict |
def desmembrar_rota(rota):
"""
Metodo responsavel por pegar metodo http e uri a partir da rota
"""
## separando metodo e uri
_metodo_http, _uri = rota.split("-")
## removendo espacos
_metodo_http = _metodo_http.strip()
_uri = _uri.strip()
return _metodo_http, _uri |
def remove_white_space(list):
"""remove leading or trailing white space from the outer sides of a list and output the list"""
nospace_list = []
for item in list:
stripped = item.strip()
nospace_list.append(stripped)
return nospace_list |
def count_keys(d):
"""Count number of keys in given dict."""
return (0 if not isinstance(d, dict) else
len(d) + sum(count_keys(v) for v in d.values())) |
def distance(a, b):
"""Return the distance between two points (rounded as per TSP datafile)"""
return int(abs(a - b) + 0.5) |
def script_entry(script):
"""
Template tag {% script_entry script %} is used to display a single
script.
Arguments
---------
script: Script object
Returns
-------
A context which maps the script object to program.
"""
return {'script': script} |
def none_tokenizer(sentence):
"""no tokenizer applied: split the sentence with space."""
return sentence.strip().split() |
def get_geocollection(location, default_global_location=False):
"""conservative approach to finding geocollections. Won't guess about ecoinvent or other databases."""
if not location:
if default_global_location:
return "world"
else:
return None
elif isinstance(locatio... |
def integer_to_binary(value):
"""
Convert R or G or B pixel values from integer to binary
INPUT: An integer tuple (e.g. (220))
OUTPUT: A string tuple (e.g. ("00101010"))
"""
return '{0:08b}'.format(value) |
def render_list(inlist):
"""
Convert a list to a string with newlines.
:param inlist: The input list
:type inlist: list
:return: the list converted to a string
"""
# Return empty string to avoid returning unnecessary newlines
if not inlist:
return ''
return '\n{}\n\n'.forma... |
def split_type(line):
"""Splits off the first word in the line and returns both parts in a tuple.
Also eliminates all leading and trailing spaces.
Example:
split_type('ROW ##.##') returns ('ROW', '##.##')
split_type('CLUE (0,1) down: Of or pertaining to the voice (5)') returns
('... |
def crc8(byteData):
"""
Generate 8 bit CRC of supplied string
"""
CRC = 0
# for j in range(0, len(str),2):
for b in byteData:
# char = int(str[j:j+2], 16)
# print(b)
CRC = CRC + b
CRC &= 0xFF
return CRC |
def is_int(in_obj):
"""
Checks if the input represents an integer and returns true iff so
"""
try:
int(in_obj)
return True
except ValueError:
return False |
def avg(X):
"""
Return the average of the list X.
EXAMPLES::
sage: from sage.tests.benchmark import avg
sage: avg([1,2,3])
2.0
"""
s = sum(X,0)
return s/float(len(X)) |
def get_specific_mouse_files(mouse_ids, files):
"""Return sub-list of `files` that contain an id in `mouse_ids`.
"""
return [s for s in files if any(xs in s for xs in mouse_ids)] |
def align_center(background_width: int, foreground_width: int, distance_top: int = 0):
"""Return the tuple necessary for horizontal centering and an optional vertical distance."""
return background_width // 2 - foreground_width // 2, distance_top |
def get_mse_sorted_norm_missing(series1, series2):
"""
sorted and normalized
series will be sorted and normalized
this function will not show any result where the two series are not of same length
"""
mse = 0.0
max_v = max(series1)
if max_v == 0.0:
# difference is equa series2
... |
def compare_files(label, new_files, fname1, fname2, exact):
"""
Performs file comparisons for check.within and check.expect.
Do not use compare_files in your code for CS 116.
"""
try:
f = open(fname1, 'r')
lines1 = list(map(lambda x: x.strip(), f.readlines()))
f.close()
... |
def valid_op_json(op_json):
"""Asserts object is in the form of `[command, {payload}]`."""
assert isinstance(op_json, list), 'json must be a list'
assert len(op_json) == 2, 'json must be a list with 2 elements'
assert isinstance(op_json[0], str), 'json[0] must be a str (command)'
assert isinstance(o... |
def height_gaussian_refactored(initial_velocity, t):
"""Wrote this just to make it purely a function of those two variables"""
return (t + 1) * (2 * initial_velocity - t) / 2 |
def has_params(data, *args):
"""
Validates required parameters against an object.
:param data:
:param args: required parameters
:return:
"""
if data is None:
return False
for a in args:
if not a in data:
return False
v = data[a]
if v is None or... |
def get_game_week(events: list) -> int:
"""Get the gameweek from a events list.
Args:
data_dump (list[dict]): list holding event dicts
Returns:
int: Current gameweek
"""
gw = list(filter(lambda x: x["is_current"] is True, events))
return gw[0]["id"] if gw else 0 |
def gibberish(*args):
"""Concatenate strings in *args together."""
# Initialize an empty string: hodgepodge
hodgepodge = ""
# Concatenate the strings in args
for word in args:
hodgepodge += word
# Return hodgepodge
return hodgepodge |
def collapsed(mol, max_diameter, window_diff, cavity_size):
"""Determines whether a molecule is collapsed or not using the below criteria.
Args:
mol: Molecule to identify whether it is collapsed.
max_diameter: Maximum distance between two atoms in the molecule.
window_diff: Mean differe... |
def HyphenateWord(original_word, max_length, join_str='-'):
"""Breaks a word at max_length with hyphens.
If the word is still too long (i.e., length > 2*max_length), the word will
be split again. The word will be split at word breaks defined by a
switch from lowercase to uppercase. The function will attempt to... |
def clean_column(string):
"""
Description :
This function allow you to transform a string separated by comas in a list of string :
Transforming the string in a list
Removing the duplicated
Removing empty space
Args:
string: string
Returns:
... |
def map_func(x):
"""Execute a function with given arguments, both of them passed as an argument
This function is used to execute map operations on a function taking an
arbitrary number of arguments
Parameters
----------
x : tuple (func, args)
A tuple where the first argument is the fun... |
def calCons2(op, op1, op2):
""" calculate the binary instruction """
temp = None
if op == "+":
temp = int(op1) + int(op2)
elif op == "-":
temp = int(op1) - int(op2)
elif op == "*":
temp = int(op1) * int(op2)
elif op == "/":
temp = int(op1) / int(op2)
else:
... |
def get_resource_name(prefix, project_name):
"""Get a name that can be used for GCE resources."""
# https://cloud.google.com/compute/docs/reference/latest/instanceGroupManagers
max_name_length = 58
project_name = project_name.lower().replace('_', '-')
name = prefix + '-' + project_name
return name[:max_nam... |
def _DiskSizeInBytesToMebibytes(lu, size):
"""Converts a disk size in bytes to mebibytes.
Warns and rounds up if the size isn't an even multiple of 1 MiB.
"""
(mib, remainder) = divmod(size, 1024 * 1024)
if remainder != 0:
lu.LogWarning("Disk size is not an even multiple of 1 MiB; rounding up"
... |
def flatten(xxs):
"""
Flatten a nested list into a single list. Note this only works for lists
nested one deep. For the general case we'd need recursion
"""
return [x for xs in xxs for x in xs] |
def _get_time_axis(time_list, units='hours'):
"""Convert time to sequential format and convert time units."""
time_axis = []
for i in range(len(time_list)):
time_sum = sum(time_list[:i])
if units == 'seconds':
pass
elif units == 'minutes':
time_sum /= 60.0
... |
def get_bytes_from_gb(size_in_gb):
""" Convert size from GB into bytes """
return size_in_gb*(1024*1024*1024) |
def find_corresponding_image(image, imageList):
"""
Find image file best matching image arg in imageList
:param image: image to match
:param imageList: list of images
:return: the name of best matching image
"""
set = [x for x in imageList if image in x]
set.sort()
return set[0] |
def push_left (grid):
"""merge grid values left"""
#push left
for i in range(3):
for row in range(len(grid)):
for column in range(len(grid[row])):
if column > 0:
if grid[row][column-1] == 0:
grid[row][column-1] = grid[row][colum... |
def cycleLength(ch,distance):
"""Function calculates the total length of the path given by a chromosome 'ch'."""
countryNo=len(ch)
total = 0.
for c in range(countryNo):
total += distance[ch[c]][ch[(c+1)%countryNo]]
return total |
def check_messages(msgs, cmd, value=None):
"""Check if specific message is present.
Parameters
----------
cmd : string
Command to check for in bytestring from microscope CAM interface. If
``value`` is falsy, value of received command does not matter.
value : string
Check if ... |
def invert(x,n):
""" Inverts the bits of a positive integer. """
return x ^ ((1 << n) - 1) |
def findChanges(priorVersions, versions) :
"""Determines which tools have new versions.
Keyword arguments:
priorVersions - Python map containing the versions as listed
currently in the existing versions.json.
versions - Python map containing the versions extracted from
the Docker image.... |
def isGoalNode(CurrentNode, goalNode):
"""
Checks if the given present node is the goal node.
Parameters:
goalNode: List
x & y coordinates of the goal node
CurrentNode: List
x & y coordinates of the present node
Returns:
... |
def getattr_keypath(obj, key_path, default=None):
"""
Get attribute by its key path.
>>> class a(object):
... class b(object):
... c = 2
...
>>> getattr_keypath(a, "b.c")
2
Args:
obj: Target object.
key_path: Key path separated by dot.
default: F... |
def module_exists(module_name):
""" Check if a module can be imported. """
try:
__import__(module_name)
except ImportError:
return False
else:
return True |
def _get_kafka_config(config: dict) -> dict:
"""Returns configurations for a consumer instance
Parameters
----------
config: dict
Dictionary of configurations
Returns
----------
kafka_config: dict
Dictionary with configurations for creating an instance of
a secured ... |
def normalize(name):
"""
normalizes the name of the company for comparison by lowercasing, substitution
:param name: the name string
:return: normalized string
"""
if name == "-":
return "company_name_not_available"
name = name.lower().strip().replace("co ", "company").replace("co.",... |
def prefix_lines(lines, prefix):
"""Add the prefix to each of the lines.
>>> prefix_lines(['foo', 'bar'], ' ')
[' foo', ' bar']
>>> prefix_lines('foo\\nbar', ' ')
[' foo', ' bar']
:param list or str lines: A string or a list of strings. If a string is
passed, the string is split ... |
def _validate_negations(base_negations, inbound_actions):
"""
Check that the inbound actions do not contain any of the base negations
"""
if base_negations:
return all(x not in inbound_actions for x in base_negations)
return True |
def pair_sums(total, least):
"""Find all pairs which add up to the provided sum.
Arguments:
total (int): Number to which returned pairs must sum.
least (int): The smallest integer which may be part of a returned pair.
Returns:
set of tuples: Containing pairs of integers adding up t... |
def _get_persistent_binding(app, device_addr):
"""
:return: bool
"""
x = app.__dict__.get('persistent_binding', False)
if x and device_addr is None:
msg = ('In case of `persistent_binding` set to `True`, '
'the `device_addr` should be set and fixed.')
raise... |
def bool_replace(text):
"""In text replace str values 'true' and 'false' by boolean values
Args:
text (str): Incoming text.
Returns:
str: Formatted text.
"""
if text == "false":
return False
elif text == "true":
return True
else:
return text |
def page_not_found(e):
"""404 Page Not Found"""
return 'Sorry, nothing to see here.', 404 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.