content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def textarea():
""" Returns a textarea parser.
Example::
...[5]
The number defines the number of rows.
"""
rows = number_enclosed_in('[]')('rows')
textarea = Suppress('...') + Optional(rows)
textarea.setParseAction(tag(type='textarea'))
return textarea | 5,348,200 |
def run(task):
"""Run the train/predict flow for `task`."""
st.markdown(f'<h1 align="center">{task}</h1>', unsafe_allow_html=True)
train_button = st.sidebar.button("Train")
sidebar_train_message = st.sidebar.empty()
main_train_message = st.empty()
slug = slugify(task)
trained = is_trained(sl... | 5,348,201 |
def union_categoricals(
to_union: List[
Union[
pandas.core.indexes.category.CategoricalIndex,
pandas.core.series.Series,
pandas.core.arrays.categorical.Categorical,
]
]
):
"""
usage.dask: 15
"""
... | 5,348,202 |
def get_agent(agent_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAgentResult:
"""
This data source provides details about a specific Agent resource in Oracle Cloud Infrastructure Database Migration service.
Display the ODMS Agent configuration.
##... | 5,348,203 |
def darknet():
"""Darknet-53 classifier.
"""
inputs = Input(shape=(416, 416, 3))
x = darknet_base(inputs)
x = GlobalAveragePooling2D()(x)
x = Dense(1000, activation='softmax')(x)
model = Model(inputs, x)
return model | 5,348,204 |
def create_process_chain_entry(input_object, python_file_url,
udf_runtime, udf_version, output_object):
"""Create a Actinia command of the process chain that uses t.rast.udf
:param strds_name: The name of the strds
:param python_file_url: The URL to the python file that defin... | 5,348,205 |
def add_user_to_authorization_domain(auth_domain_name, email, permission):
"""Add group with given permissions to authorization domain."""
# request URL for addUserToGroup
uri = f"https://api.firecloud.org/api/groups/{auth_domain_name}/{permission}/{email}"
# Get access token and and add to headers fo... | 5,348,206 |
def test_subpart_decl_build_cls(subpart_decl):
"""Test that the class creation does get the docs and set the attributes.
"""
class Test:
pass
with subpart_decl as ss:
ss.a = Feature()
subpart_decl._name_ = 'sub'
cls = subpart_decl.build_cls(Test, None, {'sub': 'Test docs',
... | 5,348,207 |
def error_032_link_two_pipes(text):
"""Fix some cases and return (new_text, replacements_count) tuple."""
(text, ignored) = ignore(text, r"\[\[\s*:?\s*{}.*?\]\]".format(IMAGE))
(text, count1) = re.subn(r"\[\[([^|\[\]\n]+)\|\|([^|\[\]\n]+)\]\]", "[[\\1|\\2]]", text)
(text, count2) = re.subn(r"\[\[([^... | 5,348,208 |
def define_answer(defined_answer):
"""
ランダムに「正解」を生成する
1桁ずつ、0~15までの乱数を引いて決めていく
count桁目の乱数(digit_kari)を引いた時、count-1桁目までの数字と重複がないかをチェック。
重複がなければ、引いた乱数(digit_kari)をans_list[count]に保存。
重複してたらその桁の乱数を引き直す。
"""
global ans_str #,ans_list
if type(defined_answer) == str and len(define... | 5,348,209 |
def cifar10(eps, use_bounds=False):
"""Example dataloader. For MNIST and CIFAR you can actually use existing ones in utils.py."""
assert eps is not None
database_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'datasets')
# You can access the mean and std stored in config file.
mean ... | 5,348,210 |
def truncate_dataset_position(filename, joint_type="w", threshold=0.01, directory="./2_smoothed/"):
"""
Truncates dataset **with raw position data** from last zero value before maximum velocity to following zero value.
:param filename: Input filename of position dataset
:param joint_type: Chooses which... | 5,348,211 |
def quadric_errors_representative(bucket):
"""
Quadric errors representative function.
:param bucket: bucket to calculate representative from.
:type bucket: Bucket
:return: bucket's representative vertex coordinates
:rtype: tuple(float, float, float)
"""
A = np.zeros((3, 3))
b = np.... | 5,348,212 |
def getMonthTicks(start, end, increment, offset=0):
"""
Create a set of matplotlib compatible ticks and tick labels
for every `increment` month in the range [start, end],
beginning at the month of start + `offset` months.
"""
xLabels = []
xTicks = []
y, m, d = helpers.yearmonthday(start)... | 5,348,213 |
def untar(fileobj):
"""Extract tar archive."""
logger.debug("untar")
fileobj = seekable(fileobj)
with tarfile.open(fileobj=fileobj) as tar_data:
tar_data.extractall() | 5,348,214 |
def entropy_layer(inp, theta, num_samples, sample_init, sample_const, train_vect):
""" Entropy PersLay
WARNING: this function assumes that padding values are zero
"""
bp_inp = tf.einsum("ijk,kl->ijl", inp, tf.constant(np.array([[1.,-1.],[0.,1.]], dtype=np.float32)))
sp = tf.get_variable("s", shape=[... | 5,348,215 |
def set_version_code(data):
"""
Utility function to set new versionCode
"""
match = version_code_pattern.search(data)
if not match:
raise ValueError('Version code not found')
version_code = int(match.group('value'))
next_version_code = '\g<key> {}'.format(version_code + 1)
return... | 5,348,216 |
def add_resource(label, device_type, address, userid, password, rackid='', rack_location='',
ssh_key=None, offline=False):
""" Add device to the list of devices in the configuration managed
Args:
label: label for device
device_type: type of device from device enumeration
... | 5,348,217 |
def kegg_df_to_smiles(kegg_df, column_name):
"""
Args:
kegg_df : pandas dataframe with SID numbers in the third column
Returns:
kegg_df : modified with a fourth column containing CID and fifth column containing SMILES
unsuccessful_list : list of SIDs for which no CID or SMILES were ... | 5,348,218 |
async def get_user(user_id: int) -> User:
"""Gets user settings.
Returns
-------
User object
Raises
------
sqlite3.Error if something happened within the database.
exceptions.NoDataFoundError if no user was found.
LookupError if something goes wrong reading the dict.
Also logs ... | 5,348,219 |
def _valid_optimizer_args(cfg_user, logger):
"""
Validates the "optimizer" parameters of a json configuration file used for training.
The function returns False if an error has occurred and True if all settings have passed the check.
:param cfg_user: EasyDict, json configuration file imported as dicti... | 5,348,220 |
def connect(
server_index: int = typer.Argument(None, help="Connect to a server with the index given by 'csgo servers'"),
):
"""
Start CSGO and connect to a specific game server.
"""
if server_index is None:
typer.echo("Please specify the server index")
return
if server_inde... | 5,348,221 |
def test_insert_again(report):
"""Insert already present data into the database."""
report.insert("London, GB") | 5,348,222 |
def delete_host_network(host_id, host_network_id):
"""Delete host network."""
data = _get_request_data()
return utils.make_json_response(
200,
host_api.del_host_network(
host_id, host_network_id, user=current_user, **data
)
) | 5,348,223 |
def rrms_error(y: np.array, y_hat: np.array) -> float:
"""
Computes the RRMS error of an estimation.
:param y: true parameters as numpy array
:param y_hat: estimated parameters as numpy array
:return: Frobenius norm of the relative estimation error, as percentage
"""
return fro_error(y, y_h... | 5,348,224 |
def create():
"""Creates new quiz and stores information about it in database."""
if request.method == "GET":
return render_template("quizzes/create.html")
error = None
questions = []
quiz_name = None
if isinstance(request.json, dict):
for quiz in request.json:
quiz_n... | 5,348,225 |
def get_teams_from_account(client: FrameioClient) -> Dict:
"""
Builds a list of teams for the account. Note: the API offers two strategies to fetch an account's teams,
`'get_teams`` and `get_all_teams`. Using `get_teams`, we'll pull only the teams owned by the account_id,
disregarding teams the user b... | 5,348,226 |
def verify_mfib_vrf_hardware_rate(
device, vrf, num_of_igmp_groups, var, rate_pps, max_time=60, check_interval=10):
"""Verify mfib vrf hardware rate
Args:
device ('obj'): Device object
neighbors (`list`): neighbors to be verified
max_time (`int`, optional): Max time... | 5,348,227 |
def sieve(n):
"""
Returns a list with all prime numbers up to n.
>>> sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> sieve(10)
[2, 3, 5, 7]
>>> sieve(9)
[2, 3, 5, 7]
>>> sieve(2)
[2]
>>> sieve(1)
... | 5,348,228 |
def is_trueish(expression: str) -> bool:
"""True if string and "True", "Yes", "On" (ignorecase), False otherwise"""
expression = str(expression).strip().lower()
return expression in {'true', 'yes', 'on'} | 5,348,229 |
def u_onequbit_h(qc: qiskit.QuantumCircuit, thetas, wire: int):
"""Return a simple series of 1 qubit - gate which is measured in X-basis
Args:
- qc (QuantumCircuit): Init circuit
- thetas (Numpy array): Parameters
- wire (Int): position that the gate carries on
Returns:
... | 5,348,230 |
def test_union_g_month_day_g_year_month_enumeration_nistxml_sv_iv_union_g_month_day_g_year_month_enumeration_1_1(mode, save_output, output_format):
"""
Type union/gMonthDay-gYearMonth is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/union/gMonthDay-gYearMonth/Schema+Inst... | 5,348,231 |
def get_manager() -> ArchiveManager:
"""
Returns the object storage manager for the archive subsys
:return:
"""
global _manager_singleton
if _manager_singleton is None:
raise Exception("Not initialized. Call init_archive_manager")
return _manager_singleton | 5,348,232 |
def require_password_and_profile_via_email(
strategy, backend, user=None, flow=None, current_partial=None, *args, **kwargs
): # pylint: disable=unused-argument
"""
Sets a new user's password and profile
Args:
strategy (social_django.strategy.DjangoStrategy): the strategy used to authenticate
... | 5,348,233 |
def plot_feat_barplot(feat_data: pd.DataFrame,
top_x_feats: int = 15,
plot_features: dict = None
):
"""Plots local feature explanations
Parameters
----------
feat_data: pd.DataFrame
Feature explanations
top_x_feats: int
... | 5,348,234 |
def RK2(state,arrayTimeIndex,globalTimeStep,dt):
"""Use this method to solve a function with RK2 in time."""
#globals
global gamma, mG
gamma = 1.4
mG = 0.4
#step data
dx = 1/(state.shape[-1]-4-1)
dtdx = dt/dx
#Creating pressure vector
if globalTimeStep%2==0:
P = eqnStateQ... | 5,348,235 |
async def post_ir_remote_key(device_id: str, remote_id: str, payload: dict) -> dict:
# fmt: off
"""
Trigger key / code on the remote bound to IR device. There are 2 types of keys on Tuya IR
devices:
* native - out of the box keys, provided with remotes for different brands
* custom - DIY... | 5,348,236 |
def login():
"""
The function for the front-end client to log in.
Use the following command to test:
$ curl -d '{"custom_id":"id"}' -H "Content-Type: application/json" -X POST http://0.0.0.0:5000/login/
Parameters
----------
google_id_token : str
The token obtained from the Google ... | 5,348,237 |
def listThingTypes():
"""
Return a list of C{unicode} strings each of which gives the name of a type
which can be created with the create command.
"""
return sorted([type.type for type in getPlugins(IThingType, imaginary.plugins)]) | 5,348,238 |
def transform(item_paths, output_dir, experiment_code, compresslevel=0):
"""Read medable csv and writes gen3 json."""
cases_emitter = emitter('case', output_dir=output_dir)
cases = set([])
with open(item_paths[0], newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader... | 5,348,239 |
def _parse_boolean(value):
"""
:param value: The string to parse
:type value: str
:returns: The parsed value
:rtype: bool
"""
try:
boolean = json.loads(value)
if boolean is None or isinstance(boolean, bool):
return boolean
else:
raise DCOSExce... | 5,348,240 |
def train(args, model, train_data_loader, dev_data_loader, accuracy, device):
"""
Train the current model
Keyword arguments:
args: arguments
model: model to be trained
train_data_loader: pytorch build-in data loader output for training examples
dev_data_loader: pytorch build-in data loader... | 5,348,241 |
def get_category_embeddings(word_table, embeds):
"""Calculate embeddings from word labels for each category."""
category_words = read_categories_as_json()
word_ids = word_table.lookup(tf.constant(category_words))
glove_embeds = tf.nn.embedding_lookup(embeds, word_ids)
# Calculate category embedding by summin... | 5,348,242 |
def find_download_links(soup, title, language):
"""Examine all download links per law document and create respective filepaths."""
vbfile = soup.find("div", "vbFile")
fulltext = soup.find("div", "fulltext")
# check if file attachment elements exist
if vbfile is not None:
attach = vbfile.se... | 5,348,243 |
def ignore():
"""An empty function with a big string.
Make the compression algorithm work a little harder.
"""
"""
LAERTES
O, fear me not.
I stay too long: but here my father comes.
Enter POLONIUS
A double blessing is a double grace,
Occasion smiles upon a second... | 5,348,244 |
def find_replace(input_path, old_string, new_string, name_id, platform, fix_cff, exclude_namerecord, output_dir,
recalc_timestamp, overwrite):
"""Replaces a string in the name table with a new string.
If the '-cff' option is passed, the string will be replaced also in the 'CFF' table:
... | 5,348,245 |
def fake_feature_date(days=365):
"""Generate fake feature_date."""
start_date = date.today()
random_number_of_days = random.randrange(days)
_date = start_date + timedelta(days=random_number_of_days)
return _date.strftime("%Y-%m-%d") | 5,348,246 |
def freq_dom(inf, outf):
"""
Dominance filter:
When there are multiple annotations of the exact same anchor, (position +
content) keep only the one with the highest count, breaking ties with
alphabetical-ness.
TODO: Could use some other measure of frequency -- or lemma numbering/graph
cent... | 5,348,247 |
def download_recurse(url, path, filenames):
"""download files from url
:param str url: the url to download from, ended with a '/'
:param str path: the directory to save the files to
:param list files: list of filenames to download
"""
path = Path(path)
with click.progressbar(filenames, labe... | 5,348,248 |
def export_graph(checkpoint_path, output_nodes):
"""
Export a graph stored in a checkpoint as a *.pb file.
:param checkpoint_path: The checkpoint path which should be frozen.
:param output_nodes: The output nodes you care about as a list of strings (their names).
:return:
"""
if not tf.gfile... | 5,348,249 |
def scss(**conf):
"""
Render all SCSS/SASS files into CSS. The input directory will be searched
for *.scss files, which will be compiled to corresponding *.css files in
the output directory.
"""
compiler = pyScss.Scss(scss_opts={'compress': 0})
logging.getLogger("scss").addHandler(logging.S... | 5,348,250 |
def GetTrackingBranch(git_repo, branch=None, for_checkout=True, fallback=True,
manifest=None, for_push=False):
"""Gets the appropriate push branch for the specified directory.
This function works on both repo projects and regular git checkouts.
Assumptions:
1. We assume the manifest def... | 5,348,251 |
def test_isupport_getitem_case_insensitive():
"""Test access to parameters is case insensitive."""
instance = isupport.ISupport(awaylen=50)
assert 'AWAYLEN' in instance
assert 'awaylen' in instance
assert instance['AWAYLEN'] == 50
assert instance['awaylen'] == 50 | 5,348,252 |
def inception_crop(image, **kw):
"""Perform an "inception crop", without resize."""
begin, size, _ = tf.image.sample_distorted_bounding_box(
tf.shape(image), tf.zeros([0, 0, 4], tf.float32),
use_image_if_no_bounding_boxes=True, **kw)
crop = tf.slice(image, begin, size)
# Unfortunately, the above ope... | 5,348,253 |
def _clear_port_access_clients_limit_v1(port_name, **kwargs):
"""
Perform GET and PUT calls to clear a port's limit of maximum allowed number of authorized clients.
:param port_name: Alphanumeric name of Port
:param kwargs:
keyword s: requests.session object with loaded cookie jar
keywo... | 5,348,254 |
def yield_abspath_from_fofn(fofn_fn):
"""Yield each filename.
Relative paths are resolved from the FOFN directory.
"""
try:
basedir = os.path.dirname(fofn_fn)
for line in open(fofn_fn):
fn = line.strip()
if not os.path.isabs(fn):
fn = os.path.abspa... | 5,348,255 |
def cvGetHistValue_1D(hist, i1):
"""Returns pointer to histogram bin"""
return cast(cvPtr1D(hist.bins, i1), c_float_p) | 5,348,256 |
def contains_order_by(query):
"""Returns true of the query contains an 'order by' clause"""
return re.search( r'order\s+by\b', query, re.M|re.I) is not None | 5,348,257 |
def handler(event, context):
"""Called by Lambda"""
try:
send(
event, context, 'SUCCESS',
main(event),
event['LogicalResourceId']
)
except Exception as e:
send(event, context, "FAILED", {"Message": str(e)}) | 5,348,258 |
def detach(l):
"""\
Set a layer as detached, excluding it from gradient computation.
:param l: layer or list of layers to detach
:return: detached layer(s)
"""
# core module has multiple overloads for this:
# 1. detach(l) where l is a Layer and the return value is a Layer
# 2. detach... | 5,348,259 |
def validate_params_int(params: dict) -> None:
"""Validates the parameters for the chart based on the integer value
:param params: Dictionary of parameters
:type params: dict
:raises ValueError:
"""
variables = ["line_width", "point_size", "bucket_size"]
for var in variables:
if va... | 5,348,260 |
def update_data(p_state, idx_chain=-1):
"""Updates various data of the chain, including:
- Energies of images
- Reaction coordinates of images
- Interpolated energy and reaction coordinate values
"""
_Update_Data(ctypes.c_void_p(p_state), ctypes.c_int(idx_chain)) | 5,348,261 |
def test_R1():
""" Test R for dependent variables """
d = D(['00', '11'], [1/2, 1/2])
assert R(d) == pytest.approx(0) | 5,348,262 |
def __shorten_floats(source):
""" Use short float notation whenever possible
:param source: The source GLSL string
:return: The GLSL string with short float notation applied
"""
# Strip redundant leading digits
source = re.sub(re.compile(r'(?<=[^\d.])0(?=\.)'), '', source)
# Strip redundan... | 5,348,263 |
def cnn_model(logits=False, input_ph=None, img_rows=28, img_cols=28,
channels=1, nb_filters=64, nb_classes=10):
"""
Defines a CNN model using Keras sequential model
:param logits: If set to False, returns a Keras model, otherwise will also
return logits tensor
:param in... | 5,348,264 |
def _mvnormal_halton(sample_shape,
mean,
randomized,
seed=None,
covariance_matrix=None,
scale_matrix=None,
validate_args=False,
dtype=None,
**kwargs):
... | 5,348,265 |
def get_meals(bouts_sec: np.ndarray, max_gap_sec: float = 60.0, min_overlap: float = 0.25):
"""
Computes a sequence of meal intervals from a sequence of chewing-bout intervals.
:param bouts_sec: The sequence of chewing-bout intervals (see ``get_bouts`` output)
:param max_gap_sec: Maximum gap-duration t... | 5,348,266 |
def certificate_request_delete(handle, name):
"""
Deletes a certificate request from keyring
Args:
handle (UcsHandle)
name (string): KeyRing name
Returns:
None
Raises:
UcsOperationError: If PkiCertReq is not present
Example:
certificate_request_delete(... | 5,348,267 |
def test_evaluate_1d_data(input_data_file, output_data_file, index):
"""
Test ability to evaluate one dimensional data.
"""
# Initialize model from spring-mass example data files:
data_model = ModelFromData(input_data_file, output_data_file, 1.)
input_data = np.genfromtxt(input_data_file)
o... | 5,348,268 |
def _fail(msg):
"""Output failure message when auto configuration fails."""
red = "\033[0;31m"
no_color = "\033[0m"
fail("%sPython Configuration Error:%s %s\n" % (red, no_color, msg)) | 5,348,269 |
def ThreePaneView4DFrames(It):
"""
Pass in a series of fImages, fArray3Ds, python lists, or numpy
array and we'll show a three-pane view with a slider on the bottom
for visualizing 4D datasets as 3D frames
"""
print("4D frame-based threepane view not implemented yet, just an idea.") | 5,348,270 |
def test_input_sanity():
""" Check incorrect input do fail """
with assert_raises(NotImplementedError) as exception: MonteCarlo(temperature=0e0)
with assert_raises(ValueError) as exception: MonteCarlo(temperature=-1e0)
mc = MonteCarlo()
with assert_raises(TypeError) as exception: mc(lambda x: 0,... | 5,348,271 |
def torch_load(path, model):
"""Load torch model states.
Args:
path (str): Model path or snapshot file path to be loaded.
model (torch.nn.Module): Torch model.
"""
if "snapshot" in os.path.basename(path):
model_state_dict = torch.load(path, map_location=lambda storage, loc: stora... | 5,348,272 |
def setPerformanceLevel(source, level):
"""Sets a given performance level for the GPU Core and Memory.
Args:
source: string containing word "core" or "mem"
level: an integer between 0-7 for core and 0-3 memory
Returns:
True - if action is sucessful.
False - not pos... | 5,348,273 |
def test_n_submodels():
"""
Test that CompoundModel.n_submodels properly returns the number
of components.
"""
g2 = Gaussian1D() + Gaussian1D()
assert g2.n_submodels() == 2
g3 = g2 + Gaussian1D()
assert g3.n_submodels() == 3
g5 = g3 | g2
assert g5.n_submodels() == 5
g7 = g... | 5,348,274 |
def elem_props_template_init(templates, template_type):
"""
Init a writing template of given type, for *one* element's properties.
"""
ret = OrderedDict()
tmpl = templates.get(template_type)
if tmpl is not None:
written = tmpl.written[0]
props = tmpl.properties
ret = Orde... | 5,348,275 |
def to_density(x, bins=5, bounds=None):
""""Turn into density based nb of bins"""
p_x = np.histogram(x, bins=bins, density=True, range=bounds)[0]
p_x = p_x / np.sum(p_x)
return p_x | 5,348,276 |
def update_partition(CatalogId=None, DatabaseName=None, TableName=None, PartitionValueList=None, PartitionInput=None):
"""
Updates a partition.
See also: AWS API Documentation
Exceptions
:example: response = client.update_partition(
CatalogId='string',
DatabaseName='string'... | 5,348,277 |
def pro_bar(ts_code='', api=None, start_date='', end_date='', freq='D', asset='E',
exchange='',
adj = None,
ma = [],
factors = None,
adjfactor = False,
contract_type = '',
retry_count = 3):
"""
BAR数据
Parameters:
------------
... | 5,348,278 |
def convert(comment, mode):
"""Convert documentation from a supported syntax into reST."""
# FIXME: try to preserve whitespace better
if mode == 'javadoc-basic' or mode == 'javadoc-liberal':
# @param
comment = re.sub(r"(?m)^([ \t]*)@param([ \t]+)([a-zA-Z0-9_]+|\.\.\.)([ \t]+)",
... | 5,348,279 |
def test_trigger_endpoint_uses_existing_dagbag(admin_client):
"""
Test that Trigger Endpoint uses the DagBag already created in views.py
instead of creating a new one.
"""
url = 'trigger?dag_id=example_bash_operator'
resp = admin_client.post(url, data={}, follow_redirects=True)
check_content... | 5,348,280 |
def output_using_scrapingtoolkit(
analysis_output: AnalysisOutput,
) -> None:
"""Outputs the analysis output using ScrapingToolKit."""
for component_type in analysis_output["component_types"]:
Evidence.Add.COMPONENT_TYPE(
identifier=component_type,
)
for format_ in analysis... | 5,348,281 |
def ticket_qr_code(request, ticket_id):
""" Generates a qr code data url to validate a ticket with the id passed """
return segno.make(
validate_ticket_url(request, ticket_id),
micro=False
).svg_data_uri(scale=2) | 5,348,282 |
def add_to_histogram(key, histogram):
"""
stop bugging me
"""
if key in histogram:
histogram[key] = int(histogram[key]) + 1
else:
histogram[key] = 1 | 5,348,283 |
def test_prefix_printer_prefix_whitespace(prefix_string, capsys, text_string):
"""Test if prefix_printer has the correct prefix."""
p_test = prefix_printer(prefix=f"{prefix_string}", whitespace=4)
p_test(text_string)
captured = capsys.readouterr()
assert captured.out == f"[{prefix_string.upper()}]: ... | 5,348,284 |
def _iou(box_a, box_b):
"""
:param box_a: [c, A, 4]
:param box_b: [c, B, 4]
:return: [c, A, B] 两两之间的iou
"""
# 变成左上角坐标、右下角坐标
boxes1 = tf.concat([box_a[..., :2] - box_a[..., 2:] * 0.5,
box_a[..., :2] + box_a[..., 2:] * 0.5], axis=-1)
boxes2 = tf.concat([box... | 5,348,285 |
def subsequent_mask(size, device=device):
"""
Mask out subsequent positions. upper diagonal elements should be zero
:param size:
:return: mask where positions are filled with zero for subsequent positions
"""
# upper diagonal elements are 1s, lower diagonal and the main diagonal are zeroed
t... | 5,348,286 |
def read_gcs_file_if_exists(gcs_client: storage.Client,
gsurl: str) -> Optional[str]:
"""return string of gcs object contents or None if the object does not exist
"""
try:
return read_gcs_file(gcs_client, gsurl)
except google.cloud.exceptions.NotFound:
return ... | 5,348,287 |
def collapse_multigraph_to_nx(
graph: Union[gr.MultiDiGraph, gr.OrderedMultiDiGraph]) -> nx.DiGraph:
""" Collapses a directed multigraph into a networkx directed graph.
In the output directed graph, each node is a number, which contains
itself as node_data['node'], while each edge contains ... | 5,348,288 |
def main(path_images, dimension, overwrite, nb_workers):
""" main entry point
:param path_images: path to images
:param int dimension: for 2D inages it is 0 or 1
:param bool overwrite: whether overwrite existing image on output
:param int nb_workers: nb jobs running in parallel
"""
image_pa... | 5,348,289 |
def validate_inputs(scenario_id, subscenarios, subproblem, stage, conn):
"""
Get inputs from database and validate the inputs
:param subscenarios: SubScenarios object with all subscenario info
:param subproblem:
:param stage:
:param conn: database connection
:return:
"""
pass
# V... | 5,348,290 |
def get_encoder_type(encoder_name):
""" gets the class of the encoer of the given name """
if encoder_name == 'Dense':
return DenseEncoder
elif encoder_name == 'CNN':
return CNNEncoder
else:
raise ValueError(encoder_name) | 5,348,291 |
def stateless_truncated_normal(shape,
seed,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
name=None):
"""Outputs deterministic pseudorandom values, truncated normall... | 5,348,292 |
def mean(l):
"""
Returns the mean value of the given list
"""
sum = 0
for x in l:
sum = sum + x
return sum / float(len(l)) | 5,348,293 |
def send_arduinos(packet : bytes):
"""Sends packets to light controllers."""
for ip in config.ARDUINO_IPS:
try:
_sock.sendto(packet,(ip, config.UDP_PORT))
except Exception:
continue | 5,348,294 |
def daqmx_tsm_s(tsm, tests_pins):
"""Returns LabVIEW Cluster equivalent data"""
print(tests_pins)
daqmx_tsms = []
sessions = []
for test_pin_group in tests_pins:
print(test_pin_group)
data = ni_daqmx.pins_to_session_sessions_info(tsm, test_pin_group)
daqmx_tsms.append(data)
... | 5,348,295 |
def tryLoadingFrom(tryPath,moduleName='swhlab'):
"""if the module is in this path, load it from the local folder."""
if not 'site-packages' in swhlab.__file__:
print("loaded custom swhlab module from",
os.path.dirname(swhlab.__file__))
return # no need to warn if it's already outsi... | 5,348,296 |
def test_show_fiff():
"""Test show_fiff."""
# this is not exhaustive, but hopefully bugs will be found in use
info = show_fiff(fname_evoked)
keys = ['FIFF_EPOCH', 'FIFFB_HPI_COIL', 'FIFFB_PROJ_ITEM',
'FIFFB_PROCESSED_DATA', 'FIFFB_EVOKED', 'FIFF_NAVE',
'FIFF_EPOCH']
assert (a... | 5,348,297 |
def create(
trial_def: Type[det.Trial],
config: Optional[Dict[str, Any]] = None,
local: bool = False,
test: bool = False,
context_dir: str = "",
command: Optional[List[str]] = None,
master_url: Optional[str] = None,
) -> Any:
# TODO: Add a reference to the local development tutorial.
... | 5,348,298 |
def collapse_quadratic(velax, data, rms):
"""
Collapse the cube using the quadratic method presented in `Teague &
Foreman-Mackey (2018)`_. Will return the line center, ``v0``, and the
uncertainty on this, ``dv0``, as well as the line peak, ``Fnu``, and the
uncertainty on that, ``dFnu``. This provide... | 5,348,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.