content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def box2start_row_col(box_num):
"""
Converts the box number to the corresponding row and column number of the square in the upper left corner of the box
:param box_num: Int
:return: len(2) tuple
[0] start_row_num: Int
[1] start_col_num: Int
"""
start_row_num = 3 * (bo... | 5,310,600 |
def safe_referrer(meta, default):
"""
Takes request.META and a default URL. Returns HTTP_REFERER if it's safe
to use and set, and the default URL otherwise.
The default URL can be a model with get_absolute_url defined, a urlname
or a regular URL
"""
referrer = meta.get('HTTP_REFERER')
i... | 5,310,601 |
def create_title(chunk, sep, tags):
"""Helper function to allow doconce jupyterbook to automatically assign titles in the TOC
If a chunk of text starts with the section specified in sep, lift it up
to a chapter section. This allows doconce jupyterbook to automatically use the
section's text as title in... | 5,310,602 |
def mock_user_data():
"""Mock os module."""
with patch('hass_nabucasa.Cloud.write_user_info') as writer:
yield writer | 5,310,603 |
def get_marker_size(number):
"""Same scaling as for year 2019. Produces more overlap between circles.
But this was considered OK, since it does reflect the reality.
"""
return SCALE * (5 * math.sqrt(number) + 5) | 5,310,604 |
def parseCmd():
"""Parse command line arguments
Returns:
dictionary: Dictionary with arguments
"""
parser = argparse.ArgumentParser(description='')
parser.add_argument('--arg', type=str,
help='')
return parser.parse_args() | 5,310,605 |
def graph2VSM(graph):
"""
Convert an igraph model to a VSM
Params:
model the igraph model
"""
terms = graph.vcount()
edges = graph.ecount()
# Use sparse matrix representation if the matrix is less than 50% full
# if terms > 20000 and graph.density() < 0.5:
if graph.density()... | 5,310,606 |
def cached(prefix=None, ext="xz"):
"""
Decorator to cache the function result in a file depending on args.
The function source is stored together with the data, source code mismatch
triggers recomputation. Note that *all* whitespace is ignored (incl. in strings)
and this heuristic ignores any other... | 5,310,607 |
def which(program, env=None):
""" returns the path to an executable or None if it can't be found"""
if env is None:
env = os.environ.copy()
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_ex... | 5,310,608 |
def recurrence_memo(initial):
"""
Memo decorator for sequences defined by recurrence
See usage examples e.g. in the specfun/combinatorial module
"""
cache = initial
def decorator(f):
@wraps(f)
def g(n):
L = len(cache)
if n <= L - 1:
retur... | 5,310,609 |
def _print_header(data):
"""
Create vcf header to make
a valid vcf.
"""
print("##fileformat=VCFv4.2", file=STDOUT)
print("##source=seqbuster2.3", file=STDOUT)
print("##reference=mirbase", file=STDOUT)
for pos in data:
print("##contig=<ID=%s>" % pos["chrom"], file=STDOUT)
prin... | 5,310,610 |
def update_project_users(post_data=None, slug=None):
"""update-project-users (Site admins/Site managers/Project managers only)
Usage: update-project-users [-h] <slug> (<username> <access_mode>) ...
Arguments:
<slug> The slug of the project
<username> The username of the user to either update o... | 5,310,611 |
def cancel_update_stack(StackName=None, ClientRequestToken=None):
"""
Cancels an update on the specified stack. If the call completes successfully, the stack rolls back the update and reverts to the previous stack configuration.
See also: AWS API Documentation
Examples
This example cancels an u... | 5,310,612 |
def satisfiesNodeConstraint(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, _: DebugContext) -> bool:
""" `5.4.1 Semantics <http://shex.io/shex-semantics/#node-constraint-semantics>`_
For a node n and constraint nc, satisfies2(n, nc) if and only if for every nodeKind, datatype, xsFacet and
values constr... | 5,310,613 |
def _gaussian(y_pred, y_true, scale):
"""
Computes the log-likelihood of each sample for a Gaussian GLM given the predicted expected values.
"""
return - 0.5 * (y_pred - y_true) ** 2 / scale ** 2 \
- 0.5 * np.log(2 * np.pi * scale**2) | 5,310,614 |
def grade(use_locks=True, student: model.Student = None):
"""Create the list of labs to pick one to grade"""
window = ui.get_window()
labs = data.get_labs()
if not labs:
popup = ui.layers.Popup("Error")
popup.set_message(["No labs have been created yet"])
window.run_layer(popup)... | 5,310,615 |
def regression_report(
y_true: Sequence,
y_pred: Sequence,
*,
precision: int = 4,
width: int = 32,
use_percentage: bool = False,
) -> str:
"""
Returns detailed regression report as string
:param y_true: sequence of ground truth values for regression problem
:param y_pred: sequen... | 5,310,616 |
def _extract_feats(data_test, model, what, skip=1, batch_size=16):
"""
:param data_test: test Dataset
:param model: network model
:param what: SK or IM
:param skip: skip a certain number of image/sketches to reduce computation
:return: a two-element list [extracted_labels, extracted_features]
... | 5,310,617 |
def textconv_pbit(pbit_path, outio):
"""
Convert a pbit to a text format suitable for diffing
"""
# TODO: check ends in pbit
order = []
with zipfile.ZipFile(pbit_path, compression=zipfile.ZIP_DEFLATED, mode="r") as zd:
# read items (in the order they appear in the archive)
for... | 5,310,618 |
def _getbkfile(repo):
"""Hook so that extensions that mess with the store can hook bm storage.
For core, this just handles wether we should see pending
bookmarks or the committed ones. Other extensions (like share)
may need to tweak this behavior further.
"""
fp, pending = txnutil.trypending(re... | 5,310,619 |
def refresh_table(model,engine):
"""
Drop the existed table from database, if exist
In any case create a new table
"""
table = model.__table__
if table.exists(engine):
logging.info(f"dropping existing table: {str(table)}")
table.drop(engine)
logging.info(f"creating a new tabl... | 5,310,620 |
def perturb(graph_list, p):
""" Perturb the list of (sparse) graphs by adding/removing edges.
Args:
p: proportion of added edges based on current number of edges.
Returns:
A list of graphs that are perturbed from the original graphs.
"""
perturbed_graph_list = []
for G_or... | 5,310,621 |
def assert_output(result, expected, exit_code=0):
"""
Assert that output matches the conditions.
:param result:
CliRunner result object
:param expected:
List/tuple of expected outputs
:param exit_code:
Expected exit code
"""
if not isinstance(expected, (tuple, list... | 5,310,622 |
def hold_out_val(data, target, include_self=True, class_weight=None,
features=None, cl='rf', verbose=False, random_state=None):
"""
performs simple hold-out validation
:param data: list of datasets to evaluate
:param verbose: if true print confusion matrix and classification report for ... | 5,310,623 |
def train(model, train_loader, loss_func, optimizer, device):
"""
训练模型
train model using loss_fn and optimizer in an epoch.
model: CNN networks
train_loader: a Dataloader object with training data
loss_func: loss function
device: train on cpu or gpu device
"""
total_loss = 0
# tr... | 5,310,624 |
def sq_dist(x: np.ndarray, y: np.ndarray):
"""
distance functions for point-point distances
:param x: nd array, T1 x D
:param y: nd array, T2 x D
:return: matrix with shape of (T1, T2)
"""
return np.sum((x[:, None, :] - y[None, :, :]) ** 2, axis=2) | 5,310,625 |
def test_pressure():
"""
Test pressure function
"""
h = 0
expected_value = 101325
assert_array_almost_equal(pressure(h), expected_value)
h = 20e3
expected_value = 5529
assert_array_almost_equal(pressure(h), expected_value) | 5,310,626 |
def autocomplete(event):
"""Force autocompletion at cursor."""
buffer = event.app.current_buffer
if buffer.complete_state:
buffer.complete_next()
else:
buffer.start_completion(select_first=True) | 5,310,627 |
def get_uuid():
"""
Returns a uuid4 (random UUID) specified by RFC 4122 as a
32-character hexadecimal string
"""
return uuid.uuid4().hex | 5,310,628 |
async def register_users(app, users):
"""Create multiple users from a list.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance.
users : list(dict)
The list of new users with each user having username, password, permissions and cards (optional).
... | 5,310,629 |
def radmat_from_df_filter(
df, radmat_field="signal", channel_i=None, return_df=False, **kwargs
):
"""
Apply the filter args from df_filter and return a radmat
"""
_df = df_filter(df, channel_i=channel_i, radmat_field=radmat_field, **kwargs)
radmat = df_to_radmat(_df, channel_i=channel_i, radmat... | 5,310,630 |
def canonical(path):
"""
Enforce a canonical representation of the artifact tree.
When directly working with artifact trees, there are many different
representations of formatting that will result in the same artifact tree.
This can cause issues when colaboratively working an atrifact tree within a... | 5,310,631 |
def _populate_number_fields(data_dict):
"""Returns a dict with the number fields N_NODE, N_EDGE filled in.
The N_NODE field is filled if the graph contains a non-`None` NODES field;
otherwise, it is set to 0.
The N_EDGE field is filled if the graph contains a non-`None` RECEIVERS field;
otherwise, it is set ... | 5,310,632 |
def tree_pretty_print(tree):
"""Pretty-print a tree of python objects.
Examples::
>>> from pptree import Node
>>> users = Node("users")
>>> group = Node("group", users)
>>> _ = Node("roles", group)
>>> _ = Node("permissions", group)
>>> _ = Node("comments", users)
>>> print(tree_pr... | 5,310,633 |
def branch_edit(request, branch_id):
"""/branch_edit/<branch> - Edit a Branch record."""
branch = models.Branch.get_by_id(int(branch_id))
if branch.owner != request.user:
return HttpTextResponse('You do not own this branch', status=403)
if request.method != 'POST':
form = BranchForm(initial={'category':... | 5,310,634 |
def eul(f, u, x_0, d, param):
"""Integrate dynamics using forward Euler method
x[k+1] = x[k] + delta*(f(x[k], u[k]))
Input: dynamics f, control input u, initial condition x_0, step d
Output: trajectory x
"""
if u.ndim == 1:
return x_0 + d*(f(x_0, u, param))
N... | 5,310,635 |
def input_network_name():
"""
Prompt user to choose a network
"""
while True:
network_name = input('network ({0})?'.format(','.join(NETWORK_NAMES)))
if network_name in NETWORK_NAMES:
return network_name | 5,310,636 |
def bitwise_or(src1, src2, dst=None, mask=None):
""" bitwise_or(src1, src2[, dst[, mask]]) -> dst """
pass | 5,310,637 |
def define_ramp_limit_constraints(n, sns, c):
"""
Defines ramp limits for a given component with valid ramplimit.
"""
rup_i = n.df(c).query('ramp_limit_up == ramp_limit_up').index
rdown_i = n.df(c).query('ramp_limit_down == ramp_limit_down').index
if rup_i.empty & rdown_i.empty:
return
... | 5,310,638 |
def main():
"""
Prompts the user to select any available non-interactive scene and loads it.
Shows how to load directly scenes without the Environment interface
Shows how to sample points in the scene and how to compute geodesic distance and the shortest path
"""
logging.info("*" * 80 + "\nDescr... | 5,310,639 |
def hashtag(phrase, plain=False):
"""
Generate hashtags from phrases. Camelcase the resulting hashtag, strip punct.
Allow suppression of style changes, e.g. for two-letter state codes.
"""
words = phrase.split(' ')
if not plain:
for i in range(len(words)):
try:
if not words[i]:
del words[i]
wor... | 5,310,640 |
def _subtract(summary, o):
"""Remove object o from the summary by subtracting it's size."""
found = False
row = [_repr(o), 1, getsizeof(o)]
for r in summary:
if r[0] == row[0]:
(r[1], r[2]) = (r[1] - row[1], r[2] - row[2])
found = True
if not found:
summary.ap... | 5,310,641 |
def maxpool_to_same_maxpool(module):
"""Turn All MaxPool2d into SameMaxPool2d to match TF padding"""
module_output = module
if isinstance(module, nn.MaxPool2d):
module_output = MaxPool2dSamePadding(
kernel_size=module.kernel_size,
stride=module.stride,
padding=0, ... | 5,310,642 |
def main(args=None):
"""
This is the main function called by the `velplot` script.
"""
from astropy.utils.compat import argparse
from astropy.extern.configobj import configobj, validate
from pkg_resources import resource_stream
parser = argparse.ArgumentParser(
description='Creat... | 5,310,643 |
def print_results(article, abstract, decoded_output):
"""Prints the article, the reference summmary and the decoded summary to screen"""
print ""
tf.logging.info('ARTICLE: %s', article)
tf.logging.info('REFERENCE SUMMARY: %s', abstract)
tf.logging.info('GENERATED SUMMARY: %s', decoded_output)
print "" | 5,310,644 |
def check_for_split(G, edge):
"""
Given an edge in tuple form, check if it splits the
graph into two disjoint clusters. If so, it returns
True. Otherwise, False.
"""
# Possibly keep a record of splits.
try:
return not G.edge_disjoint_paths(source=edge[0], target=edge[1])
# TO... | 5,310,645 |
def process_boto3_stubs(
output_path: Path, service_names: List[ServiceName]
) -> Boto3StubsPackage:
"""
Parse and write stubs package `boto3_stubs`.
Arguments:
output_path -- Package output path.
Return:
Parsed Boto3StubsPackage.
"""
logger.debug("Parsing boto3 stubs")
... | 5,310,646 |
def double_wedge_filter(sinogram, center=0, sino_type="180", iteration=5,
mask=None, ratio=1.0, pad=250):
"""
Apply double-wedge filter to a sinogram image (Ref. [1]).
Parameters
----------
sinogram : array_like
2D array. 180-degree sinogram or 360-degree sinogram.
... | 5,310,647 |
def gather_data_to_plot(wells, df):
"""
Given a well ID, plot the associated data, pull out treatments.
Pull in dataframe of all the data.
"""
data_to_plot = []
error_to_plot = []
legend = []
for well in wells:
data_to_plot.append(df.loc[well, '600_averaged'])
error_to_pl... | 5,310,648 |
def build_rust_cmdclass(cargo_toml_path, debug=False,
extra_cargo_args=None, quiet=False,
ext_name=None):
"""
Args:
cargo_toml_path (str) The path to the cargo.toml manifest
(--manifest)
debug (boolean) Co... | 5,310,649 |
def create_data_frame_sfem(data_sfem, strategy_order):
""" Create the DataFrame that will be used for the
type classification.
Args:
data_sfem (DataFrame): Individual level data that is
already subset to the correct level.
strategy_order (list): Name of all st... | 5,310,650 |
def is_ignored(filename, ignores):
"""
Checks if the filename matches any of the ignored keywords
:param filename:
The filename to check
:type filename:
`str`
:param ignores:
List of regex paths to ignore. Can be none
:type ignores:
`list` of `str` or None
:r... | 5,310,651 |
def patch(vol_data, # the volume
patch_size, # patch size
patch_stride=1, # patch stride (spacing)
nb_labels_reshape=1, # number of labels for categorical resizing. 0 if no resizing
keep_vol_size=False, # whether to keep the volume size on categorica... | 5,310,652 |
def public():
"""
# TODO improve docstring
Filtered version of the Alerts controller
"""
s3.filter = (FS("scope") == "Public") # TODO do this in the prep of alert()
return alert() | 5,310,653 |
def token(username: str, password: str, auth_url: str = 'https://api.sonetel.com/SonetelAuth/beta/oauth/token',
refresh: str = "no", grant_type: str = "password", refresh_token: str = None) -> dict:
"""
Create an API access token from the user's Sonetel email address and password.
Optionally, gene... | 5,310,654 |
async def present(
hub,
ctx,
name,
resource_group,
sku,
kind,
location,
custom_domain=None,
encryption=None,
network_rule_set=None,
access_tier=None,
https_traffic_only=None,
is_hns_enabled=None,
tags=None,
connection_auth=None,
**kwargs,
):
"""
..... | 5,310,655 |
def ftp_file_hash(con):
""" Get the file hashes inside the FTP server
Assumes that the FTP connection is already in the wordpress dir.
"""
# Function to get MD5 Hash inside the FTP server
def get_md5(fpath):
""" Returns the md5 hash string of a file """
ftp_md5 = hashlib.md5()... | 5,310,656 |
def defineFrom(from_name, *names):
"""Define deferred imports from a particular module.
The from_name specifies which module to import.
The rest of the parameters specify names to import from that module.
"""
module = initialize(2)
__deferred_definitions__ = module.__deferred_definitions__
... | 5,310,657 |
def writeABF1(sweepData, filename, sampleRateHz, units='pA'):
"""
Create an ABF1 file from scratch and write it to disk.
Files created with this function are compatible with MiniAnalysis.
Data is expected to be a 2D numpy array (each row is a sweep).
"""
assert isinstance(sweepData, np.ndarray)... | 5,310,658 |
def check_transaction_threw(client, transaction_hash):
"""Check if the transaction threw/reverted or if it executed properly
Returns None in case of success and the transaction receipt if the
transaction's status indicator is 0x0.
"""
encoded_transaction = data_encoder(transaction_hash.decode(... | 5,310,659 |
def boldReplacements(tex):
"""
SPECIFIC TO shmem_reductions:
Replace the Latex command:
"\\textbf{<NAME>} \\newline <text> <code> \\newline...\\bigskip"
--NAME will the title of a new section header with <text> as the
immediate content.
-- <code> will be replaced as normal (See function ... | 5,310,660 |
def stop_program():
"""Small function to ask for input and stop if needed
"""
ok = input("Press S to Stop, and any other key to continue...\n")
if ok in ["S", "s"]:
return True
return False | 5,310,661 |
def rotate(n):
"""
Rotate 180 the binary bit string of n and convert to integer
"""
bits = "{0:b}".format(n)
return int(bits[::-1], 2) | 5,310,662 |
def fixture_list_arg():
"""Test for the correct stdout.
Output in the tests should match what this returns
"""
def list_arg(*profiles):
_string = ""
for profile in profiles:
_string += (
f"[{profile}]\n"
f"reponame = {HOST}\n"
... | 5,310,663 |
def tkForm(fields):
"""tkForm(fields: dict)->dict
fields: {'label1': 'defVal1', ...}
return: modified fields or {} if Esc
>_> tkForm( {'Imię':'iii', 'Imię 2':'iii 2', 'Nazwisko':'Nnn'} )
{'Imię': 'iii 1', 'Imię 2': 'iii 2', 'Nazwisko': 'nnn 3'}
"""
master = tk.Tk()
entries = {}
for i, (field,... | 5,310,664 |
def concentration_at_M(Mass, k, P, n_s, Omega_b, Omega_m, h, T_CMB=2.7255, delta=200, Mass_type="crit"):
"""Concentration of the NFW profile at mass M [Msun/h].
Only implemented relation at the moment is Diemer & Kravtsov (2015).
Note: only single concentrations at a time are allowed at the moment.
Ar... | 5,310,665 |
def knc_require_k1om(*_):
"""Compatibility checking callback for use with data models.
Requires that the Intel k1om tools be installed if the host architecture is KNC.
Raises:
ConfigurationError: Invalid compiler family specified in target configuration.
"""
k1om_ar = util.which('x86_64-k1... | 5,310,666 |
def flip_thetas(thetas, theta_pairs):
"""Flip thetas.
Parameters
----------
thetas : numpy.ndarray
Joints in shape (num_thetas, 3)
theta_pairs : list
List of theta pairs.
Returns
-------
numpy.ndarray
Flipped thetas with shape (num_thetas, 3)
"""
thetas... | 5,310,667 |
def Client(token=None, endpoint=None, config_path=None, connect_timeout=None):
"""Return global `RESTClientObject` with optional configuration.
Missing configuration will be read from env or config file.
Parameters
----------
token : str, optional
API token
endpoint : str, optional
... | 5,310,668 |
def numeral_to_int(numeral: str) -> int:
"""Returns the integer value represented by the given Roman numeral."""
i = 0
numeral_len = len(numeral)
total = 0
while i < numeral_len:
curr_value = numeral_values[numeral[i]]
if i < numeral_len - 1:
next_value = numeral_values[n... | 5,310,669 |
def main():
"""Read in a 'standard' file - printing out a smaller version
"""
parser = argparse.ArgumentParser(
description="Filter compressed standard SMILES"
" for Astex Fragment network."
)
parser.add_argument('--input',
help="The input, a compr... | 5,310,670 |
def TopOpeBRepTool_TOOL_tryTg2dApp(*args):
"""
:param iv:
:type iv: int
:param E:
:type E: TopoDS_Edge &
:param C2DF:
:type C2DF: TopOpeBRepTool_C2DF &
:param factor:
:type factor: float
:rtype: gp_Vec2d
"""
return _TopOpeBRepTool.TopOpeBRepTool_TOOL_tryTg2dApp(*args) | 5,310,671 |
def GetMounts(filename=constants.PROC_MOUNTS):
"""Returns the list of mounted filesystems.
This function is Linux-specific.
@param filename: path of mounts file (/proc/mounts by default)
@rtype: list of tuples
@return: list of mount entries (device, mountpoint, fstype, options)
"""
# TODO(iustin): inve... | 5,310,672 |
def AppendToFile(file_path, string):
"""Append the string to the given file.
This method provides atomic appends if the string is smaller than
PIPE_BUF (> 512 bytes). It does not guarantee atomicity once the
string is greater than that.
Args:
file_path: File to be appended to.
string: String to ap... | 5,310,673 |
def disable_slot(slot, con=None):
"""Return True on success, False on failure, if con given does not commit"""
if not slot:
return False
if con is None:
try:
con = open_database()
result = disable_slot(slot, con)
if result:
con.commit()
... | 5,310,674 |
def surface_analysis_function_for_tests(surface, a=1, c="bar"):
"""This function can be registered for tests."""
return {'name': 'Test result for test function called for surface {}.'.format(surface),
'xunit': 'm',
'yunit': 'm',
'xlabel': 'x',
'ylabel': 'y',
... | 5,310,675 |
def do_tagging(deprel_folder, wiki_folder, setnames, gpus, split_size=int(5e4)):
"""This will format the train/dev/test sets of wikibio
so that we can run the deprel tagging network we have trained"""
for setname in setnames:
assert setname in ['train', 'valid', 'test']
print(f'Loading exa... | 5,310,676 |
def add_or_update(record, key, timetable, name, force_refresh):
"""
Insert a new user record or update exist one
:param name: user name identifier
:param timetable: timetable list
:param force_refresh: if refresh is required
:param key: the key in database
:param record: a User record
:r... | 5,310,677 |
def benchmark(N=1000, n_features=20, hidden_layer_sizes="26,25", max_iter=1000,
learning_rate_init=1e-4, batch_size=100, run_torch=True,
device='cpu', opset=12, profile='fct'):
"""
Compares :epkg:`onnxruntime-training` to :epkg:`scikit-learn` for
training. Training algorithm is S... | 5,310,678 |
def setDirs(fpath):
"""Add file dir to python path and setup the working directory
"""
import os, sys
# get MPI status
haveMpi, comm, rank, size = getMpi()
# create workspace path
sys.path.append(os.path.dirname(fpath)) # [RB] !this folder is can be a subfolder of one of the folders in the p... | 5,310,679 |
def from_time (year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None):
"""
Convenience wrapper to take a series of date/time elements and return a WMI time
of the form yyyymmddHHMMSS.mmmmmm+UUU. All elements may be int, string or
omitted altogether. If omi... | 5,310,680 |
def plural(num, one, many):
"""Convenience function for displaying a numeric value, where the attached noun
may be both in singular and in plural form."""
return "%i %s" % (num, one if num == 1 else many) | 5,310,681 |
def _handle_login_redirect(request, key):
""" This function is used to redirect login request to Microsoft OneDrive login page.
:param request: Data given to REST endpoint
:param key: Key to search in state file
:return: response authorization_url/admin_consent_url
"""
asset_id = request.GET.g... | 5,310,682 |
def test_fetch_alerts(requests_mock):
"""Tests taegis-fetch-alert command function
"""
mock_response = {
"data": {
"alerts": [TAEGIS_ALERT]
}
}
client = mock_client(requests_mock, mock_response)
args = {
"ids": ["c4f33b53-eaba-47ac-8272-199af0f7935b"]
}... | 5,310,683 |
def shape_element(element, node_attr_fields=NODE_FIELDS, way_attr_fields=WAY_FIELDS,
problem_chars=PROBLEMCHARS, default_tag_type='regular'):
"""Clean and shape node or way XML element to Python dict"""
node_attribs = {}
way_attribs = {}
way_nodes = []
tags = [] # Handle secondar... | 5,310,684 |
def get_parent_module():
"""Get parent filename."""
frame = inspect.currentframe()
module = inspect.getmodule(frame)
while module.__name__ == __name__:
if frame.f_back is None:
raise ValueError("Fell off the top of the stack.")
frame = frame.f_back
module = inspect.ge... | 5,310,685 |
def pytest_addoption(parser):
"""Add a custom option to the pytest call.
Simply use
.. code-block:: bash
$ pytest --n-random-tests=n
to restrict running each random test with `n` increments of the base seed given by
`pytest-randomly`.
"""
parser.addoption(
"--n-random-te... | 5,310,686 |
def keyTangent(q=1,e=1,a=1,an="string",at="string",cp=1,f="floatrange",g=1,hi="string",ia="angle",itt="string",iw="float",iub=1,index="uint",ix="float",iy="float",l=1,oa="angle",ott="string",ow="float",ox="float",oy="float",ptt="string",r=1,s=1,sa=1,t="timerange",uni=1,wl=1,wt=1):
"""
http://help.autodesk.com/cloud... | 5,310,687 |
def move_random():
"""Sends random command to robot."""
rng = np.random.default_rng()
random_pos = (rng.random((6,)) - 0.5) / 2.0
command = Command(
x=random_pos[0],
y=random_pos[0],
z=random_pos[0],
roll=random_pos[0],
pitch=random_pos[0],
yaw=random_pos... | 5,310,688 |
def log_response(response: str, trim_log_values: bool = False, **kwargs: Any) -> None:
"""Log a response"""
return log_(response, response_logger, logging.INFO, trim=trim_log_values, **kwargs) | 5,310,689 |
def run():
"""Requirements for Task 1B"""
# Build list of stations
stations = build_station_list()
# Defines co-ordinate p (city centre)
p = (52.2053, 0.1218)
# Calls function
x = stations_by_distance(stations, p)
# Crates empty lists for closest and furthest stations
closest = [... | 5,310,690 |
def logged_in(browser: RoboBrowser):
"""
Returns true if we are still on the login page
"""
login_div = browser.find('div', content="Login")
return True if not login_div else False | 5,310,691 |
def nan_dot(A, B):
"""
Returns np.dot(left_matrix, right_matrix) with the convention that
nan * 0 = 0 and nan * x = nan if x != 0.
Parameters
----------
A, B : np.ndarrays
"""
# Find out who should be nan due to nan * nonzero
should_be_nan_1 = np.dot(np.isnan(A), (B != 0))
shoul... | 5,310,692 |
def get_log_files():
"""
TODO: Document
:return:
"""
files = set()
for file in os.listdir(LOG_DIR):
if file.endswith(".log"):
files.add(os.path.join(LOG_DIR, file))
return files | 5,310,693 |
def metadata_record_validation_activity_show(context, data_dict):
"""
Return the latest validation activity for a metadata record.
:param id: the id or name of the metadata record
:type id: string
:rtype: dictionary, or None if the record has never been validated
"""
log.debug("Retrieving ... | 5,310,694 |
def start():
"""Torrentool command line utilities.""" | 5,310,695 |
def create_sample_lp():
"""
Using gurobi create a sample LP.
"""
# Forest of 100 stands each assumed to be 1 ha in area
stands = create_stands(100)
# Minimum harvest age is 40 years, 10 year planning horizon
schedules = schedule_generator(4, 10)
# Track the age of each stand under eac... | 5,310,696 |
def train_crabnet(model_name, csv_train, csv_val=None, val_frac=0.25):
"""
Function to train crabnet. This function allows a user to easily train
crabnet by only supplying training data a model name. You can update
epoch and batch size if desired.
Parameters
----------
model_name : str
... | 5,310,697 |
def link_console_script(pkg, overwrite=False):
"""Find console scripts of the package and try to link the executable to
the global scripts folder.
:arg str pkg: Package name.
:arg bool overwrite: Whether to overwrite the existed script.
"""
import shutil
import os
from configparser ... | 5,310,698 |
def test_query_retry_maxed_out(
mini_sentry, relay_with_processing, outcomes_consumer, events_consumer
):
"""
Assert that a query is not retried an infinite amount of times.
This is not specific to processing or store, but here we have the outcomes
consumer which we can use to assert that an event ... | 5,310,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.