content stringlengths 42 6.51k |
|---|
def guess(key, values):
"""
Returns guess values for the parameters of this function class based on the input. Used for fitting using this class.
"""
return [min(values), 0.2, 3, 0.2, 3, 115] |
def _is_number(s):
"""
Checks if input is a number
Parameters
----------
s : anything
"""
try:
float(s)
return True
except ValueError:
return False |
def link_local(mac: str) -> str:
"""
Convert MAC to IPv6 Link-local address
:param mac: MAC address
:type mac: str
:return: IPv6 Link-local address
:rtype: str
"""
# only accept MACs separated by a colon
parts = mac.split(":")
# modify parts to match IPv6 value
parts.insert... |
def repeat_range(pattern, nmin, nmax):
""" `m` to `n` repeats of a pattern
:param pattern: an `re` pattern
:type pattern: str
:param nmin: minimum number of repeats
:type nmin: int
:param nmax: maximum number of repeats
:type nmax: int
:rtype: str
"""
return r'(?:{:s}){{{:d},{:... |
def wpa_validation_check(words=[]):
"""
Function to optimise wordlist for wpa cracking
> Removes Duplicates.
> Removes passwords < 8 or > 63 characters in length.
"""
custom_list = list(set(words))
custom_list = [x for x in custom_list if not (len(x) < 8 or len(x) > 63)]
return custom... |
def levenshtein(s1, s2, allow_substring=False):
"""Return the Levenshtein distance between two strings.
The Levenshtein distance (a.k.a "edit difference") is the number of characters that need to be substituted,
inserted or deleted to transform s1 into s2.
Setting the `allow_substring` parameter to Tr... |
def sort_apps(app_list):
"""Sort the apps in the admin site"""
app_idx = dict()
app_names = []
for idx, app in enumerate(app_list):
app_idx[app['app_label']] = idx
app_names.append(app['app_label'])
new_list = []
if 'auth' in app_names:
app_names.remove('auth')
... |
def _shared(permissions, groupid):
"""
Return True if the given permissions object represents shared permissions.
Return False otherwise.
Reduces the client's complex permissions dict to a simple shared boolean.
:param permissions: the permissions dict sent by the client in an
annotation ... |
def mock_getenv_old(name):
"""
a mock for getenv to return the OLD environment variable set with pre-defined values
"""
if name == "DB_TYPE":
return "OLDENV_DB_TYPE"
elif name == "DB_HOST":
return "OLDENV_DB_HOST"
elif name == "DB_NAME":
return "OLDENV_DB_NAME"
elif n... |
def apply_offsets(coordinates, offset_scales):
"""Apply offsets to coordinates
#Arguments
coordinates: List of floats containing coordinates in point form.
offset_scales: List of floats having x and y scales respectively.
#Returns
coordinates: List of floats containing coordinates in... |
def which_path(execname):
"""
Returns either the path to `execname` or None if it can't be found
"""
import subprocess
from warnings import warn
try:
p = subprocess.Popen(['which', execname], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
sout, serr = p.communicate()
if... |
def is_hex(s: str) -> bool:
"""
Hack way to show if a string is a hexadecimal -- works for our purposes here
"""
try:
int(s, 16)
return True
except ValueError:
return False |
def insertion_sort_recursive(integers):
"""Performs insertion sort recursively."""
integers_clone = list(integers)
def helper(arr, n):
if n > 0:
helper(arr, n-1)
while arr[n] < arr[n-1] and n > 0:
arr[n], arr[n-1] = arr[n-1], arr[n]
n -= 1
... |
def pp_num(num):
"""
pretty prints number with commas
"""
s = '%d' % num
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + ','.join(reversed(groups)) |
def str_decrypt(key,enc):
"""malware string decryption algorithm"""
dec =""
for i in enc:
tmp1 = ((key << 13) ^ key) & 0xffffffff
tmp2 = (tmp1 >> 17) ^ tmp1 & 0xffffffff
key = (tmp2 << 5) ^ tmp2 & 0xffffffff
dec += chr(i + key & 0xff)
return dec |
def validate_tweet(tweet: str) -> bool:
"""It validates a tweet.
Args:
tweet (str): The text to tweet.
Raises:
ValueError: Raises if tweet length is more than 280 unicode characters.
Returns:
bool: True if validation holds.
"""
str_len = ((tweet).join(tweet)).count(twe... |
def switch_subgraph_ids(adj_nodes_list, idx_mapping):
"""function maps the node indices to new indices using a mapping
dictionary.
Args:
adj_nodes_list (list): list of list containing the node ids
idx_mapping (dict): node id to mapped node id
Returns:
list: list of list containin... |
def hello(name: str) -> str:
"""
This is module function and it is added to documentation even if it does
not have a docstring. Function signature will be also generated respecting
regular and comment-style type annotations. Let's use PEP 257 format here.
Examples::
# Google-style code blo... |
def is_iterable(obj):
"""Returns true of the object is iterable.
"""
try:
iter(obj)
except Exception:
return False
else:
return True |
def fix_nested_filter(query, parent_key):
"""
Fix the invalid 'filter' in the Elasticsearch queries
Args:
query (dict): An Elasticsearch query
parent_key (any): The parent key
Returns:
dict: An updated Elasticsearch query with filter replaced with query
"""
if isinstanc... |
def _is_json_mimetype(mimetype):
"""Returns 'True' if a given mimetype implies JSON data."""
return any(
[
mimetype == "application/json",
mimetype.startswith("application/") and mimetype.endswith("+json"),
]
) |
def _build_rule(protocol: str, port: int, address: str) -> str:
"""
builds a rule string to use when updating a firewall
Args:
protocol (str): protocol to use
port (int): port to use
address (str): ip address to use
Returns:
str: formatted string to use when sending the... |
def _opSeqToStr(seq, line_labels):
""" Used for creating default string representations. """
if len(seq) == 0: # special case of empty operation sequence (for speed)
if line_labels is None or line_labels == ('*',): return "{}"
else: return "{}@(" + ','.join(map(str, line_labels)) + ")"
def... |
def make_capital(string):
"""Capitalize first letter of a string, leaving the rest of the string as is
Parameters
----------
string : str
The string to capitalize (e.g. 'foRUm').
Returns
-------
str
The capitalized string (e.g. 'FoRUm').
"""
if isinstance(string, s... |
def create_register_form_data(username, password, first_name, last_name, phone_number):
""" Returns a register_form_data (dict) containing username, password, first_name, last_name and phone_number items
Args:
username (dict): [description]
password (dict): [description]
first_name (dic... |
def _func_star(args):
"""
A function and argument expanding helper function.
The first item in args is callable, and the remainder of the items are
used as expanded arguments. This is to make the function header for reduce
the same for the normal and parallel versions. Otherwise, the functions
... |
def treversed(*args, **kwargs):
"""Like reversed, but returns a tuple."""
return tuple(reversed(*args, **kwargs)) |
def delete_nth(order, max_e):
"""
Given a list lst and a number N, create a new list
that contains each number of lst at most N times without
reordering. For example if N = 2, and the input is
[1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next
[1,2] since this would lead to 1 and 2 being in ... |
def mergeDicts(dict1, dict2):
"""Merge two dictionaries."""
res = {**dict1, **dict2}
return res |
def num_classes(name):
""" Gets the number of classes in specified dataset to create models """
if name == 'cifar10':
return 10
elif name == 'cifar100':
return 10
return 0 |
def _is_set(i, k):
"""
:param i: the index of the bit
:param k:
:return:
"""
# not sure this is actually the most efficient implementation
return (1 << i) & k != 0 |
def point_distance_squared(ax: int, ay: int, bx: int, by: int) -> int:
"""Returns distance between two points squared"""
return (ax - bx) ** 2 + (ay - by) ** 2 |
def get_smaller_and_greater(a, b):
"""compare two elements then return smaller and greater"""
if a < b:
return a, b
return b, a |
def configuration_str( configuration, repetition = 1, prefix = '', suffix = '' ):
""" Return a string repr (with a prefix and/or suffix) of the configuration or '' if it's None """
s = ''
if configuration is not None:
s += '[' + ' '.join( configuration ) + ']'
if repetition:
s += '... |
def flatten(l):
"""Flattens a list of lists to the first level.
Given a list containing a mix of scalars and lists,
flattens down to a list of the scalars within the original
list.
Args:
l (list): Input list
Returns:
list: Flattened list.
"""
if not isinstance(l, list... |
def do_almost_nothing(value):
"""Do almost nothing."""
value += 1
return value |
def get_file_from_path(path):
"""
Trims a path string to retrieve the file
:param path:
:return: file
"""
return path.split('/')[-1] |
def judge(expected_out: str, output: str) -> bool:
"""
:param expected_out: expected output value of the task
:param output: output value of the task
:return: **true** or **false** (if output and expected_out are equal or not)
"""
return ' '.join(expected_out.split()) == ' '.join(output.sp... |
def minmax(value, min_value, max_value):
"""Returns `value` or one of the min/max bounds if `value` is not between them.
"""
return min(max(value, min_value), max_value) |
def parse_runtime_duration(runtime):
"""Parse duration information from TransXChange runtime code"""
# Converters
HOUR_IN_SECONDS = 60 * 60
MINUTE_IN_SECONDS = 60
time = 0
runtime = runtime.split("PT")[1]
if 'H' in runtime:
split = runtime.split("H")
time = time + int(spli... |
def get_keys_by_value(dict_of_elements, value_to_find):
"""
Parse a dict() to get keys of elements with a specified value
:param dict_of_elements:
:param value_to_find:
:return:
"""
list_of_keys = list()
list_of_items = dict_of_elements.items()
for item in list_of_items:
if i... |
def get_pipeline(args):
""" Extract pipeline plugin/argument pairs from arguments """
ret_pipeline = list()
str_arguments = " ".join(args)
plugin_groups = str_arguments.split("@@")
if plugin_groups[0] != "":
return ret_pipeline
for plugin_group in plugin_groups[1:]:
plugin_grou... |
def formatSignificantDigits(q,n):
"""
Truncate a float to n significant figures, with exceptions for numbers below 1
Only works for numbers [-100;100]
Arguments:
q : a float
n : desired number of significant figures # Hard-coded
Returns:
Float with only n s.f. and trailing zeros, but... |
def database(result):
"""
Normalize the database name.
"""
if result["database"] == "PDBE":
return "PDB"
return result["database"] |
def get_time_duration_string(seconds):
"""Returns a string with the time converted to reasonable units."""
if seconds >= 1:
val = "{:.3f} s".format(seconds)
elif seconds >= 0.001:
val = "{:.3f} ms".format(seconds * 1000)
elif seconds >= 0.000001:
val = "{:.3f} us".format(seconds ... |
def _get_fs(fs, nyq):
"""
Utility for replacing the argument 'nyq' (with default 1) with 'fs'.
"""
if nyq is None and fs is None:
fs = 2
elif nyq is not None:
if fs is not None:
raise ValueError("Values cannot be given for both 'nyq' and 'fs'.")
fs = 2 * nyq
r... |
def norm_to_pump(dataDict):
""" Divide all curves in dataDict by it's pump power value"""
dataDictNorm = dataDict
norm = []
for key in dataDict:
norm = dataDict[key]['data'][1] / dataDict[key]['Pump Power']#dataDict[key]['Pump Power']
#rest = norm-dataDict[key]['data'][1][1]
data... |
def has_loop(page_list):
"""
Check if a list of page hits contains an adjacent page loop (A >> A >> B) == True.
:param page_list: list of page hits derived from BQ user journey
:return: True if there is a loop
"""
return any(i == j for i, j in zip(page_list, page_list[1:])) |
def _dictify(value):
"""
Converts non-dictionary value to a dictionary with a single
empty-string key mapping to the given value. Or returns the value
itself if it's already a dictionary. This is useful to map values to
row's columns.
"""
return value if isinstance(value, dict) else {'': value} |
def temporal_iou(span_A, span_B):
"""
Calculates the intersection over union of two temporal "bounding boxes"
span_A: (start, end)
span_B: (start, end)
"""
union = min(span_A[0], span_B[0]), max(span_A[1], span_B[1])
inter = max(span_A[0], span_B[0]), min(span_A[1], span_B[1])
if inter... |
def invert_defs_dict(defs_dict):
"""
Inverts the definitions dictionary such that
the instrument program numbers are the keys
and the
Args:
defs_dict (dict):
Returns:
"""
result = {}
for v in defs_dict.values():
for i in v['program_numbers']:
result[i]... |
def union(cluster_a, value_a, cluster_b, value_b):
"""
Returns union of compatible clusters.
Compatibility means that values agree on common
variables.
The set of variable indices is the set union
of variables in both clusters.
"""
cluster_a_list = list(cluster_a)
value_a_list = lis... |
def Dic_Apply_Func(pyfunc,indic):
"""
Purpose: apply a function to value of (key,value) pair in a dictionary and maintain the dic.
Arguments:
pyfunc --> a python function object.
"""
outdic=dict()
for key in indic.keys():
outdic[key]=pyfunc(indic[key])
return outdic |
def euler56(lim=100):
"""Solution for problem 56."""
int_ = {str(d): d for d in range(10)}
maxi = 1
for a in range(2, lim + 1):
p = a
for b in range(2, lim + 1):
p *= a
maxi = max(maxi, sum(int_[d] for d in str(p)))
return maxi |
def dict_to_list(inp_dictionary,replace_spaces=False):
"""Method to convert dictionary to a modified list of strings for input to argparse. Adds a '--' in front of keys
in the dictionary.
Args:
inp_dictionary (dict): Flat dictionary of parameters
replae_spaces (bool): A flag for replace sp... |
def _merge_batch_class(existing, other):
"""
Sets or unions two sets, for building batch class restrictions.
If existing is None, the other set is returned directly
Parameters:
existing: iterable object of the current batch classes
other: iterable object of batch classes to add
Ret... |
def defineParameter(dictionary, key, fallback = None):
"""
Define a variable if it is contained in the dictionary, if not use a fallback
Fairly self explanitory, this gets used a *lot*
"""
if key in dictionary:
parameter = dictionary[key]
else:
parameter = fallback
return parameter |
def _for(x):
""" _for """
ret = x * x
for i in (2, 3):
ret = ret * i
return ret |
def bet_size_sigmoid(w_param, price_div):
"""
Part of SNIPPET 10.4
Calculates the bet size from the price divergence and a regulating coefficient.
Based on a sigmoid function for a bet size algorithm.
:param w_param: (float) Coefficient regulating the width of the bet size function.
:param pric... |
def getMetricSummaries(metrics):
"""This function takes in a list of confusion metric summaries (usually from cross validation over a range of factors) and
then computes the listing of precision, recall, and accuracy for each factor then returns precision, recall and accuracy in that order."""
precision ... |
def bgm_variant_sample(bgm_project, institution, variant):
"""
This item is not pre-posted to database so gene list association with
variant samples can be tested (due to longer process of associating variant
samples with gene lists when the latter is posted after the former).
"""
item = {
... |
def dbsimpson(f, limits: list, d: list):
"""Simpson's 1/3 rule for double integration
int_{ay}^{by} int_{ax}^{bx} f(x,y) dxdy
Args:
f (func): two variable function, must return float or ndarray
limits (list): limits of integration [ax, bx, ay, by]
d (lsit): list of integral resolut... |
def euclidean_distance(list1, list2):
""" Calculate the Euclidean distance between two lists """
# Make sure we're working with lists
# Sorry, no other iterables are permitted
assert isinstance(list1, list)
assert isinstance(list2, list)
dist = 0
# 'zip' is a Python builtin, documented... |
def manhattan(p,q):
"""
Calculate the manhattan distance
"""
same = 0
for i in p:
if i in q:
same += 1
n = same
vals = range(n)
distance = sum(abs(p[i] - q[i]) for i in vals)
return distance |
def safe_int(n):
"""
Safely convert n value to int.
"""
if n is not None:
return int(n)
return n |
def function1(arg1, arg2):
"""This is my doc string of things"""
ans = arg1 + arg2
return ans |
def mult(vector, float):
"""
Multiplies a vector with a float and returns the result in a new vector.
:param vector: List with elements of the vector.
:param float: float is factor.
:return: vector
"""
new_vector = []
for item in vector:
new_vector.append(item * float)
return... |
def sum_up_diagonals(matrix):
"""Given a matrix [square list of lists], return sum of diagonals.
Sum of TL-to-BR diagonal along with BL-to-TR diagonal:
>>> m1 = [
... [1, 2],
... [30, 40],
... ]
>>> sum_up_diagonals(m1)
73
>>> m2 = [
.... |
def get_parallel(a, n):
"""Get input for GNU parallel based on a-list of filenames and n-chunks.
The a-list is split into n-chunks. Offset and amount are provided."""
k, m = divmod(len(a), n)
# chunked = list((a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)))
offset = ' '.join(lis... |
def set_data_format(array_values):
"""
Check and set the corresponding format for each value
:param list[list[str]] array_values: list of values
:return: list[list[str]]: array formatted
"""
formatted_data = []
for d in array_values:
values = []
for v in d:
# Try... |
def query_generator(search="", loc="", org="", created="", sort=""):
""" Generates a query for repository search based on input parameters.
Args:
search: the string that the query is looking for.
loc: where the query should look for the search string.
org: the repository that contains t... |
def var_is_in_cosmic(variant_data):
"""Check if variant is in the COSMIC database
:param variant_data: A GeminiRow for a single variant.
:type variant_data: GeminiRow.
:returns: bool -- True or False.
"""
if variant_data['cosmic_ids'] is not None:
return True
else:
return F... |
def upperize(val):
"""
Converts string to uppercase if it exists
:param val: string to be converted
:return: converted string
"""
if val is not None:
return str(val).upper()
else:
return None |
def moveTo(obj, device):
"""
obj: the python object to move to a device, or to move its contents to a device
device: the compute device to move objects to
"""
if hasattr(obj, "to"):
return obj.to(device)
elif isinstance(obj, list):
return [moveTo(x, device) for x in obj]
elif... |
def topics_from_keys(keys):
"""
Extracts the desired topics from specified keys
:param Keys: List of desired keys
:return: List of topics
"""
topics = set()
for key in keys:
if not key.startswith("/"):
key = "/" + key
chunks = key.split("/")
for i in range... |
def map_to_range(x, in_min, in_max, out_min, out_max, clip=True):
"""
Maps a value from one range to another.
:param x: Input value
:param in_min: Input range minimum
:param in_max: Input range maximum
:param out_min: Output range minimum
:param out_max: Output range maximum
:param clip:... |
def check_dependents(full_name, import_list):
""" Check if we are parent of a loaded / recursed-to module file.
Notes:
Accept full_name if full_name.something is a recursed-to module
Args:
full_name: The full module name
import_list: List of recursed-to modules
Returns:
... |
def _GetVersionIndex(version_str):
"""Returns the version index from ycsb version string.
Args:
version_str: ycsb version string with format '0.<version index>.0'.
Returns:
(int) version index.
"""
return int(version_str.split('.')[1]) |
def generate_repo_name(team_name: str, master_repo_name: str) -> str:
"""Construct a repo name for a team.
Args:
team_name: Name of the associated team.
master_repo_name: Name of the template repository.
"""
return "{}-{}".format(team_name, master_repo_name) |
def fake_update_dict(fake_message_dict):
"""Return a fake Telegram update with message as dict."""
return {
'update_id': 12345,
'message': fake_message_dict
} |
def _build_option_macro_name(config_key: str) -> str:
"""Build macro name for configuration key.
All configuration variables require a macro name, so that they can be referenced in a header file.
Some values in config define "macro_name", some don't. This helps generate consistent macro names
for the l... |
def none_wrapper(value, default=""):
"""
Pure laziness! Sometimes this ends up being nice syntactic sugar for code readability.
"""
return value if value is not None else default |
def degrees_to_decimal(degrees_string):
"""
Convert degrees:minutes:seconds to degrees.decimal
# E.g. '-37:47:10.6' returns -37.78627777777778 Originally: -37.7862648
# '175:19:55.2' returns 175.332 Originally:'175.3319996'
"""
minutes = 0
seconds = 0
degrees_list = degrees_string... |
def getUserRecCalories(weight, height, age, gender):
"""
Parameter:
weight A integer value of user's weight
height A integer value of user's height
age A integer value of user's age
gender A string value contains user's genders
"""
recCal = 0
# The Harris-Benedict Equation
... |
def isCommentCSVLine(Entries):
"""
Treat CSV lines starting with a '#' as a comment.
"""
return len(Entries) > 0 and Entries[0].startswith("#") |
def relative_path(root,path):
"""both [root] and [path] are in split tuple form"""
i = 0
while i < len(path) and path[i]=='..':
i+=1
if i == 0:
return root + path
if i > len(root):
# Relative goes back further than root, return path relative to root
return ('..',)*(i-... |
def to_bool(value):
""" Convert an int (0 or 1) to a boolean.
"""
if value == 1:
return True
else:
return False |
def adjust_relations(relations):
"""Adjust relations to Siren protocol.
:param relations: iterable with relations.
:returns: tuple with string relations.
:raises: :class:ValueError.
"""
try:
return tuple(str(relation) for relation in relations)
except TypeError as error:
rai... |
def binarize_value(df_element: str, patterns: str) -> int:
""" Binarizes searching value.
Parameters:
----------
df_element:
searching source.
patterns:
searching elements.
Returns:
----------
Binarized value.
"""
for pattern in patterns:
if pattern... |
def _reverse(x: int) -> int:
"""
Args:
x: 32-bit signed integer
Returns: x with digits reversed if it would fit in a 32-bit signed integer,
0 otherwise
Examples:
>>> _reverse(123)
321
>>> _reverse(-123)
-321
>>> _reverse(120)
21
... |
def unquote(tag):
# type: (str) -> str
"""Remove namespace from prefixed tag.
See: [Python issue 18304](https://bugs.python.org/issue18304)
Arguments:
tag {str} -- (possibly-)namespaced tag
Returns:
str -- tag name without namespace
"""
return tag.split('}').pop() |
def _arguments_str_from_dictionary(options):
"""
Convert method options passed as a dictionary to a str object
having the form of the method arguments
"""
option_string = ""
for k in options:
if isinstance(options[k], str):
option_string += k+"='"+str(options[k])+"',"
... |
def get_ad_sublist(adlist, names):
"""
Select a sublist of AstroData instances from the input list using a list
of filename strings. Any filenames that don't exist in the AstroData list
are just ignored.
"""
outlist = []
for ad in adlist:
if ad.filename in names:
outlist.... |
def euclideanDistance(loc1, loc2):
"""
Return the Euclidean distance between two locations, where the locations
are pairs of numbers (e.g., (3, 5)).
"""
# BEGIN_YOUR_CODE (our solution is 1 line of code, but don't worry if you deviate from this)
return ((loc1[0]-loc2[0])**2+(loc1[1]-loc2[1])**2)... |
def get_tail(raw_url_str):
"""
Get final end chunk of https url- such as, for given "https:1/2/3/4.pdf,
returns "4.pdf"
:param raw_url_str: str
:return: str
"""
split = raw_url_str.split('/')
if len(split[-1]) == 0: # in case there's appended '/' at the end of url
return split[-... |
def for_loop(function, argument_list):
"""Apply a multivariate function to a list of arguments in a serial fashion.
Uses Python's built-in for statement.
Args:
function: A callable object that accepts more than one argument
argument_list: An iterable object of input argument collections
... |
def fill_buckets(buckets, all_jobs):
"""Split jobs in buckets according their memory consumption."""
if 0 in buckets.keys(): # do not split it
buckets[0] = list(all_jobs.keys())
return buckets
# buckets were set
memlims = sorted(buckets.keys())
prev_lim = 0
for memlim in memlims... |
def digital_root(number: int) -> int:
"""Sums all numbers in given number.
Args:
number (int): given number
Examples:
>>> assert digital_root(166) == 4
"""
while number > 10:
number = sum(map(int, str(number)))
return number |
def rivers_with_station(stations):
"""
Returns a set of all rivers monitored by 'stations'.
'stations' is a list of 'MonitoringStation' objects. Documentation for object 'station' can be found
by importing 'station' from 'floodsystem' and typing 'help(station.MonitoringStation)'
"""
river_lis... |
def replace_module_suffix(state_dict, suffix, replace_with=""):
"""
Replace suffixes in a state_dict
Needed when loading DDP or classy vision models
"""
state_dict = {
(key.replace(suffix, replace_with, 1) if key.startswith(suffix) else key): val
for (key, val) in state_dict.items()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.