content stringlengths 42 6.51k |
|---|
def emptyslot(table):
"""
Checks if the board is playable
returns True if yes or else returns False
"""
rows = len(table)
columns = len(table[0])
for x in range(0, rows):
for y in range(0, columns):
if table[x][y] != '-':
continue
else:
... |
def rivers_with_station(stations):
"""D - Returns a set with the names of the rivers with a monitoring station"""
set_of_rivers = set() #a set contains only unique elements so river names are not repeated
for station in stations:
set_of_rivers.add(station.river) #just adds river name to th... |
def flatten_map(m):
"""Expand a dictionary's items into a flat list
"""
# This is the fastest way to do this in Python
return [item for t in m.items() for item in t] |
def _compress_for_distribute(max_vol, plan, **kwargs):
"""
Combines as many dispenses as can fit within the maximum volume
"""
source = None
new_source = None
a_vol = 0
temp_dispenses = []
new_transfer_plan = []
disposal_vol = kwargs.get('disposal_vol', 0)
max_vol = max_vol - dis... |
def convert_to_int(s):
"""
Filter to convert a string to an int
"""
if s is not None:
return int( s.strip() )
return None |
def combine_hash(lhash: int, rhash: int) -> int:
"""
As boost::hash_combine
"""
lhash ^= rhash + 0x9e3779b9 + (lhash << 6) + (rhash >> 2)
return lhash |
def operation_name(operation):
"""Extract operation name from given string. The name is assumed to be the first
word, followed by ( or whitespace.
"""
return operation.split(" ")[0].strip("(\n") |
def get_human_readable_duration(seconds):
"""Parses seconds into a human readable string."""
if seconds < 0:
return '0 seconds'
seconds = int(seconds)
days, rem = divmod(seconds, 86400)
hours, rem = divmod(rem, 3600)
minutes, seconds = divmod(rem, 60)
if seconds < 1:
secon... |
def get_neighb_hor(curr_i, curr_j, off, w, h):
"""Computes the neighbour with horizontal offset for upper half of the image and
vertical offset for the lower part of the cubemap image."""
if(0 <= curr_i < h):
if(0 <= curr_j < w):
if ((curr_j + off) >= w): return curr_i, curr_j + o... |
def func_dc400d407d514c66a0f00e41e8c416cc(psum):
"""mingain = psum
for i in range(N):
for j in range(i+1):
gain = max(S[j],S[i]-S[j],psum-S[i])
mingain = min(mingain,gain)
return float(psum-mingain)/psum"""
mingain = psum
minpgain = psum
return minpgain |
def sort_list(len_1, len_2, len_3):
"""
Create a list sorting the indexes along three directions:
Input:
len_1 = Number of elements of the array for the first index
len_2 = Number of elements of the array for the second index
len_3 = Number of elements of the array for the third index
... |
def contrasting_text_color(hex_str: str) -> str:
"""Get a contrasting foreground text color for specified background hex color
:param hext_str: A hex string color ('#XXXXXX') for which to determine a black-or-white
foreground color.
:return: '#FFF' or '#000'.
"""
r, g, b = (hex_str[1:3], he... |
def gcd(x, y):
"""
Function to find gcm (greatest common divisor) of two numbers
:param x: first number
:param y: second number
:return: gcd of x and y
"""
while y != 0:
(x, y) = (y, x % y)
return x |
def delete_note(note_list, index_of_note):
"""Deletes a note
@param note_list: a list of NotedItem objects.
@param index_of_note: the index of the item to delete in the note_list.
@return: the edited note_list without the item meant to be deleted.
"""
del note_list[index_of_note]
return note... |
def map2grades(gmap):
"""Convert a mapping {sid -> grade} to a grade string for the GRADES
field in the GRADES table.
"""
return ';'.join([g + '=' + v for g, v in gmap.items()]) |
def generator_function(function, argument_list):
"""Apply a univariate function to a list of arguments in a serial fashion.
Uses Python's built-in generator function syntax to return a generator iterator.
Args:
function: A callable object that accepts one argument
argument_list: An iterabl... |
def cameraEfficiencyResultsFileName(site, telescopeModelName, zenithAngle, label):
"""
Camera efficiency results file name.
Parameters
----------
site: str
South or North.
telescopeModelName: str
LST-1, MST-FlashCam, ...
zenithAngle: float
Zenith angle (deg).
lab... |
def get_filepaths(directory, file_type = "*"):
"""
utils return file paths under directory
Modify filtering file type
:param directory:
:return:
"""
import os
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
if file_type =... |
def get_scan_resource_label(system_type: str) -> str:
"""
Given a system type, returns the label to use in scan output
"""
resource_label_map = {
"redshift_cluster": "Redshift Cluster",
"rds_instance": "RDS Instance",
"rds_cluster": "RDS Cluster",
"okta_application": "Okt... |
def length_of_longest_substring(s: str) -> int:
"""Returns the length of the longest substring without repeating characters.
Args:
s: A string of alphanumeric characters, symbols, or whitespace.
Examples:
>>> length_of_longest_substring("abcabcbb") # "abc"
3
>>> length_of_l... |
def reduc_fn(key, elements, window_size):
""" Receives `window_size` elements """
# Shuffle within each bucket
return elements |
def build_tr_create_module_page_link(region, module_type_id):
"""
Build the direct link to the corresponding Threat Response page in the
given region for creating a module of the given type.
"""
if module_type_id is None:
return 'N/A'
return (
f'https://securex.{region}.securit... |
def countOf(a, b):
"""Return the number of times b occurs in a."""
count = 0
for i in a:
if i == b:
count += 1
return count |
def edgecount(graph):
""" Returns the number of edges in the graph"""
count = 0
for node in graph.keys():
count += len( graph[node] )
return count / 2 |
def _chord(x, y0, y1):
"""
Compute the area of a triangle defined by the origin and two
points, (x,y0) and (x,y1). This is a signed area. If y1 > y0
then the area will be positive, otherwise it will be negative.
"""
return 0.5 * x * (y1 - y0) |
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
"*** YOUR ... |
def make_message(device_id, action, data=''):
"""Returns a formatted string based on actions"""
if data:
return '{{ "device" : "{}", "action":"{}", "data" : "{}" }}'.format(
device_id, action, data)
else:
return '{{ "device" : "{}", "action":"{}" }}'.format(device_id, action) |
def muted_color(color: str, alpha: float = 0.2):
"""Return dict of color, muted_color and muted_alpha
from given color.
Example::
>>> colors = palette()
>>> c = next(colors)
>>> muted_color(c)
{'color': '#1f77b4', 'muted_color': '#1f77b4', 'muted_alpha': 0.2}
>>> fig.line(x,... |
def suma(*args):
"""Sum indefinite number of integers and/or floats.
Parameters
----------
args : ints and/or floats
An indeterminate number of ints and/or floats.
Returns
-------
value : int, float
Returns the result of the operation
"""
value = 0
f... |
def get_batch_size(model_name, value):
"""get_batch_size
These default batch_size values were chosen based on available
GPU RAM (11GB) on GeForce GTX-2080Ti.
"""
if value > 0:
return value
elif 'mobilenet_v2' in model_name:
return 64
elif 'resnet50' in model_name:
re... |
def significance_level(value_to_check, string_to_print):
""" This function attaches ***/**/* to float if float meets conditions.
Designed to be used in ttest(), reg_tab and reg_tab_ext to indicate statistical significance.
:param (float) value_to_check: value to check
:param (str) string_to... |
def _has_name(soup_obj):
"""checks if soup_obj is really a soup object or just a string
If it has a name it is a soup object"""
try:
name = soup_obj.name
if name == None:
return False
return True
except AttributeError:
return False |
def _magnitude_to_marker_size(v_mag):
"""Calculate the size of a matplotlib plot marker representing an object with
a given visual megnitude.
A third-degree polynomial was fit to a few hand-curated examples of
marker sizes for magnitudes, as follows:
>>> x = np.array([-1.44, -0.5, 0., 1., 2., 3., ... |
def getMissingConfiguration(s) :
"""
Given a string, returns all the counts of concecutive missing values in the string, in the form of array.
We also include another value indicating if the edges are same or different
"""
# Initialize variables for computing and storing the values
missing_coun... |
def extract_module( asdl_str ):
"""Return the module name and the module string of the given asdl
string."""
module_name_start = asdl_str.index( 'module' ) + len( 'module' )
module_name_end = asdl_str.index( '{' )
module_str_end = asdl_str.index( '}' )
module_name = asdl_str[ module_name_start : module_nam... |
def json_get_fields(recipe, path=[]):
"""Recusrsively finds fields in script JSON and returns them as a list.
Field has format: { "field":{ "name":"???", "kind":"???", "default":???,
"description":"???" }}
Args:
recipe: (dict) A dictionary representation fo the JSON script.
path: (list) St... |
def text_sanitizer(input) -> str:
"""
input: a string input
Remove all the newlines, whitespaces from string
"""
return input.replace('\n', '').replace('\r', '').strip() |
def findenergy(x, y, vx, vy, mu):
"""Finds the energy at a point in the 4D phase-space."""
r1 = ((x + mu)**2 + y**2) ** 0.5
r2 = ((x - (1 - mu))**2 + y**2) ** 0.5
return 0.5 * (vx**2 + vy**2 - x**2 - y**2) - (1 - mu)/r1 - mu/r2 - 0.5 * (1 - mu) * mu |
def isEdgeLocalizedWithPostProcessingAndLaundering(edge_id, edge, operation):
"""
APPLIES: SELECTION
A 'inclusion rule' that includes AntiForensic, PostProcessing and Laundering Masks.
Excludes Output, TimeAlteration, Transforms, Donors, and DeleteAudioSample.
'Blue' links override.
:param edge_... |
def configlet_get_fact_key(configlet_name, cvp_facts):
"""
Get Configlet ID provided by CVP in facts.
Parameters
----------
configlet_name : string
Name of configlet to look for the key field
cvp_facts : dict
Dictionary from cv_facts
Returns
-------
string
K... |
def parameter_tuple_parser(parameter_tuple, code_list, relative_base):
"""
Accepts parameter_tuple, code_list, and relative_base. Returns parameter for use in intcode operation.
"""
if parameter_tuple[0] == 0:
return code_list[parameter_tuple[1]]
elif parameter_tuple[0] == 1:
retur... |
def _process_stdout_line(line: bytes) -> bytes:
"""Processes a line of stdout from Klepto.
Args:
line: Klepto output line.
Returns:
bytes
"""
if line.startswith(b'INSERT INTO'):
line = line.strip()
line = line.replace(b'INSERT INTO ', b'INSERT INTO public.')
... |
def filter_none_values(dict):
"""Return dictionary with values that are None filtered out"""
return {k: v for (k, v) in dict.items() if v is not None} |
def gNFW_model(r3d_kpc, P0, r_p, slope_a=1.33, slope_b=4.13, slope_c=0.31):
"""
Compute a gNFW model
Parameters
----------
- r3d_kpc (kpc): array of radius
- P0 : normalization
- r_p (kpc): characteristic radius parameter
- sope_a : intermediate slope parameter
- sope_b : outer slop... |
def predict(model, element):
"""A helper function for predict_example."""
return model(element[0]), element[1] |
def source_extension(source):
"""Get file extension for source"""
extensions = {'gamry': '.DTA', 'zplot': '.z'}
return extensions[source] |
def update_nested_dict(main_dict, new_dict):
"""
Update nested dict (only level of nesting) with new values.
Unlike `dict.update`, this assumes that the values of the parent dict are
dicts (or dict-like), so you shouldn't replace the nested dict if it
already exists. Instead you should update... |
def cleanup_property(key):
"""
Cleans the given key by removing whitespace from beginning/end of it and
replacing any other whitespace by the underscore character.
:param key: the key.
:return: a cleaned up key.
:rtype: str
"""
return key.split(':')[0].strip().replace(' ', '_') |
def xor_bytes(a, b):
"""Repeats b if a is longer."""
xored = bytearray()
for i in range(len(a)):
next_byte = a[i] ^ b[i % len(b)]
xored.append(next_byte)
return b''.join(bytes(x) for x in xored) |
def flatten_list_of_tuples(data):
"""
Flatten List of tuples to single iterable
[(1, ), (2, ), (3, )] --> (1, 2, 3)
"""
return list(zip(*data))[0] if data else () |
def hardlims(n):
"""
Symmetrical Hard Limit
"""
if n < 0:
return -1
else:
return 1 |
def recursive_topological_sort(graph, node):
"""perform topo sort on a graph
return an KeyError if some dependency is missing.
:arg graph: a dict of list with dependency name.
:arg node: the node you want calculate the dependencies
"""
result = []
seen = set()
def recursive_helper(nod... |
def is_unknown_dimension(dim):
""" Return true if dim is not a positive integer value. """
if dim is None or not isinstance(dim, int):
return True
return dim <= 0 |
def replace_param_occurrences(string, params):
"""replace occurrences of the tuning params with their current value"""
for k, v in params.items():
string = string.replace(k, str(v))
return string |
def resolve_path(base, path):
""" Resolve (some) relative path. """
if path[0] == "/":
# Absolute path
return path
return base + path |
def removesuffix(string, suffix):
"""Implementation of str.removesuffix() function available for Python versions lower than 3.9."""
if suffix and string.endswith(suffix):
return string[: -len(suffix)]
else:
return string |
def distanc(*args):
"""
Calcs squared euclidean distance between two points represented by n dimensional vector
:param tuple args: points to calc distance from
:return: euclidean distance of points in *args
"""
if len(args) == 1:
raise Exception('Not enough input arguments (expected two... |
def isHttpUrl(url:str) -> bool:
""" Check whether a URL is a http URL.
"""
return url.startswith(('http', 'https')) |
def count_words(phrase):
"""
Returns a dict with count of each word in a phrase
keys are the words and values the count of occurrence.
"""
import re
import string
from collections import Counter
phrase = phrase.lower()
tokens = re.findall(r'[0-9a-zA-Z\']+', phrase)
tokens = [word... |
def get_equally_distributed_datapoints(rps_min, rps_max, increment):
"""Get an equal distribution of measurements for the given configuration."""
return range(rps_min, rps_max, increment) |
def getFeedRate(rpm, chipLoad, numTeeth):
"""
Calculates the feedrate in inches per minute
args:
rpm = spindle speed
chipLoad = chip load (inches per tooth)
numTeeth = number of teeth on tool
"""
feedRate = rpm*chipLoad*numTeeth
return feedRate |
def slashpath_to_localpath(path):
"""
Replace ``/`` in ``path`` with ``os.sep`` .
"""
from os import sep
return path.replace('/', sep) |
def get_pairs(word):
"""Return set of symbol pairs in a word.
word is represented as tuple of symbols (symbols being variable-length strings)
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs |
def _get_cheapest_shipping(shipping_dict):
"""Use the shipping_dict as returned by _get_shipping_choices
to figure the cheapest shipping option."""
least = None
leastcost = None
for key, value in shipping_dict.items():
current = value['cost']
if leastcost is None or current < leastc... |
def getpath(data, path):
"""Traverse nested dictionaries with a 'dotted path'.
x['a.b'] == x['a']['b']
"""
for p in path.split('.'):
data = data[p]
return data |
def sort_bookmarks_list(l):
"""Function to sort list containing dict and Bookmark objects.
All Bookmark objects will appear before dict object. Apart from that
there are not other conditions considered in the 'sorting'.
"""
l_bookmarks = []
l_dicts = []
for item in l:
if type(item... |
def convert_bytes(num):
"""
convert num to idiomatic byte unit
:param num: the input number.
:type num:int
:return: str
>>> convert_bytes(200)
'200.0 bytes'
>>> convert_bytes(6000)
'5.9 KB'
>>> convert_bytes(80000)
'78.1 KB'
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'T... |
def _calculate_valuation_constant(
lulc_cur_year, lulc_fut_year, discount_rate, rate_change,
price_per_metric_ton_of_c):
"""Calculate a net present valuation constant to multiply carbon storage.
Parameters:
lulc_cur_year (int): calendar year in present
lulc_fut_year (int)... |
def sort_dict(dictionary):
"""utility function that from a dictionary returns a list of tuples ordered by dictionary values"""
d = dict(dictionary)
l = []
for key in d.keys():
l.append((d[key], key))
l.sort(reverse=True)
return l |
def _xmlcharref_encode(unicode_data, encoding="ascii"):
"""Emulate Python 2.3's 'xmlcharrefreplace' encoding error handler."""
res = ""
# Step through the unicode_data string one character at a time in
# order to catch unencodable characters:
for char in unicode_data:
try:
char.... |
def index_by_modifier(sequence, modifier, target_index=None):
"""
Create an index of objects in a sequence. The index's key will be provider by the modifier. Values are single
objects, so in case of a duplicate key the latest object will persist.
The modifier is called for each object with that object ... |
def is_tracked_zone(cname, zones):
"""
Does the provided CName belong to a tracked TLD?
"""
for zone in zones:
if cname.endswith("." + zone) or cname == zone:
return True
return False |
def deserialize_signature(signature):
"""Convert a signature from a 32-byte hex string to an r, s pair."""
if len(signature) != 128:
raise ValueError(
'Invalid serialized signature, expected hex string of length 128',
)
return int(signature[:64], 16), int(signature[64:], 16) |
def reverse_coordinate_order(coords):
"""
Takes a tuple of (lat, lng) or (lng, lat) coordinates and reverses their
order.
"""
if len(coords) != 2:
raise ValueError('coordinates must contain exactly 2 points')
return (coords[1], coords[0]) |
def binary_search_iterative(arr: list, el: int) -> int:
"""
Search for an element `el` in the sorted list `arr`.
Return the index of element if found, else -1
"""
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == el:
return mid... |
def str_to_pair_of_lists(_str1, _str2, _sep=','):
"""
Attempts to convert 2 strings containing tokens separated by some _sep to a pair of lists, e.g. "a1,a2,a3", "b1,b2,b3" -> [['a1','a2','a3'],['b1','b2','b3']]
:param _str1: input string #1
:param _str2: input string #2
:param _sep: token separator... |
def gcd(a,b):
"""returns g = gcd(a,b)"""
while b != 0:
q, r = divmod(a,b)
a,b = b, r
return a |
def extension(filename):
"""Return the extension of a filename
Keyword arguments:
filename -- the original filename
"""
# Check if a .something exist in the actual filename
if filename.rfind(".") == -1:
return ""
file_extension = filename[filename.rfind("."):]
return file_extens... |
def parse_filter_args(args):
"""Parses --filter arguments from the command line."""
filter_args = {}
for arg in args:
if arg.endswith(".py"):
filter_args['__script__'] = arg
elif "=" in arg:
key, value = arg.split("=", maxsplit=1)
filter_args[key] = value
... |
def validate_and_clean_char(param, value, allowed, replace=None):
"""
decodes encoded values in the clinical parameters if it is an allowed value
:param param: Clinical parameter
:param value: value of the parameter
:param allowed: list of allowed values in this field
:param replace: list on... |
def _make_unique(l):
"""Check that all values in list are unique and return a pruned and sorted list."""
return sorted(set(l)) |
def eat_porridge(this_sucks, temperature, wtf):
"""
Should we eat the porridge?
Parameters
----------
temperature, porridge : {'too hot', 'too cold', 'just right'}
The temperature of the porridge
output : bool
If we should eat the porridge
"""
if temperature not in {'to... |
def triangleNum(upperLimit):
""" Determines the triangle number up to upperLimit
--param
upperLimit : int
--return
integer
"""
return sum(range(1,upperLimit+1)) |
def constant_schedule_with_warmup(epoch, warmup_epochs=0, lr_start=1e-4, lr_max=1e-3):
""" Create a schedule with a constant learning rate preceded by a warmup
period during which the learning rate increases linearly between {lr_start} and {lr_max}.
"""
if epoch < warmup_epochs:
lr = (lr_max - ... |
def filter_characters(results: list) -> str:
"""Filters unwanted and duplicate characters.
Args:
results: List of top 1 results from inference.
Returns:
Final output string to present to user.
"""
text = ""
for i in range(len(results)):
if results[i] == "$":
... |
def check_file_type(file_path, file_types):
"""
check file type to assert that only file with certain predefined extensions
are checked.
Args:
file_path (str) : path to file.
file_types (list) : list of file extensions to accept.
Returns:
boolean, true if file type is sup... |
def over1000minus1000(num_dict):
"""assumes num_list is a dictionary whose values are numerics
returns a list of numerics, of the values over 1000 of num_dict minus 1000"""
minus_list = []
for key, value in num_dict.items():
mod_num = value - 1000
if mod_num > 0:
minus_list.a... |
def _hostname_matches(cert_pattern, actual_hostname):
"""
:type cert_pattern: `bytes`
:type actual_hostname: `bytes`
:return: `True` if *cert_pattern* matches *actual_hostname*, else `False`.
:rtype: `bool`
"""
if b'*' in cert_pattern:
cert_head, cert_tail = cert_pattern.split(b".",... |
def visual_scaling(img):
""" go from (-1, 1) to (0, 1)"""
return (img + 1) / 2 |
def _manifest(package_name):
"""
Helper function to create an appropriate manifest with a provided package name.
:pram package_name The package name used in the manifest file.
"""
return """
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="{}" >
<uses-sdk
... |
def format_lang_string(lang_str):
"""
This function formats a string to be a parameter in a POST request
to https://detectlanguage.com
"""
lang_str = lang_str.replace(' ', '+')
lang_str = 'q=' + lang_str
return lang_str |
def _getcontextrange(context, config):
"""Return the range of the input context, including the file path.
Return format:
[filepath, line_start, line_end]
"""
file_i = context['_range']['begin']['file']
filepath = config['_files'][file_i]
line_start = context['_range']['begin']['line... |
def hello(name, age, tags=None):
"""
User friendly welcome function.
Uses `name` and `age` to salute user.
This is still same line of documentation.
While this is a new paragraph.
Note that `rst` is sensitive to empty lines and spaces.
Some code Example:
.. code-block:: python
... |
def strip_str(inp):
"""Helper method to strip a string of all non alphanumeric characters.
Args:
inp (str): -
Returns:
str: stripped output
>>> x = 'Test-string123__:'
>>> y = strip_str(x)
>>> y
'teststring123'
"""
return ''.join(ch.lower() for ch in inp if ch.isa... |
def binary_correct(c_row, label_col):
"""
determine if the row is correct or not
:param c_row: row from a dataframe (dict-like)
:param label_col: the colum where the label information resides
:return: boolean if the value is correct or not
>>> test_row = {'task': 'Pneumonia', 'value': 'Pneumonia... |
def per_period_annuity_payment_of_principal(principal, num_payment_periods,
loan_interest_rate, pay_principal_throughout):
"""We want to pay some amount A every period such that we'll pay
off the full principal P after N payment periods, using a loan
interest ra... |
def set_size(x):
"""
Set VARLEN to the appropriate sign
"""
return x["VARLEN"] if x["var_type"] == "INS" else -x["VARLEN"] |
def simple_round(fl, prec):
"""Rounds a fl to prec precision."""
return round(fl, prec) |
def check_hotlinetimings(dump):
"""check to linetimings hotshot-profile datafile."""
signature = "yes".encode()
return True if dump.find(signature) > 0 else False |
def flatten_object(obj, result=None):
"""
Convert an object to a flatten dictionary
example: { "db": { "user": "bar" }} becomes {"db.user": "bar" }
"""
if not result:
result = {}
def _flatten(key_obj, name=''):
if isinstance(key_obj, dict):
for item in key_obj:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.