content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_api_analysis_generation(analysis):
"""
Runs full analysis workflow (with GMM clustering).
"""
working_folder = "full_analysis"
check_remove_folder(working_folder)
n_clusts = 3
analysis.generate(working_folder, "gaussianmixture", analysis_nclust=n_clusts)
# Check if reports exis... | 39,200 |
def _make_experiment(exp_id=1, path="./Results/Tmp/test_FiftyChain"):
"""
Each file specifying an experimental setup should contain a
make_experiment function which returns an instance of the Experiment
class with everything set up.
@param id: number used to seed the random number generators
@p... | 39,201 |
def main():
""" main """
start = time.time()
_load_arxiv_demo()
end = time.time()
minutes = round((end-start)/60)
print("Total time required:", minutes, "minutes", round((end-start)%60, 1), "seconds") | 39,202 |
def find_largest_digit_helper(n, max_n=0):
"""
:param n: int,待判別整數
:param max_n: int,當下最大整數值
:return: int,回傳n中最大之 unit 整數
"""
# 特殊情況:已達最大值9,就不需再比了
if n == 0 or max_n == 9:
return max_n
else:
# 負值轉換為正值
if n < 0:
n *= -1
# 用餘數提出尾數
unit_n = n % 10
# 尾數比現在最大值
if unit_n > max_n:
max_n = unit_n
... | 39,203 |
def build_stats(loss, eval_result, time_callback):
"""Normalizes and returns dictionary of stats.
Args:
loss: The final loss at training time.
eval_result: Output of the eval step. Assumes first value is eval_loss and
second value is accuracy_top_1.
time_callback: Time track... | 39,204 |
def write_feature_to_file(filename, locs, desc):
""" 将特征位置和描述子保存到文件中"""
savetxt(filename, hstack((locs, desc))) | 39,205 |
def run_test_is_pressed(touch_sensor):
"""
Tests the is_pressed method of the TouchSensor class.
:type touch_sensor: touch.TouchSensor
"""
print()
print("--------------------------------------------------")
print("Testing the is_pressed method")
print(" of the TouchSenso... | 39,206 |
def test_track_tag_mat_view(app):
"""Tests that genre metrics can be queried"""
with app.app_context():
db = get_db()
test_entities = {
"tracks": [
{"track_id": 1, "tags": "", "owner_id": 1},
{"track_id": 2, "owner_id": 1, "tags": "pop,rock,electric"},
{"... | 39,207 |
def random_resource_code2() -> str:
"""One random book name chosen at random. This fixture exists so
that we can have a separate book chosen in a two language document
request."""
book_ids = list(bible_books.BOOK_NAMES.keys())
return random.choice(book_ids) | 39,208 |
def _to_str(value):
"""Helper function to make sure unicode values are converted to UTF-8.
Args:
value: String or Unicode text to convert to UTF-8.
Returns:
UTF-8 encoded string of `value`; otherwise `value` remains unchanged.
"""
if isinstance(value, unicode):
return value.encode('utf-8')
ret... | 39,209 |
def __forward(
tzolkin: TzolkinDate, num_results: int, ret_val: List[datetime.date]
) -> None:
"""Search backwards in time for Tzolkin date `tzolkin` and append to the list.
Args:
tzolkin (TzolkinDate): The Tzolkin date to search for.
num_results (int): The number of dates to search.
... | 39,210 |
def get_loss(loss_name):
"""Get loss from LOSS_REGISTRY based on loss_name."""
if not loss_name in LOSS_REGISTRY:
raise Exception(NO_LOSS_ERR.format(
loss_name, LOSS_REGISTRY.keys()))
loss = LOSS_REGISTRY[loss_name]
return loss | 39,211 |
def collate_fn(batch):
"""
Data collater.
Assumes each instance is a dict.
Applies different collation rules for each field.
Args:
batches: List of loaded elements via Dataset.__getitem__
"""
collated_batch = {}
# iterate over keys
for key in batch[0]:
try:
... | 39,212 |
def _rec_eval_in(g, a, v, i, j, K):
"""Recursive helper for :func:`dmp_eval_in`."""
if i == j:
return dmp_eval(g, a, v, K)
v, i = v - 1, i + 1
return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in g ], v) | 39,213 |
def test_nb4jupyter_metadata(validator_name):
"""Test that a notebook with a jupyter metadata passes validation"""
set_validator(validator_name)
with TestsBase.fopen(u'test4jupyter_metadata.ipynb', u'r') as f:
nb = read(f, as_version=4)
validate(nb)
assert isvalid(nb) | 39,214 |
def normalize(array):
"""
Normalize a 4 (or Nx4) element array/list/numpy.array for use as a quaternion
:param array: 4 or Nx4 element list/array
:returns: normalized array
:rtype: numpy array
"""
quat = np.array(array)
return np.squeeze(quat / np.sqrt(np.sum(quat * quat, axis=-1, keep... | 39,215 |
def dose_class_baseline(dose_num, df_test, df_targets):
"""Calculate the PR- baseline for each dose treatment"""
dose_cpds_index = df_test[df_test['dose'] == dose_num].index
df_class_targets = df_targets.loc[dose_cpds_index].reset_index(drop = True)
class_baseline_score = calculate_baseline(df_class_targets)
... | 39,216 |
def xrange(mn: int, mx: int = None) -> list:
"""Built-in range function, but actually gives you a range between mn and mx.
Range: range(5) -> [0, 1, 2, 3, 4]
XRange: xrange(5) -> [0, 1, 2, 3, 4, 5]"""
return list(range(0 if mx is None else mn, mn + 1 if mx is None else mx + 1)) | 39,217 |
def stage_per_sample_specific_statics(opts, sample_ids):
"""Items like the Latex templates
Parameters
----------
opts : dict
A dict of relevant opts.
sample_ids : Iterable of str
A list of sample IDs of interest
Returns
-------
dict
A dict containing each sample... | 39,218 |
def rw_shebangs(root):
""" This finds and rewrites shebang lines that point to a non-standard Python executable.
The new shebang points to the equivalent Python executable from a "standard" system Python installation
(ie, "/usr/bin/python*").
root is the abs path to $(chpl_home)/third-party/chpl-ven... | 39,219 |
def sous_tableaux(arr: list, n: int) -> list:
"""
Description:
Découper un tableau en sous-tableaux.
Paramètres:
arr: {list} -- Tableau à découper
n: {int} -- Nombre d'éléments par sous-tableau
Retourne:
{list} -- Liste de sous-tableaux
Exemple:
>>> sous_ta... | 39,220 |
def get_previous_tweets(date_entry):
"""Return details about previous Tweets. Namely, retrieve details
about the date_entry-th Tweets from 7 days ago, 30 days ago, and a
random number of days ago.
If a given Tweet does not exist, its corresponding entry in the
output will be empty.
Args:
... | 39,221 |
def changed_cat_keys(dt):
"""Returns keys for categories, changed after specified time"""
return [root_category_key()] | 39,222 |
def modelStep2(inputdir):
"""
Run accordJP pipeline, starting launch model setup step 2
As of this moment, JYL -- FIXME
Print INPUTDIR if the directory exists.
"""
click.echo(click.format_filename(inputdir))
analysisPipeline.launchModelStep2(inputdir) | 39,223 |
def create_client(CLIENT_ID, CLIENT_SECRET):
"""Creates Taboola Client object with the given ID and secret."""
client = TaboolaClient(CLIENT_ID, client_secret=CLIENT_SECRET)
return client | 39,224 |
def set_values_at_of_var_above_X_lat_2_avg(lat_above2set=65, ds=None,
use_avg_at_lat=True, res='0.125x0.125',
var2set=None,
only_consider_water_boxes=True,
... | 39,225 |
def tag(ctx, whatever):
"""legacy_lain functionality, for lain4 clusters, you don't need to
manually tag"""
legacy_lain('tag', *whatever) | 39,226 |
def vzc_dict(svy):
"""
vizier column dictionary
dictionary for NVSS, TGSS column using vizier
TODO: add column for errors too
"""
columns = {'tgss': ['RAJ2000', 'DEJ2000', 'Maj', 'Min', 'PA'],
'nvss': ['RAJ2000', 'DEJ2000', 'MajAxis', 'MinAxis', 'PA', '+NVSS']
}
... | 39,227 |
def link_predict(predictions, truth):
"""
predictions : torch.Tensor, similarity matrix of shape (batch_size, entity_count)
truth: torch.Tensor, vector of length (BatchSize)
"""
pass | 39,228 |
def _plot_xkcd(plot_func, *args, **kwargs):
""" Plot with *plot_func*, *args* and **kwargs*, but in xkcd style. """
with plt.xkcd():
fig = plot_func(*args, **kwargs)
return fig | 39,229 |
def unfollow_user():
"""UnfollowUser"""
auth = request.headers
user = request.args.get('userId')
req = requests.post(
'/api/v1/IsAuthenticated',
{'id': auth['Authorization']}
)
req.json()
if req.authenticated:
cur = MY_SQL.connection.cursor()
cur.execute(
... | 39,230 |
def isOverlaysEnabled():
"""Returns whether or not the current client's quality overlay
system is currently enabled.
Returns:
bool: True (1) if overlays are currently enabled.
"""
return False | 39,231 |
def load_image(path, size=None, grayscale=False):
"""
Load the image from the given file-path and resize it
to the given size if not None.
"""
# Load the image using opencv
if not grayscale: # BGR format
image = cv2.imread(path)
else: # grayscale format
image = cv2.imread(... | 39,232 |
def brent_min(f, bracket, fnvals=None, tolerance=1e-6, max_iterations=50):
"""\
Given a univariate function f and a tuple bracket=(x1,x2,x3) bracketing a minimum,
find a local minimum of f (with fn value) using Brent's method.
Optionally pass in the tuple fnvals=(f(x1),f(x2),f(x3)) as a parameter.
"""
x1, x2, x3 = b... | 39,233 |
def test_config_load3():
""" test config many shards with many replicas """
print test_config_load3.__name__
test_config_file = BytesIO()
# non ordered
append_to_file_mongo_setting(test_config_file, 'mongo-oplog-shard2-rs1')
append_to_file_mongo_setting(test_config_file, 'mongo-oplog-shard2-rs2'... | 39,234 |
def best_validity(source):
"""
Retrieves best clustering result based on the relative validity metric
"""
# try:
cols = ['min_cluster_size', 'min_samples', 'validity_score', 'n_clusters']
df = pd.DataFrame(source, columns = cols)
df['validity_score'] = df['validity_score'].fillna(0)
bes... | 39,235 |
def normalize_cell_value(value):
"""Process value for writing into a cell.
Args:
value: any type of variable
Returns:
json serialized value if value is list or dict, else value
"""
if isinstance(value, dict) or isinstance(value, list):
return json.dumps(value)
return va... | 39,236 |
def clear():
"""Clears the current context figure of all marks axes and grid lines."""
fig = _context['figure']
if fig is not None:
fig.marks = []
fig.axes = []
setattr(fig, 'axis_registry', {})
_context['scales'] = {}
key = _context['current_key']
if key is n... | 39,237 |
def _ancestry2paths(A):
"""Convert edge x edge ancestry matrix to tip-to-tip path x edge
split metric matrix. The paths will be in the same triangular matrix order
as produced by distanceDictAndNamesTo1D, provided that the tips appear in
the correct order in A"""
tips = [i for i in range(A.shape... | 39,238 |
def test_analyze_crash_lint(config):
"""The lint checker crashes."""
FakeChecker = create_fake_checker(
check_type=CheckType.lint, name="name", text="text", url="url"
)
def raises(*a):
raise ValueError
FakeChecker.run = raises
with patch("charmcraft.linters.CHECKERS", [FakeChe... | 39,239 |
def geometric_mean(x, axis=-1, check_for_greater_than_zero=True):
"""
Return the geometric mean of matrix x along axis, ignore NaNs.
Raise an exception if any element of x is zero or less.
"""
if (x <= 0).any() and check_for_greater_than_zero:
msg = 'All elements of x (except NaNs... | 39,240 |
def export_deck(database, deckname):
"""Export a deck from the database
arguments:
database - filepath for the sqlite database file
deckname - name of the deck to load in in
yields: lines
"""
logging.info('exporting deck...')
sq, c = get_db(database)
logging.info('getting deck info... | 39,241 |
def test_combined_preprocessing_mislabeled_coords():
"""Test if the renaming is applied to datavariables and then if they are moved to the coords."""
# create a 2d dataset
xlen, ylen, zlen = (10, 5, 1)
ds = create_test_ds("x", "y", "dummy", xlen, ylen, zlen).squeeze().drop("dummy")
ds = ds.assign(de... | 39,242 |
def mongodb():
"""
Simple form to get and set a note in MongoDB
"""
return None | 39,243 |
def get_single_blog(url):
"""Получить блог по указанному url"""
blog = Blog.get_or_none(Blog.url == url)
if blog is None:
return errors.not_found()
user = get_user_from_request()
has_access = Blog.has_access(blog, user)
if not has_access:
return errors.no_access()
blog_dic... | 39,244 |
def update(
schedule_id: uuid.UUID = typer.Argument(
..., help="The ID for the schedule to update"
),
name: str = typer.Option(..., help="A name for this schedule"),
description: str = typer.Option(..., help="A description for this schedule"),
schedule: str = typer.Option(
...,
... | 39,245 |
def test_section():
"""Returns a testing scope context to be used in 'with' statement
and captures testing code.
Example::
with autograd.train_section():
y = model(x)
compute_gradient([y])
with autograd.test_section():
# testing, IO, gradient upda... | 39,246 |
async def get_installation_owner(metadata_account_id: int,
mdb_conn: morcilla.core.Connection,
cache: Optional[aiomcache.Client],
) -> str:
"""Load the native user ID who installed the app."""
user_login = await m... | 39,247 |
def test_binop_fail(py_c_vec):
"""Test binary operations with invalid operands."""
Vec, Angle, Matrix, parse_vec_str = py_c_vec
vec = Vec()
operations = [
op.add, op.iadd,
op.sub, op.isub,
op.truediv, op.itruediv,
op.floordiv, op.ifloordiv,
op.mul, op.imul,
... | 39,248 |
def get_cflags():
"""Get the cflag for compile python source code"""
flags = ['-I' + get_path('include'),
'-I' + get_path('platinclude')]
flags.extend(getvar('CFLAGS').split())
# Note: Extrat cflags not valid for cgo.
for not_go in ('-fwrapv', '-Wall'):
if not_go in flags:
... | 39,249 |
def request_post_json(url, headers, data):
"""Makes a POST request and returns the JSON response"""
try:
response = requests.post(url, headers=headers, data=data, timeout=10)
if response.status_code == 201:
return response.json()
else:
error_message = None
... | 39,250 |
def get_rand_number(min_value, max_value):
"""
This function gets a random number from a uniform distribution between
the two input values [min_value, max_value] inclusively
Args:
- min_value (float)
- max_value (float)
Return:
- Random number between this range (float)
"""
range... | 39,251 |
def test_remove_moderator(api_client):
"""This should remove a moderator from a channel"""
resp = api_client.channels.remove_moderator("a_channel", "01BSRT7XMQT33SCNKTYTSES5QQ")
assert resp.status_code == 204 | 39,252 |
def detect_callec(tree):
"""Collect names of escape continuations from call_ec invocations in tree.
Currently supported and unsupported cases::
# use as decorator, supported
@call_ec
def result(ec): # <-- we grab name "ec" from here
...
# use directly on a literal... | 39,253 |
def _get_good_pport_list(sriov_adaps, pports, capacity, redundancy,
check_link_status, redundant_pports=None):
"""Get a list of SRIOV*PPort filtered by capacity and specified pports.
Builds a list of pypowervm.wrappers.iocard.SRIOV*PPort from sriov_adaps
such that:
- Only ports... | 39,254 |
def read(string):
""" Given a single interval from a GFFv2 file, returns an Interval object.
Will return meta lines if they start with #, track, or browser. """
if string.startswith(metalines):
return interval(_is_meta=True, seqname=string)
values = []
cols = string.split(delimiter)
fo... | 39,255 |
def imprimirTextoCentrado(texto, tamanoTexto, relleno=" "):
"""
Imprime el texto especificado de manera centra, flanqueando el texto
con el carácter de relleno especificado.
"""
print (texto.center(tamanoTexto, relleno)) | 39,256 |
def average_results(results_path: Union[Path, str], split_on: str = " = ") -> Dict[str, float]:
"""
Average accuracy values from a file.
Parameters
----------
results_path : Union[Path, str]
The file to read results from.
split_on : str
The symbol which separates an accuracy's k... | 39,257 |
def absPath(myPath):
"""Get absolute path to resource, works for dev and for PyInstaller"""
import sys
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
lprint("found MEIPASS: %s " % os.path.join(base_path, os.path.basename(myPath)))
... | 39,258 |
def dict_collection_only(method):
"""
Handles the behavior when a group is present on a clumper object.
"""
@wraps(method)
def wrapped(clumper, *args, **kwargs):
if not clumper.only_has_dictionaries:
non_dict = next(d for d in clumper if not isinstance(d, dict))
rais... | 39,259 |
def cmd_connection_delete(context, name):
"""
Delete a connection definition from the set of connections defined.
This may be either defined by the optional name parameter or if there
is no name provided, a select list will be presented for the user
to select the connection to be deleted.
"""
... | 39,260 |
def country_name(country_id):
"""
Returns a country name
>>> country_name(198)
u'Spain'
"""
if country_id == '999':
#Added for internal call - ie flag/phone.png
return _('internal call').title()
try:
obj_country = Country.objects.get(id=country_id)
return obj... | 39,261 |
def parse_mjinfo():
"""List up game history stored in Flash cache directory
Returns
-------
dict
Key : str
File name in which data are stored
Value : list of dict
Information of logs. See :func:`parse_sol`.
"""
if sys.platform == 'darwin':
root_di... | 39,262 |
def multiply(input_op_node: cc_dag.OpNode, output_name: str, target_col_name: str, operands: list):
"""
Define Multiply operation.
:param input_op_node: Parent node for the node returned by this method.
:param output_name: Name of returned Multiply node.
:param target_col_name: Name of column that ... | 39,263 |
def download_clip_wrapper(
row, label_to_dir, trim_format, tmp_dir, existing_files: Dict[str, Path] = {}
):
"""Wrapper for parallel processing purposes."""
output_filename = construct_video_filename(row, label_to_dir)
clip_id = os.path.basename(output_filename).split(".mp4")[0]
if clip_id in existi... | 39,264 |
def test_random_poly_game(players, strategies, functions, inp, weight, deg): # pylint: disable=too-many-arguments
"""Test poly aggfn"""
aggfn_verify(gamegen.poly_aggfn(players, strategies, functions))
aggfn_verify(gamegen.poly_aggfn(
players, strategies, functions, input_prob=inp, weight_prob=weight... | 39,265 |
def list_subdir(path):
""" list all subdirectories given a directory"""
return [o for o in os.listdir(path) if os.path.isdir(path / o)] | 39,266 |
def update_jira(vulnerability_dictionary, config):
"""
Feeds JIRA with issues based on the vulnerability dictionary.
:param vulnerability_dictionary: dictionary of vulnerabilities
:param config: confiture object that contains the quart configuration.
:return: int, number of issues created/updat... | 39,267 |
def build_task_file(task_id, file_input_path, file_input_size,
file_key_path, file_key_size, file_output_path,
file_output_size, process_type):
"""
Build a temporary task file using the Erfr task ID containing the
relevant information of the corresponding encr... | 39,268 |
def RegisterErrorHandlers(app):
"""Registers the error handlers in the flask app.
Args:
app: Flask application to register the handlers.
"""
app.register_error_handler(ValueError, ValueErrorMessage)
app.register_error_handler(KeyError, KeyErrorMessage)
app.register_error_handler(NotImplementedError, No... | 39,269 |
def KLdist(P,Q):
"""
KLDIST Kullbach-Leibler distance.
D = KLDIST(P,Q) calculates the Kullbach-Leibler distance (information
divergence) of the two input distributions.
"""
P2 = P[P*Q>0]
Q2 = Q[P*Q>0]
P2 = P2 / np.sum(P2)
Q2 = Q2 / np.sum(Q2)
D = np.sum(P2*np.log(P2/Q2))
... | 39,270 |
def get_args():
"""Get arguments from CLI"""
parser = argparse.ArgumentParser(
description="""\nRuns Stacks process_radtags on each plate in barcodes.txt file""")
parser.add_argument(
"--Read1",
required=True,
action=FullPaths,
help="""Path to Read... | 39,271 |
def homepage(request: HttpRequest) -> HttpResponse:
""" Render the home page of the application. """
context = make_context(request)
person = get_person(TARGET_NICK)
if not person:
return render(request, "404.html", status=404)
context["person"] = person
technology_set = person.technol... | 39,272 |
def _call_rmat(scale, num_edges, create_using, mg):
"""
Simplifies calling RMAT by requiring only specific args that are varied by
these tests and hard-coding all others.
"""
return rmat(scale=scale,
num_edges=num_edges,
a=0.1,
b=0.2,
c... | 39,273 |
def value_loss(old_value):
"""value loss for ppo"""
def loss(y_true, y_pred):
vpredclipped = old_value + K.clip(y_pred - old_value, -LOSS_CLIPPING, LOSS_CLIPPING)
# Unclipped value
vf_losses1 = K.square(y_pred - y_true)
# Clipped value
vf_losses2 = K.square(vpredclipped -... | 39,274 |
def split_by_worker(urls):
"""Selects a subset of urls based on Torch get_worker_info.
Used as a shard selection function in Dataset."""
import torch
urls = [url for url in urls]
assert isinstance(urls, list)
worker_info = torch.utils.data.get_worker_info()
if worker_info is not None:
... | 39,275 |
def concatenate_child_attributes_to_parent(child_data=None,
parent_attribute=""):
"""
:param child_data:
:param parent_attribute:
:return:
"""
global concatenated_json
if isinstance(child_data, dict):
for attribute in child_data:
... | 39,276 |
def show(resource: str) -> None:
"""Show resources"""
if resource == 'config':
show_resource('conf.d/line_item_manager.yml')
if resource == 'template':
show_resource('conf.d/line_item_template.yml')
if resource == 'bidders':
print("%-25s%s" % ('Code', 'Name'))
print("%-25... | 39,277 |
def cpu_count():
"""Get the available CPU count for this system.
Takes the minimum value from the following locations:
- Total system cpus available on the host.
- CPU Affinity (if set)
- Cgroups limit (if set)
"""
count = os.cpu_count()
# Check CPU affinity if available
if psutil... | 39,278 |
def zoom_and_rotate_video(vid: videoType,
zoom: float,
rotate: float = 0,
show: bool = True,
save_name: str = "") -> None:
"""Zoom and rotate each frame of video, save new array (return new video array?)"""
f... | 39,279 |
def runge_kutta4(y, x, dx, f):
"""computes 4th order Runge-Kutta for dy/dx.
Parameters
----------
y : scalar
Initial/current value for y
x : scalar
Initial/current value for x
dx : scalar
difference in x (e.g. the time step)
f : ufunc(y,x)
Callable function ... | 39,280 |
def histplot(x_col, data, bins='auto', x_label=None, x_rot=0,
x_ticks=None, x_tick_lab=None, xmin=1, xmax=10,
y_label=None, y_rot=0, y_ticks=None,
y_tick_lab=None, y_min=0, y_max=None,
title=None, save_name=None, cum=False,
stat='probability', figsiz... | 39,281 |
def genBinaryFileRDD(sc, path, numPartitions=None):
"""
Read files from a directory to a RDD.
:param sc: SparkContext.
:param path: str, path to files.
:param numPartition: int, number or partitions to use for reading files.
:return: RDD with a pair of key and value: (filePath: str, fileData: Bina... | 39,282 |
def test_immutable_literals(doctest):
"""
> (immutable? "abc")
#t
""" | 39,283 |
def generate():
"""
Generate a classic image quote
:rtype: InspiroBotImageResponse
:return: The generated response
"""
try:
r = requests.get("{}?generate=true".format(url()))
except:
raise InsprioBotError("API request failed. Failed to connect")
if r.status_code != 200:
... | 39,284 |
def describe_tasks(cluster=None, tasks=None):
"""
Describes a specified task or tasks.
See also: AWS API Documentation
Examples
This example provides a description of the specified task, using the task UUID as an identifier.
Expected Output:
:example: response = client.describe_tas... | 39,285 |
def convert_avgpool(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert Average pooling.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionar... | 39,286 |
def inference_lstm(im_path, model_path, tok_path, max_cap_len=39):
"""
Perform inference using a model trained to predict LSTM.
"""
tok = pickle.load(open(tok_path, 'rb'))
model = load_model(
model_path,
custom_objects={'RepeatVector4D': RepeatVector4D})
encoder = ImageEncoder(ra... | 39,287 |
def iterative_proof_tree_bfs(rules_dict: RulesDict, root: int) -> Node:
"""Takes in a iterative pruned rules_dict and returns iterative proof
tree."""
root_node = Node(root)
queue = deque([root_node])
while queue:
v = queue.popleft()
rule = sorted(rules_dict[v.label])[0]
if n... | 39,288 |
def get_host_buffer_init(arg_name, num_elem, host_data_type, host_init_val):
"""Get host code snippet: init host buffer"""
src = get_snippet("snippet/clHostBufferInit.txt")
src = src.replace("ARG_NAME", arg_name)
src = src.replace("NUM_ELEM", str(num_elem))
src = src.replace("HOST_DATA_TYPE", host_d... | 39,289 |
def get_setting(setting, override=None):
"""Get setting.
Get a setting from `muses` conf module, falling back to
the default.
If override is not None, it will be used instead of the setting.
:param setting: String with setting name
:param override: Value to use when no setting is available. D... | 39,290 |
def extract_year_month_from_key(key):
"""
Given an AWS S3 `key` (str) for a file,
extract and return the year (int) and
month (int) specified in the key after
'ano=' and 'mes='.
"""
a_pos = key.find('ano=')
year = int(key[a_pos + 4:a_pos + 8])
m_pos = key.find('mes=')
month... | 39,291 |
def to_time_zone(self):
"""Check the toTimeZone() function with DateTime64 extended range."""
stress = self.context.stress
timezones = timezones_range(stress)
for year in years_range(stress):
with Given(f"I select datetimes in {year}"):
datetimes = select_dates_in_year(year=year, st... | 39,292 |
def depolarize(p: float) -> DepolarizingChannel:
"""Returns a DepolarizingChannel with given probability of error.
This channel applies one of four disjoint possibilities: nothing (the
identity channel) or one of the three pauli gates. The disjoint
probabilities of the three gates are all the same, p /... | 39,293 |
def verilog_to_circuit(
netlist,
name,
infer_module_name=False,
blackboxes=None,
warnings=False,
error_on_warning=False,
fast=False,
):
"""
Creates a new Circuit from a module inside Verilog code.
Parameters
----------
netlist: str
Verilog code.
name: str... | 39,294 |
def load_all_channels(event_id=0):
"""Returns a 3-D dataset corresponding to all the electrodes for a single subject
and a single event. The first two columns of X give the spatial dimensions, and
the third dimension gives the time."""
info = load_waveform_data(eeg_data_file())
locs = load_channel_l... | 39,295 |
def parentheses_cleanup(xml):
"""Clean up where parentheses exist between paragraph an emphasis tags"""
# We want to treat None's as blank strings
def _str(x):
return x or ""
for em in xml.xpath("//P/*[position()=1 and name()='E']"):
par = em.getparent()
left, middle, right = _st... | 39,296 |
def filter_atoms(coordinates, num_atoms=None, morphology="sphere"):
"""
Filter the atoms so that the crystal has a specific morphology with a given number of atoms
Params:
coordinates (array): The atom coordinates
num_atoms (int): The number of atoms
morphology (str): The morphology... | 39,297 |
async def async_test_temperature(opp, cluster, entity_id):
"""Test temperature sensor."""
await send_attributes_report(opp, cluster, {1: 1, 0: 2900, 2: 100})
assert_state(opp, entity_id, "29.0", TEMP_CELSIUS) | 39,298 |
def predict_timeslice_single(vis: Visibility, model: Image, predict=predict_2d, remove=True,
gcfcf=None, **kwargs) -> Visibility:
""" Predict using a single time slices.
This fits a single plane and corrects the image geometry.
:param vis: Visibility to be predicted
:param... | 39,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.