content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_tasks(
id: Optional[str], name: Optional[str], completed: Optional[bool], comment: Optional[str], limit: Optional[str],
) -> str:
"""
:param id: This optional parameter accepts a string and response is filtered based on this value
:param name: This optional parameter accepts a string and respons... | 5,350,700 |
def f_test_probability(N, p1, Chi2_1, p2, Chi2_2):
"""Return F-Test probability that the simpler model is correct.
e.g. p1 = 5.; //number of PPM parameters
e.g. p2 = p1 + 7.; // number of PPM + orbital parameters
:param N: int
Number of data points
:param p1: int
Number of para... | 5,350,701 |
def validate_user(headers):
"""Validate the user and return the results."""
user_id = headers.get("User", "")
token = headers.get("Authorization", "")
registered = False
if user_id:
valid_user_id = user_id_or_guest(user_id)
registered = valid_user_id > 1
else:
valid_user... | 5,350,702 |
def load_csv_to_journal(batch_info):
"""Take a dict of batch and csv info and load into journal table."""
# Create batch for testing
filename = batch_info['filename']
journal_batch_name = batch_info['journal_batch_name']
journal_batch_description = batch_info['journal_batch_description']
journa... | 5,350,703 |
def _init():
"""
Loads the TRICAL library and sets up the ctypes interface.
Called automatically the first time a Python instance is created.
"""
global _TRICAL
# TODO: search properly
lib = os.path.join(os.path.dirname(__file__), "libTRICAL.dylib")
_TRICAL = cdll.LoadLibrary(lib)
... | 5,350,704 |
def test_paragraph_series_b_cr():
"""
Test case: Paragraph containing a character reference.
was: test_paragraph_extra_14
"""
# Arrange
source_markdown = """fun & joy"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):fun \a&\a\a&\a&\a\a joy:]",
"... | 5,350,705 |
def validate_guid(guid: str) -> bool:
"""Validates that a guid is formatted properly"""
valid_chars = set('0123456789abcdef')
count = 0
for char in guid:
count += 1
if char not in valid_chars or count > 32:
raise ValueError('Invalid GUID format.')
if count != 32:
... | 5,350,706 |
def load_key_string(string, callback=util.passphrase_callback):
# type: (AnyStr, Callable) -> RSA
"""
Load an RSA key pair from a string.
:param string: String containing RSA key pair in PEM format.
:param callback: A Python callable object that is invoked
to acquire a passphr... | 5,350,707 |
def AddSourceToFunction(function, function_ref, update_mask, source_arg,
stage_bucket, messages, service):
"""Add sources to function."""
_CleanOldSourceInfo(function)
if source_arg is None:
source_arg = '.'
source_arg = source_arg or '.'
if source_arg.startswith('gs://'):
upda... | 5,350,708 |
def start_search(keyword):
"""检索入口
:param keyword: 检索关键词"""
search_url = get_full_url(kw=keyword)
headers = {'User-Agent': USER_AGENT}
resp = requests.get(url=search_url, headers=headers)
print('请求响应状态码:', resp.status_code)
print('请求响应内容:', resp.json()) | 5,350,709 |
def load_lbidd(n=5000, observe_counterfactuals=False, return_ites=False,
return_ate=False, return_params_df=False, link='quadratic',
degree_y=None, degree_t=None, n_shared_parents='median', i=0,
dataroot=None,
print_paths=True):
"""
Load the LBIDD data... | 5,350,710 |
def generate_iface_status_html(iface=u'lo', status_txt="UNKNOWN"):
"""Generates the html for interface of given status. Status is UNKNOWN by default."""
status = "UNKNOWN"
valid_status = html_generator.HTML_LABEL_ROLES[0]
if status_txt is not None:
if (str(" DOWN") in str(status_txt)):
status = "DOWN"
valid... | 5,350,711 |
def generalization(self, source, target):
"""Create generalization.
"""
if isprofilemember(source):
return
tok = token('sourcetotargetuuidmapping', False)
containeruuid = tok.uuids[source.__parent__.uuid]
container = target.anchor.node(containeruuid)
general_source = source.refindex[... | 5,350,712 |
def board_size_by_user(board):
"""Get and set board size by user input.
Prompt user to enter number of rows and columns for the board. Default are
the currant board settings (used in user enter nothing).
If no valid inputs are given, user warning will be printed and he will be
prompted for in... | 5,350,713 |
def test__get_dependency_names():
"""Test that the regex in _get_dependency_names() parses a requirements file correctly."""
mock_dependencies: List[str] = [
"# This is a comment",
"#This is another comment",
"--requirement requirements.txt",
"latest-package",
"duplicate-... | 5,350,714 |
def is_a(file_name):
"""
Tests whether a given file_name corresponds to a CRSD file. Returns a reader instance, if so.
Parameters
----------
file_name : str
the file_name to check
Returns
-------
CRSDReader1_0|None
Appropriate `CRSDReader` instance if CRSD file, `None` ... | 5,350,715 |
def Closure(molecules):
"""
Returns the set of the closure of a given list of molecules
"""
newmol=set(molecules)
oldmol=set([])
while newmol:
gen=ReactSets(newmol,newmol)
gen|=ReactSets(newmol,oldmol)
gen|=ReactSets(oldmol,newmol)
oldmol|=newmol
newmol=gen-oldmol
return oldmol | 5,350,716 |
def get_logs(repo_folder):
""" Get the list of logs """
def get_status(path, depth, statuses):
if depth == 3:
for f in os.listdir(path):
if f == STATUS_FILE_NAME:
f = os.path.join(path,f)
statuses.append(f)
else:
for... | 5,350,717 |
def get_celery_task():
"""get celery task, which takes user id as its sole argument"""
global _celery_app
global _celery_task
if _celery_task:
return _celery_task
load_all_fetcher()
_celery_app = Celery('ukfetcher', broker=ukconfig.celery_broker)
_celery_app.conf.update(
CELE... | 5,350,718 |
def plot_keras_activations(activations):
"""Plot keras activation functions.
Args:
activations (list): List of Keras
activation functions
Returns:
[matplotlib figure]
[matplotlib axis]
"""
fig, axs = plt.subplots(1,len(activations),figsize=(3*len(activations),5)... | 5,350,719 |
def check_enum_struct_names():
"""Ensure that none of the items in ENUM_DATA_TYPE_NAMES are in STRUCT_DATA_TYPE_ALIASES"""
from msl.equipment.resources.picotech.picoscope.enums import ENUM_DATA_TYPE_NAMES
from msl.equipment.resources.picotech.picoscope.structs import STRUCT_DATA_TYPE_ALIASES
for item i... | 5,350,720 |
def hog_feature(image, pixel_per_cell=8):
"""
Compute hog feature for a given image.
Important: use the hog function provided by skimage to generate both the
feature vector and the visualization image. **For block normalization, use L1.**
Args:
image: an image with object that we want to d... | 5,350,721 |
def create_parser() -> ArgumentParser:
"""
Helper function parsing the command line options.
"""
parser = ArgumentParser(description="torchx CLI")
subparser = parser.add_subparsers(
title="sub-commands",
description=sub_parser_description,
)
subcmds = {
"describe": ... | 5,350,722 |
def test_contains_always_match():
"""
Contains handler should always match if no rate is specified.
"""
handler = core.ContainsHandler(name='#', func=None)
assert handler.match('Tell me about #foo', channel='bar') | 5,350,723 |
def process_word(word):
"""Remove all punctuation and stem words"""
word = re.sub(regex_punc, '', word)
return stemmer.stem(word) | 5,350,724 |
def no_autoflush(fn):
"""Wrap the decorated function in a no-autoflush block."""
@wraps(fn)
def wrapper(*args, **kwargs):
with db.session.no_autoflush:
return fn(*args, **kwargs)
return wrapper | 5,350,725 |
def print_exception(exc, msg=None):
"""Print the given exception. If a message is given it will be prepended to the exception message with a \n."""
if msg:
exc = "\n".join((msg, str(exc)))
_, _, exc_tb = sys.exc_info()
traceback.print_exception(exc.__class__, exc, exc_tb) | 5,350,726 |
def default_model():
"""Get a path for a default value for the model. Start searching in the
current directory."""
project_root = get_project_root()
models_dir = os.path.join(project_root, "models")
curr_dir = os.getcwd()
if (
os.path.commonprefix([models_dir, curr_dir]) == models_dir
... | 5,350,727 |
def int_to_ip(ip):
"""
Convert a 32-bit integer into IPv4 string format
:param ip: 32-bit integer
:return: IPv4 string equivalent to ip
"""
if type(ip) is str:
return ip
return '.'.join([str((ip >> i) & 0xff) for i in [24, 16, 8, 0]]) | 5,350,728 |
def audit_work_timer_cancel(id):
"""
Cancel timer set.
:param id:
:return:
"""
work = Work.query.get(id)
celery.control.revoke(work.task_id, terminate=True)
work.task_id = None
work.timer = None
db.session.add(work)
db.session.commit()
return redirect(url_for('.audit_wo... | 5,350,729 |
def drawDestCxIds2(ax, layer, fontsize, markersize, partitionColors, xShift):
"""Draw the destination compartment ids into an existing figure.
The displayed ids are interleaved and are grouped into partitions.
:param plt.Axes ax: Matplotlib axes.
:param Layer layer: The layer to visualize.
:param ... | 5,350,730 |
def team_pos_evolution(team_id):
"""
returns the evolution of position
for a team for the season
"""
pos_evo = []
for week in team_played_weeks(team_id):
try:
teams_pos = [x[0] for x in league_table_until_with_teamid(week)]
pos = teams_pos.index(int(team_id)) + 1... | 5,350,731 |
def ifft_method(x, y, interpolate=True):
"""
Perfoms IFFT on data.
Parameters
----------
x: array-like
the x-axis data
y: array-like
the y-axis data
interpolate: bool
if True perform a linear interpolation on dataset before transforming
Returns
-------
x... | 5,350,732 |
def getExecutable():
"""
Returns the executable this session is running from.
:rtype: str
"""
return sys.executable | 5,350,733 |
def run(namespace=None, action_prefix='action_', args=None):
"""Run the script. Participating actions are looked up in the caller's
namespace if no namespace is given, otherwise in the dict provided.
Only items that start with action_prefix are processed as actions. If
you want to use all items in the... | 5,350,734 |
def get_file_with_suffix(d, suffix):
"""
Generate a list of all files present below a given directory.
"""
items = os.listdir(d)
for file in items:
if file.endswith(suffix):
return file.split(suffix)[0]
return None | 5,350,735 |
def app():
"""Create and configure a new app instance for each test."""
# create a temporary file to isolate the database for each test
db_fd, db_path = tempfile.mkstemp()
# warnings.warn(UserWarning("db in file: " + db_path))
# create the app with common test config
app = create_app({"TESTING":... | 5,350,736 |
def force_range(m1, m2):
""" Generate a graph on the relationship between Force and distance between two masses
:param m1: INT: The mass of object 1
:param m2: INT: The mass of object 2
"""
# Generate list of values for range from 100 - 1000 (increments of 50)
r = range(100, 1001, 50)
# Grav... | 5,350,737 |
def PolyMod(f, g):
"""
return f (mod g)
"""
return f % g | 5,350,738 |
def policy_improvement(nS, nA, P, full_state_to_index, g=.75,t=0.05):
"""Iteratively evaluates and improves a policy until an optimal policy is found
or reaches threshold of iterations
Parameters:
nS: number of states
nA: number of actions
P: transitional tuples given state and actio... | 5,350,739 |
def get_train_val_test_data(args):
"""Load the data on rank zero and boradcast number of tokens to all GPUS."""
(train_data, val_data, test_data) = (None, None, None)
# Data loader only on rank 0 of each model parallel group.
if mpu.get_model_parallel_rank() == 0:
data_config = configur... | 5,350,740 |
def user_data_check(data_file):
"""
1 - Check user data file, and if necessary coerce to correct format.
2 - Check for fold calculation errors, and if correct, return data frame
for passing to later functions.
3 - If incorrect fold calculations detected, error message returned.
:param d... | 5,350,741 |
def build_task_inputs_spec(
task_spec: pipeline_spec_pb2.PipelineTaskSpec,
pipeline_params: List[dsl.PipelineParam],
tasks_in_current_dag: List[str],
) -> None:
"""Builds task inputs spec from pipeline params.
Args:
task_spec: The task spec to fill in its inputs spec.
pipeline_params: The list ... | 5,350,742 |
def get_modules(request: HttpRequest) -> JsonResponse:
"""Gets a list of modules for the provided course from the Canvas API based on current user
A module ID has to be provided in order to access the correct course
:param request: The current request as provided by django
:return: A JSONResponse containing either ... | 5,350,743 |
def async_client(async_app):
"""A test async client for the app."""
with async_app.test_client() as testing_client:
yield testing_client | 5,350,744 |
def create_workflow(session, workflow_spec=dict(), result_schema=None):
"""Create a new workflow handle for a given workflow specification. Returns
the workflow identifier.
Parameters
----------
session: sqlalchemy.orm.session.Session
Database session.
workflow_spec: dict, default=dict(... | 5,350,745 |
def scan(graph, connectionInfo, logger, thread):
"""
Get hardware information for each host in a Xen Environment.
Method collects hardware data from XenServer.
Updates will be stored in existing hosts.
Necessary values in the configuration file of this collector module:
- timeout Timeout ... | 5,350,746 |
def poppler_page_get_text_layout(page):
"""
Wrapper of an underlying c-api function not yet exposed by the
python-poppler API.
Returns a list of text rectangles on the pdf `page`
"""
n = c_uint(0)
rects = CRectangle.ptr()
# From python-poppler internals it is known that hash(page) ret... | 5,350,747 |
def get_volume(name: Optional[str] = None,
namespace: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVolumeResult:
"""
## Example Usage
```python
import pulumi
import pulumi_harvester as harvester
ubuntu20_dev_mount_disk = harves... | 5,350,748 |
def both_block_num_missing(record):
"""
Returns true of both block numbers are missing
:param record: dict - The record being evaluated
:return: bool
"""
rpt_block_num = record.get("rpt_block_num", "") or ""
rpt_sec_block_num = record.get("rpt_sec_block_num", "") or ""
# True, if neithe... | 5,350,749 |
def map_keys(func,dic):
"""
TODO:
Test against all types
handle python recursion limit
"""
return {func(k):map_keys(func,v)
if isinstance(v,dict) else v
for k,v in dic.items()} | 5,350,750 |
def jsonize(v):
"""
Convert the discount configuration into a state in which it can be
stored inside the JSON field.
Some information is lost here; f.e. we only store the primary key
of model objects, so you have to remember yourself which objects
are meant by the primary key values.
"""
... | 5,350,751 |
def cli(env, identifier, network_type, speed):
"""Manage network settings."""
public = (network_type == 'public')
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
vsi.change_port_speed(vs_id, public, speed) | 5,350,752 |
def clean_kaggle_movies(movies_df):
"""
Clean the Kaggle movie data with the following steps:
1. Drop duplicate rows
2. Filter out adult videos and drop unnecessary columns
3. Recast columns to appropriate data types
Parameters
----------
movies_df : Pandas dataframe
Kaggle mov... | 5,350,753 |
async def test_get_read_only_properties(hass, hass_ws_client, iolinc_properties_data):
"""Test getting an Insteon device's properties."""
mock_read_only = ExtendedProperty(
"44.44.44", "mock_read_only", bool, is_read_only=True
)
mock_read_only.load(False)
ws_client, devices = await _setup(
... | 5,350,754 |
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up RainMachine sensors based on the old way."""
pass | 5,350,755 |
def generate_trainer(
datafiles: List[str],
labelfiles: List[str],
class_label: str,
batch_size: int,
num_workers: int,
optim_params: Dict[str, Any]={
'optimizer': torch.optim.Adam,
'lr': 0.02,
},
weighted_metrics: bool=None,
scheduler_params: Dict[str, float]=None,
... | 5,350,756 |
def WriteToFileOrStdout(path, content, overwrite=True, binary=False,
private=False):
"""Writes content to the specified file or stdout if path is '-'.
Args:
path: str, The path of the file to write.
content: str, The content to write to the file.
overwrite: bool, Whether or not ... | 5,350,757 |
def make_shift_x0(shift, ndim):
"""
Returns a callable that calculates a shifted origin for each derivative
of an operation derivatives scheme (given by ndim) given a shift object
which can be a None, a float or a tuple with shape equal to ndim
"""
if shift is None:
return lambda s, d, i... | 5,350,758 |
def load_pca_tsne(pca, name, tpmmode=True, logmode=True, exclude=[], cache=True, dir='.'):
"""
Run t-sne using pca result
Parameters
----------
pca : array, shape (n_samples, n_pca)
pca matrix.
name: str
name of pca results
Returns
-------
tsne : array, shape (n_s... | 5,350,759 |
def reconstruct(ctx: click.Context, keyfile: BufferedIOBase, secretfile: Path) -> None:
"""
Reconstruct the secret.
Decrypt re-encrypted shares with the receiver's private key KEYFILE and
join the shares to reconstruct the secret. It is written into SECRETFILE.
"""
pvss = pvss_from_datadir(ctx... | 5,350,760 |
def test_get_part_count_lambda_b(subcategory_id):
"""get_part_count_lambda_b() should return a float value for the base hazard rate on success."""
ATTRIBUTES["subcategory_id"] = subcategory_id
ATTRIBUTES["environment_active_id"] = 3
ATTRIBUTES["construction_id"] = 1
_lambda_b = switch.get_part_count... | 5,350,761 |
def one_zone_numerical(params, ref_coeff, num_molecules=1e-9):
"""Returns one zone reactor exit flow."""
time = np.array(params[0], dtype=float)
gradient = np.array(params[1], dtype=float)
gridpoints = int(params[2])
step_size, area = float(params[3]), float(params[4])
solu = odeint(
... | 5,350,762 |
async def find_pets_by_status(
new: int,
status: List[str] = Query(None, description="Status values that need to be considered for filter"),
token_petstore_auth: TokenModel = Security(get_token_petstore_auth, scopes=["read:pets"]),
) -> List[Pet]:
"""Multiple status values can be provided with comma sep... | 5,350,763 |
def simple_mock_home_fixture():
"""Return a simple mocked connection."""
mock_home = Mock(
spec=AsyncHome,
name="Demo",
devices=[],
groups=[],
location=Mock(),
weather=Mock(
temperature=0.0,
weatherCondition=WeatherCondition.UNKNOWN,
... | 5,350,764 |
def get_all_event_history_links():
"""From ufcstat website finds all completed fights and saves
the http into the current working directory
"""
url = "http://www.ufcstats.com/statistics/events/completed?page=all"
href_collection = get_all_a_tags(url)
#Add all links to list that have event-deta... | 5,350,765 |
def profile_plot(x,z,data,ax,context_label = None,add_labels = False,xlabel = None,xmin = None, xmax=None, max_depth=None):
"""
UnTRIM-like profile plot of salinity
xmin,xmax are the bounds (in km) of the profile
max_depth is the maximum depth, data assumed to be
"""
import matplotlib
impo... | 5,350,766 |
def plot_book_wordbags(urn, wordbags, window=5000, pr = 100):
"""Generate a diagram of wordbags in book """
return plot_sammen_vekst(urn, wordbags, window=window, pr=pr) | 5,350,767 |
def map_line2citem(decompilation_text):
"""
Map decompilation line numbers to citems.
This function allows us to build a relationship between citems in the
ctree and specific lines in the hexrays decompilation text.
Output:
+- line2citem:
| a map keyed with line numbers, holdin... | 5,350,768 |
def from_dict(params, filter_func=None, excludes=[], seeds=[], order=2,
random_seed=None):
"""Generates pair-wise cases from given parameter dictionary."""
if random_seed is None or isinstance(random_seed, int):
return _from_dict(params, filter_func, excludes, seeds, order, random_seed)
... | 5,350,769 |
def ensure_min_topology(*args, **kwargs):
"""
verifies if the current testbed topology satifies the
minimum topology required by test script
:param spec: needed topology specification
:type spec: basestring
:return: True if current topology is good enough else False
:rtype: bool
"""
... | 5,350,770 |
def encode_mode(mode):
"""
JJ2 uses numbers instead of strings, but strings are easier for humans to work with
CANNOT use spaces here, as list server scripts may not expect spaces in modes in port 10057 response
:param mode: Mode number as sent by the client
:return: Mode string
"""
if... | 5,350,771 |
def detect_properties_uri(uri):
"""Detects image properties in the file located in Google Cloud Storage or
on the Web."""
vision_client = vision.Client()
image = vision_client.image(source_uri=uri)
props = image.detect_properties()
print('Properties:')
for color in props.colors:
pr... | 5,350,772 |
def split_array(arr, num_of_splits):
"""split an array into equal pieces"""
# TODO Replace this function with gluon.utils.split_data() once targeting MXNet 1.7
size = arr.shape[0]
if size < num_of_splits:
return [arr[i:i + 1] for i in range(size)]
slice_len, rest = divmod(size, num_of_splits... | 5,350,773 |
def randclust(SC, k):
""" cluster using random """
# generate labels.
labels = np.array([random.randint(0,k-1) for x in range(SC.shape[1])])
# compute the average.
S, cats = avg_cat(labels, SC)
# return it.
return S, labels, cats | 5,350,774 |
def get_domains_by_name(kw, c, adgroup=False):
"""Searches for domains by a text fragment that matches the domain name (not the tld)"""
domains = []
existing = set()
if adgroup:
existing = set(c['adgroups'].find_one({'name': adgroup}, {'sites':1})['sites'])
for domain in c['domains'].find({}, {'domain': 1, '... | 5,350,775 |
def SetCommandFlag(device, engine_ip, engine_port):
"""Set up adb Chrome command line flags
Args:
device: (str) Serial number of device we should use.
engine_ip: (str) Blimp engine IP address.
engine_port: (str) Port on the engine.
"""
cmd_helper.GetCmdStatusAndOutput([
os.path.join(SRC_PATH,... | 5,350,776 |
def read_bbgt(filename):
"""
Read ground truth from bbGt file.
See Piotr's Toolbox for details
"""
boxes = []
with open(filename,"r") as f:
signature = f.readline()
if not signature.startswith("% bbGt version=3"):
raise ValueError("Wrong file signature")
rects... | 5,350,777 |
async def test_aliases_gateway(mocker):
"""Возврат данных в виде списка."""
json = [
{"secid": "OGKB", "isin": "1-02-65105-D"},
{"secid": "OGK2", "isin": "1-02-65105-D"},
{"secid": "OGK2-001D", "isin": "1-02-65105-D-001D"},
]
outer_call = mocker.patch.object(moex.aiomoex, "find_s... | 5,350,778 |
def measure(G, wire, get_cb_delay = False, meas_lut_access = False):
"""Calls HSPICE to obtain the delay of the wire.
Parameters
----------
G : nx.MultiDiGraph
The routing-resource graph.
wire : str
Wire type.
get_cb_delay : Optional[bool], default = False
Determines... | 5,350,779 |
def direction_to(front,list_of_others,what="average") :
"""
Compute the direction vector towards *some other entities*.
Parameters
----------
front : :py:class:`front.Front`
Front to be used as the origin (starting point) of the direction \
vector
list_of_others : list
List... | 5,350,780 |
def live_ferc_db(request):
"""Use the live FERC DB or make a temporary one."""
return request.config.getoption("--live_ferc_db") | 5,350,781 |
async def get_eth_hash(timestamp: int) -> Optional[str]:
"""Fetches next Ethereum blockhash after timestamp from API."""
try:
this_block = w3.eth.get_block("latest")
except Exception as e:
logger.error(f"Unable to retrieve latest block: {e}")
return None
if this_block["timestam... | 5,350,782 |
def resize_opencv(method, *args, **kwargs):
"""Direct arguments to one of the resize functions.
Parameters
----------
method
One among 'crop', 'cover', 'contain', 'width', 'height' or 'thumbnail'
image
Numpy array
size
Size object with desired size
"""
method = f... | 5,350,783 |
def delete_credential(credentials):
"""
Function to delete a Credentials from the credentials list
"""
credentials.delete_credentials() | 5,350,784 |
def extract_url_dataset(dataset,msg_flag=False):
"""
Given a dataset identifier this function extracts the URL for the page where the actual raw data resides.
"""
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
import time
# Ignore SSL cert... | 5,350,785 |
def test__repeated_median(repeated_median):
"""
(1-5)/1 ; (6-5)/2 ; (72-5)/3 => 0.5
(1-5)/-1 ; (6-1)/1 ; (72-1)/3 => 5
(5-6)/-2 ; (1-6)/1 ; (72-6)/2 => 5
(5-72)/-3 ; (1-72)/-2 ; (6-72)/1 => something (23.67)
-------
overall median of (0.5, 5, 5 and something) is (5+5)/2 = 5
"""
... | 5,350,786 |
def test_encrypt_and_decrypt_one(benchmark: BenchmarkFixture) -> None:
"""Benchmark encryption and decryption run together."""
primitives.encrypt = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_encrypt
primitives.decrypt = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_decrypt
def encrypt_and_decr... | 5,350,787 |
def MPI_ITOps(mintime = 5, maxtime = 20, cap = 60):
"""
Returns a costOfLaborValue object suitable to attach to a sim or other event
Time is in hours
"""
timeDist = LogNormalValue(maxtime, mintime, cap)
costDist = LogNormalValue(235, 115, 340)
team = costOfLaborValue("IT I&O Team", timeDist,... | 5,350,788 |
def load_private_wallet(path):
"""
Load a json file with the given path as a private wallet.
"""
d = json.load(open(path))
blob = bytes.fromhex(d["key"])
return BLSPrivateHDKey.from_bytes(blob) | 5,350,789 |
def format_parameters(parameters: str) -> str:
"""
Receives a key:value string and retuns a dictionary string ({"key":"value"}). In the process strips trailing and
leading spaces.
:param parameters: The key-value-list
:return:
"""
if not parameters:
return '{}'
pairs = []
for... | 5,350,790 |
def downvote_question(current_user, question_id):
"""Endpoint to downvote a question"""
error = ""
status = 200
response = {}
question = db.get_single_question(question_id)
if not question:
error = "That question does not exist!"
status = 404
elif db.downvote_question(curre... | 5,350,791 |
def test_updating_with_layer_change(make_napari_viewer, monkeypatch):
"""Test that the dialog text updates when the active layer is changed."""
viewer = make_napari_viewer()
view = viewer.window.qt_viewer
# turn off showing the dialog for test
monkeypatch.setattr(QtAboutKeyBindings, 'show', lambda *... | 5,350,792 |
def get_new_generation(generation: GEN, patterns: PATTERNS) -> GEN:
"""Mutate current generation and get the next one."""
new_generation: GEN = dict()
plant_ids = generation.keys()
min_plant_id = min(plant_ids)
max_plant_id = max(plant_ids)
for i in range(min_plant_id - 2, max_plant_id + 2):
... | 5,350,793 |
def ell2tm(latitude, longitude, longitude_CM, ellipsoid = 'GRS80'):
"""
Convert ellipsoidal coordinates to 3 degree Transversal Mercator
projection coordinates
Input:
latitude: latitude of a point in degrees
longitude: longitude of a point in degrees
longitude_CM: central... | 5,350,794 |
def Format_Phone(Phone):
"""Function to Format a Phone Number into (999)-999 9999)"""
Phone = str(Phone)
return f"({Phone[0:3]}) {Phone[3:6]}-{Phone[6:10]}" | 5,350,795 |
def aStarSearch(problem, heuristic=nullHeuristic):
"""Search the node that has the lowest combined cost and heuristic first."""
"*** YOUR CODE HERE ***"
from sets import Set
startState = problem.getStartState()
if problem.isGoalState(startState):
return []
# Each element in the fringe st... | 5,350,796 |
def _stack_add_equal_dataset_attributes(merged_dataset, datasets, a=None):
"""Helper function for vstack and hstack to find dataset
attributes common to a set of datasets, and at them to the output.
Note:by default this function does nothing because testing for equality
may be messy for certain types; t... | 5,350,797 |
def _rstrip_inplace(array):
"""
Performs an in-place rstrip operation on string arrays. This is necessary
since the built-in `np.char.rstrip` in Numpy does not perform an in-place
calculation.
"""
# The following implementation convert the string to unsigned integers of
# the right length. ... | 5,350,798 |
def compute_fixpoint_0(graph, max_value):
"""
Computes the fixpoint obtained by the symbolic version of the backward algorithm for safety games.
Starts from the antichain of the safe set and works backwards using controllable predecessors.
The maximum value for the counters is a parameter to facilitate ... | 5,350,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.