content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def cancel_job(task_id):
"""Calls :meth:`cancel_job <Scheduler.cancel_job>` on the
:data:`default scheduler instance <default_scheduler>`.
"""
default_scheduler.cancel_job(task_id) | 5,309,500 |
def calculate_pct_poi_msgs(series):
"""calculates the percentage of a potential POI's
total messages that are to or from a POI
Args:
series (pandas.core.series.Series): data series associated with a single POI
Returns:
[pandas.core.series.Series]: data series with the added POI mess... | 5,309,501 |
def clear_cache(location):
"""
Remove selected cached data, please run malaya_speech.print_cache() to get path.
Parameters
----------
location : str
Returns
-------
result : boolean
"""
if not isinstance(location, str):
raise ValueError('location must be a string')
... | 5,309,502 |
def test_has_can_find_sections_and_keys(templated_config_file, key):
"""
config_file.config_file.ConfigFile.has
Ensure that when a section or key that exists
is passed to has(), it can find it and returns True.
"""
config = templated_config_file()
assert config.has(key)
assert key in co... | 5,309,503 |
def version():
"""
Get the Vagrant version.
"""
with settings(hide('running', 'warnings'), warn_only=True):
res = local('vagrant --version', capture=True)
if res.failed:
return None
line = res.splitlines()[-1]
version = re.match(r'Vagrant (?:v(?:ersion )?)?(.*)', line).group(... | 5,309,504 |
def aggrmem(mems):
"""Aggregates memory information returned from keymem().
If mems is a dict, uses its values() only.
If mems is a list, uses it directly.
Returns a single memory structure, formatted just like keymem():
- keys: list of key names
- types: list of types, corresponding to ... | 5,309,505 |
def create_ir():
"""
Read out the ir to compare it before and after adding a flag from the pass
to the sequence or work with its returnings.
"""
complete_ir = mktemp("-p", local.cwd)
complete_ir = complete_ir.rstrip('\n')
return complete_ir | 5,309,506 |
def _dist_obs_oracle(oracle, query, trn_list):
"""A helper function calculating distances between a feature and frames in oracle."""
a = np.subtract(query, [oracle.f_array[t] for t in trn_list])
return (a * a).sum(axis=1) | 5,309,507 |
def test_make_grid(hspace):
"""Test that different dimension types are supported"""
flattened_space = flatten_space(hspace)
assert list(make_grid(flattened_space["x"], 7)) == [0, 1, 2, 3, 4, 5, 6]
numpy.testing.assert_almost_equal(
make_grid(flattened_space["y[0]"], 4), [1, 2, 3, 4], decimal=4
... | 5,309,508 |
def bond_zh_hs_cov_daily(symbol: str = "sz123111") -> pd.DataFrame:
"""
新浪财经-债券-沪深可转债的历史行情数据, 大量抓取容易封 IP
http://vip.stock.finance.sina.com.cn/mkt/#hskzz_z
:param symbol: 沪深可转债代码; e.g., sh010107
:type symbol: str
:return: 指定沪深可转债代码的日 K 线数据
:rtype: pandas.DataFrame
"""
r = requests.get... | 5,309,509 |
def test_editorstate_finalstate():
"""check the computed final state matches the final state"""
test_set = get_json_records_with_finalstate("data")
for json_file, final_file in test_set:
es.doc_lines = []
es.apply_doc_edit_calls = -1
final_state = open(final_file).read()
comp... | 5,309,510 |
def predict_m(m, f, g, c0, alpha, B, pv, e, mu, R, eta):
"""
Calculate a predicted m given an input m. The idea is that we can iterate until they match.
Inputs:
parameters, m
Outputs:
predicted m
predicted establishment fraction
predicted mutation rate
predicted mean time ... | 5,309,511 |
def msg_encoder( encoding=None ):
""" 返回一个 with a pair of functions to encode/decode 消息 的命名元组。
如果 encoding 为None , 将返回 a pass through function 。 """
Codec = namedtuple( 'Codec', ['enc','dec'] )
if encoding in (None,False):
l = lambda x : unicode(x)
return Codec(l,l)
else:
... | 5,309,512 |
def test_cut_path_into_segments(settings, path, segments):
"""Cut a path into segments"""
resolver = PathBreadcrumbResolver(settings.ROOT_URLCONF)
assert resolver.cut(path) == segments | 5,309,513 |
def test_get_sync_policy_by_id_false():
"""Will return a list of sync policies (Wrong password).
:return: Should return: False
"""
syn = syncope.Syncope(syncope_url="http://192.168.1.145:9080", username="admin", password="passwrd")
assert syn.get_sync_policy_by_id(5) == False | 5,309,514 |
def is_dataframe_column_numeric(dataset : pd.DataFrame, column : str) -> bool:
"""
Return True if column in dataset is float or int (numeric), otherwise False
Parameters
----------
dataset : pandas.DataFrame
the dataframe that contains at least the column "column"
column : str
n... | 5,309,515 |
def dylan_string(value):
"""Assuming value is a Dylan string, return it as a Python str"""
if dylan_is_byte_string(value):
return dylan_byte_string_data(value).decode('utf-8')
elif dylan_is_unicode_string(value):
data = dylan_unicode_string_data(value)
(int_size, data_format) = target_address_format(v... | 5,309,516 |
def read_CUB(train_list_file, test_list_file):
""" Reads and parses examples from CUB dataset """
img_height = 227
img_width = 227
num_val_img = 500 # you can change the number of validation images here
train_img = []
train_label = []
test_img = []
test_label = []
train_img, tra... | 5,309,517 |
def mediatailor_configuration_ddb_items(region):
"""
Retrieve and format MediaTailor configuration for cache storage.
"""
items = []
for config in mediatailor_configurations(region):
arn = config["PlaybackConfigurationArn"]
service = "mediatailor-configuration"
items.append(n... | 5,309,518 |
def main():
"""
Función que calcula e imprime la suma de todos los números primos menores o iguales a 5,000,000
haciendo uso de procesos paralelos.
"""
n = 5000000
lst = []
for i in range(1,n+1):
lst.append(i)
print('end')
with ProcessPoolExecutor(max_workers = 6) as executor... | 5,309,519 |
def upload_scripts(scripts: list):
"""
Uploads all scripts in the list provided
"""
inform(" Uploading helper scripts")
cnt = 1
for script in scripts: # Loop thru the scripts defined below
if "yum install gdb -y" in script: ... | 5,309,520 |
def VtuRemoveCellField(vtu, fieldName):
"""
Remove a P0 field from the supplied vtu
"""
vtu.ugrid.GetCellData().RemoveArray(fieldName)
return | 5,309,521 |
def parse_user_input(req):
"""Helper function to parse the information received by spark."""
http_method = None
if req.method == "GET":
fake_json = {
"roomType": "direct",
"created": "2016-12-02T23:27:30.199Z",
"personId": "Y2lzY29zcGFyazovL3VzL1BFT1BMRS82NmVjMDkyNi0zO... | 5,309,522 |
def validate(ticket):
"""
Will attempt to validate the ticket. If validation fails, then False
is returned. If validation is successful, then True is returned
and the validated username is saved in the session under the
key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary
is ... | 5,309,523 |
def network_to_bandwidth_range(network_type: NetworkType, network_speed: NetworkSpeed) -> Tuple[int, int]:
""" Returns the (low, high) bandwidth range in kbps for the given network type """
network_bandwidth_map = {
NetworkType.WIRED: {NetworkSpeed.FAST: (48000, 96000), NetworkSpeed.SLOW: (24000, 48000)... | 5,309,524 |
def open_session(file_location=None, base_url=DEFAULT_BASE_URL):
"""Open Session File or URL.
Open a session file or URL. This will clear all networks, tables and styles associated with current
session. Be sure to ``saveSession`` first.
Args:
file_location (str): File path or URL (with 'http' ... | 5,309,525 |
def cli(ctx, verbose, dry_run, debug, output_json, cmd_tree):
"""
Top level function to kick of click parsing.
verbose and dry-run are to be respected globally
"""
if cmd_tree:
print_full_cmd_tree()
sys.exit(0)
if ctx.invoked_subcommand is None:
print(ctx.command.get_hel... | 5,309,526 |
def hex_to_uint(hex_string: str) -> Uint:
"""
Convert hex string to Uint.
Parameters
----------
hex_string :
The hexadecimal string to be converted to Uint.
Returns
-------
converted : `Uint`
The unsigned integer obtained from the given hexadecimal string.
"""
r... | 5,309,527 |
def _read_int(f, b):
"""
Read an integer of a specified number of bytes from the filestream f
"""
if b == 1:
return struct.unpack('<B', f.read(b))[0]
elif b == 2:
return struct.unpack('<H', f.read(b))[0]
elif b == 4:
return struct.unpack('<I', f.read(b))[0]
elif b == ... | 5,309,528 |
def order_auditable_fields_at_end(field):
"""
Sort Condition for Auditable Fields
:param field:
:return:
"""
if field in AUDITABLE_FIELDS:
return 2 if field == LAST_FIELD else 1
return 0 | 5,309,529 |
def led_pwm_handler(frequency=None, duty_cycle=None):
"""
Change PWM frequency and/or duty cycle for LED.
Optional arguments:
- frequency (float): Change to frequency in Hz.
- duty_cycle (float): Change to duty cycle in percent.
"""
ret = {}
if frequency != None:
led_pwm.C... | 5,309,530 |
def _setup(sys_module, _imp_module):
"""Setup importlib by importing needed built-in modules and injecting them
into the global namespace.
As sys is needed for sys.modules access and _imp is needed to load built-in
modules, those two modules must be explicitly passed in.
"""
global _imp, sys
... | 5,309,531 |
def get_module_list(username, bk_biz_id, kwargs=None):
"""
@summary: 查询模块
@param kwargs:
@param username: 执行用户名
@param bk_biz_id: 业务id
@return: [{'bk_module_id':'', 'bk_module_name':''}...]
"""
client = get_client_by_user(username)
params = {
"bk_biz_id": bk_biz_id,
}
... | 5,309,532 |
def tearDownModule(): # pylint: disable=invalid-name
"""Close database."""
global ENGINE
global SESSION
ENGINE.dispose()
ENGINE = None
SESSION = None | 5,309,533 |
async def test_ratelimit(monkeypatch: pytest.MonkeyPatch) -> None:
"""Test if `@ratelimit` decorator works properly."""
for _ in range(3):
assert "dQw4w9WgXcQ" in await rick()
with pytest.raises(RateLimitError):
await rick()
current_time = time.monotonic()
monkeypatch.setattr(time, ... | 5,309,534 |
def _visualize_feature_correlations(feature_correlations, figsize=(16,12), cmap="coolwarm", annot=True,
fmt=".2f", linewidths=.05):
"""
Visualizes the feature correlations of a training dataset or feature group in the featurestore
Args:
:feature_correlations: th... | 5,309,535 |
def get_level(env_level: Optional[str]) -> Optional[int]:
"""
Convert user-entered log level to a numeric one to send to the logger
module.
:param env_level: either log level number or log level name
:return: the associated log level number
"""
if env_level is None:
return None
... | 5,309,536 |
def test_delete_schedule():
"""
"""
result = schedules.delete_schedule(
TOKEN, SCHEDULE_NAME, customerid=CUSTOMERID)
assert "error" not in result | 5,309,537 |
def select_modality():
"""
modalityを選択する
Returns:
[str]]: selected_modality[0] ["CT", "XR", "ANGIO","PT"]のいずれかひとつ
"""
root = tk.Tk()
root.title("Modalityを選択")
root.geometry("400x300")
M = tk.Label(text='')
label1 = tk.Label(text="Modalityを選択")
label1.pack(padx=5, pady=... | 5,309,538 |
def make_env(env_fn, env_kwargs, index_col_worker, index_grad_worker, index_env, log_dir=None, info_keywords=(), mode="train"):
"""
Returns a function that handles the creating of a single environment, so it
can be executed in an independent thread.
Parameters
----------
env_fn : func
... | 5,309,539 |
def remote_dev_dependencies_fetch_remote_crates():
"""This function defines a collection of repos and should be called in a WORKSPACE file"""
maybe(
http_archive,
name = "remote_dev_dependencies__addr2line__0_14_1",
url = "https://crates.io/api/v1/crates/addr2line/0.14.1/download",
... | 5,309,540 |
def wait_for_file_mtime_change(filename):
"""This function is typically called before a file save operation,
waiting if necessary for the file modification time to change. The
purpose is to avoid successive file updates going undetected by the
caching mechanism that depends on a change in the file modif... | 5,309,541 |
def getMenuOption():
"""Return the user's option"""
return menu_option | 5,309,542 |
def calc_transform(src, dst_crs=None, resolution=None, dimensions=None,
src_bounds=None, dst_bounds=None, target_aligned_pixels=False):
"""Output dimensions and transform for a reprojection.
Parameters
------------
src: rasterio.io.DatasetReader
Data source.
dst_crs: rast... | 5,309,543 |
def help(bot, update):
"""send a message when the command /help is issued"""
reply = '''send /run stock_name to fetch stock data.\n send /predict stock_name to predict next closing price.\n send /list to see available stocks.'''
update.message.reply_text(reply) | 5,309,544 |
def usearch_dereplicate_exact_seqs(
fasta_filepath,
output_filepath=None,
minlen=64,
w=64,
slots=16769023,
sizeout=True,
maxrejects=64,
log_name = "derep.log",
usersort=False,
HALT_EXEC=False,
save_intermediate_files=False,
... | 5,309,545 |
def kill():
"""
Kills the browser process in use.
"""
from .informations import connected, set_connection_status, drivername
if layer == 'Selenium':
if connected:
if browsername == 'Chrome' or browsername == 'Firefox':
driver_process = psutil.Process(browser.servi... | 5,309,546 |
def get(remote_path, local_path=None):
"""
Download one or more files from a remote host.
`~fabric.operations.get` returns an iterable containing the absolute paths
to all files downloaded, which will be empty if ``local_path`` was a
StringIO object (see below for more on using StringIO). This obje... | 5,309,547 |
def compare_equality(col_1, col_2):
"""
This function compare the equality of two columns
and output an accuracy percentage
"""
return float(col_1.eq(col_2.values).mean()) | 5,309,548 |
def run_SEIR(E0, I0, R0, ds):
"""
Simulate SEIR model using forward euler integration. All states are defined as
fractions of a population. All rates are discrete rates at the timescale of a
signle simulation timestep.
Parameters
----------
E0, I0, R0 : float
Initial condition... | 5,309,549 |
def segment_min(data, segment_ids, name=None):
"""
Segment min operator.
This operator calculate the minimum elements of input `data` which with
the same index in `segment_ids`.
It computes a tensor such that $out_i = \\min_{j} data_{j}$
where min is over j such that `segment_ids[j] == i`.
... | 5,309,550 |
def _database_uri():
"""Use db from TESTING_SQLALCHEMY_DATABASE_URI env var or
try to create db for SQLALCHEMY_DATABASE_URI with postfix "_test"
"""
TESTING_SQLALCHEMY_DATABASE_URI = os.getenv("TESTING_SQLALCHEMY_DATABASE_URI")
if TESTING_SQLALCHEMY_DATABASE_URI:
testing_database_uri = TES... | 5,309,551 |
def draw_door(door):
"""
Draws the door of the house.
:param door: a Turtle object
:return: None
"""
door.penup()
door.setpos(20, -200)
door.pendown()
door.color("#ff0000")
door.begin_fill()
for shape in range(2):
door.forward(40)
door.left(90)
door.f... | 5,309,552 |
def standardize(df, feature_list, exclude_list):
"""Fit and save StandardScaler and PCA
"""
# Exclude unnecessary columns
df.drop(columns=exclude_list, inplace=True)
# Fit and save standardizer
standard_scaler = StandardScaler()
# standard_scaler.fit(songs_df[feature_list])
standard_fea... | 5,309,553 |
def test_text_no_text_or_file():
"""One of <test> (arg) and <file> <opt> should be set"""
result = runner_debug([])
assert "<file> required" in result.output
assert result.exit_code != 0 | 5,309,554 |
def plumbing(fn: str) -> Plumbing:
"""
Create a new plumbing instance by parsing yaml from the filename.
:param fn: A filename containing the pipeline.
:return: A plumbing object
This uses the resource framework to locate the yaml file which means that pipelines can be shipped as plugins.
"""
... | 5,309,555 |
def upgrade(options, version=None, repo_path=None):
"""Upgrade the database's current migration level.
:param options: options dict
:param version: version to upgrade (defaults to latest)
:retval version number
"""
db_version(options, repo_path) # Ensure db is under migration control
repo... | 5,309,556 |
def test_exit_code_reporting() -> None:
"""
Confirm that failed commands are not reported as successful, and confirm
that our test infrastructure is valid.
"""
with pytest.raises(AssertionError):
_run_and_verify_exit_code_zero(["det", "-m", conf.make_master_url(), "cmd", "run", "false"]) | 5,309,557 |
def saveForwardState(old_s_tree, new_s_tree, s):
"""Saving the s_current as well as all its successors in the old_s_tree into the new_s_tree.
Parameters
----------
old_s_tree : dict
The old tree.
new_s_tree : dict
The new tree.
s_current : :py:class:`ast_toolbox.mcts.AdaptiveStr... | 5,309,558 |
def display_volume_group():
"""
this function display the available physical volume
:return: output variable that contains exit code and output string in tuple datatype
"""
cmd = "vgdisplay"
output = sp.getstatusoutput(cmd)
return output | 5,309,559 |
def get_keyable_attributes(object_name=""):
"""
return an array of keyable attributes.
:param object_name:
:return: <list> keyable attributes found for this object.
"""
cnst_attr = Attributes(object_name, keyable=True)
return cnst_attr.keyable.keys() | 5,309,560 |
def write_output():
"""
-- get cal constants, covariance matrix, results of peak search
-- write to file
""" | 5,309,561 |
def find_pangrams(word_set, depth_max=6, current_words=None):
"""
Find minimal pangrams out of a set of words.
Call with any iterable of words, and it returns a list of pangrams,
if any, sorted by increasing letter count. You can set depth_max to control
search depth if your word set calls for it.
... | 5,309,562 |
def plot_domain(sim_ws):
""" a useless function
"""
import matplotlib.pyplot as plt
sim = flopy.mf6.MFSimulation.load(sim_ws=sim_ws)
gwf = sim.get_model("gwf")
hk = np.log10(gwf.get_package("npf").k.array)
mn, mx = hk.min(), hk.max()
print(hk.shape)
fig, axes = plt.subplots(1, 3, fi... | 5,309,563 |
def pyPlotVolcano(df, n_padj=0.05, n_log2FC=0, alpha=0.7, s=3, linewidth=0.5, ylim_max=None, xlim=None, a_color="#D90416", b_color="#033E8C", c_color="grey", save=None, dpi=300, **kwargs):
"""
volcanoPlot
Parameters
-------
input:
df
pd.dataFrame containing the res
n_padj
... | 5,309,564 |
def test(taskID, solve, data):
"""Given a task ID, call the given solve() function on every
example in the task data."""
print(taskID)
train_input, train_output, test_input, test_output = data
print("Training grids")
for x, y in zip(train_input, train_output):
yhat = solve(x)
sho... | 5,309,565 |
def test_b_traversal_from_node_not_in_graph_raises_error(full_graph_1):
"""Test that traversing from node not in graph raises ValueError."""
with pytest.raises(ValueError):
full_graph_1.breadth_first_traversal(0) | 5,309,566 |
def parse_cli():
"""Parse the command line arguments.
"""
parser = argparse.ArgumentParser(
'CLI options take precedence over settings in the yaml file'
'empty arguments are replaced by settings in the default yaml file')
parser.add_argument('-s',
dest='settings',
type... | 5,309,567 |
def IncrementMetricsSpecsCounters(pipeline: beam.Pipeline,
metrics_specs: Iterable[config.MetricsSpec]):
"""To track count of all metrics specs in TFMA."""
def _MakeAndIncrementCounters(_):
for metrics_spec in metrics_specs:
for metric in metrics_spec.metrics:
_I... | 5,309,568 |
def add_ion_density_field(atom, ion, ds, ftype="gas",
ionization_table=None,
field_suffix=False,
sampling_type='local',
particle_type=None):
"""
Add ion mass density field to a yt dataset for the desired ion.... | 5,309,569 |
def make_random_circuit(n_rows, n_cols, depth):
"""Generate a random unparameterized circuit of fixed depth."""
return cirq.experiments.generate_boixo_2018_supremacy_circuits_v2_grid(
n_rows=n_rows,
n_cols=n_cols,
cz_depth=depth - 2, # Account for beginning/ending Hadamard layers
... | 5,309,570 |
def update_worker(
*,
db_session: Session = Depends(get_db),
worker_id: int,
worker_in: WorkerUpdate,
):
"""
Update a worker contact.
"""
worker = get(db_session=db_session, worker_id=worker_id)
if not worker:
raise HTTPException(status_code=204, detail="The worker with this ... | 5,309,571 |
def InstallLibrary(name, version, explicit=True):
"""Install a package.
If the installation is explicit then the user made the installation request,
not a package as a dependency. Explicit installation leads to stricter
version checking.
Args:
name: Name of the requested package (already validated as av... | 5,309,572 |
def save(filename, ax=None):
"""Save figure.
Parameters
----------
filename : string
The filepath into which the current figure will be saved.
ax : `matplotlib.pyplot.Axes`, `None` by default
The axis from which the plot to be saved derives. If left as `None`,
`matplotlib.p... | 5,309,573 |
def process_reader_outputs(fnames: List[str],
reader: str,
dart_ids: Mapping[str, str] = None,
extract_filter: List[str] = None,
grounding_mode: str = 'compositional',
nproc: int = 8,
... | 5,309,574 |
def add_arg_type_after_self(t: Callable, arg_type: Type) -> Callable:
"""Add an argument with the given type to a callable type after 'self'."""
return Callable([t.arg_types[0], arg_type] + t.arg_types[1:],
[t.arg_kinds[0], nodes.ARG_POS] + t.arg_kinds[1:],
[t.arg_names[0... | 5,309,575 |
def extract_constraints(input_def):
"""
:param input_def: an input definition.
:return: Constraint instances in respect to the constraint defined in the
input definition.
"""
return [parse(c) for c in input_def.get(CONSTRAINT_CONST, [])] | 5,309,576 |
def load_italy_power_demand(split=None, return_X_y=False):
"""
Loads the ItalyPowerDemand time series classification problem and
returns X and y
Parameters
----------
split: None or str{"train", "test"}, optional (default=None)
Whether to load the train or test partition of the problem.... | 5,309,577 |
def softmax(arr, axis=None):
"""softmax"""
return np.exp(arr) / np.sum(np.exp(arr), axis=axis, keepdims=True) | 5,309,578 |
def get_target_project_select(site, project):
"""Return remote target project level selection HTML"""
current_level = None
try:
rp = RemoteProject.objects.get(
site__mode=SODAR_CONSTANTS['SITE_MODE_TARGET'],
site=site,
project_uuid=project.sodar_uuid,
)
... | 5,309,579 |
def form_SelectWithOtherChoice(request):
"""
A basic select choice with input option
"""
schema = schemaish.Structure()
schema.add('mySelect', schemaish.Integer())
options = [(1,'a'),(2,'b'),(3,'c')]
form = formish.Form(schema, 'form')
form['mySelect'].widget = formish.SelectWithOtherCh... | 5,309,580 |
def lssitepackages_cmd():
"""Show the content of the site-packages directory of the current virtualenv."""
site = sitepackages_dir()
print(*site.iterdir())
extra_paths = site / '_virtualenv_path_extensions.pth'
if extra_paths.exists():
print('from _virtualenv_path_extensions.pth:')
w... | 5,309,581 |
def print_predictions(src_sents,tgt_sents,scores,src_tokenizer,tgt_tokenizer):
"""Prints the predictions of model after converting ids to words
Args:
src_sents (Tensor): Tensor of source ids
tgt_sents (Tensor): Actual Tensor of target ids
scores (Tensor): Vocab scores
src_tokeni... | 5,309,582 |
def bgrewriteaof():
""" 将redis的AOF文件压缩 """
redis = redis_wrap.get_redis()
redis.bgrewriteaof() | 5,309,583 |
def default_handler(request):
""" The default handler gets invoked if no handler is set for a request type """
return alexa.respond(get_pool_weather_handler(request)) | 5,309,584 |
def check_ghi_limits_QCRad(ghi, solar_zenith, dni_extra, limits=None):
"""
Tests for physical limits on GHI using the QCRad criteria.
Test passes if a value > lower bound and value < upper bound. Lower bounds
are constant for all tests. Upper bounds are calculated as
.. math::
ub = min + m... | 5,309,585 |
def register(func: Callable, module: ModuleType, generate_lm=False) -> KscStub:
"""
Main Knossos entry point.
The @register decorator transforms a TorchScript function into a
KscAutogradFunction which implements the function and its
derivatives.
```
@knossos.register
def foo(x : ... | 5,309,586 |
def load_and_save_params(default_params, exp_dir, ignore_existing=False):
"""Update default_params with params.json from exp_dir and overwrite params.json with updated version."""
default_params = json.loads(json.dumps(default_params))
param_path = os.path.join(exp_dir, 'params.json')
logging.info("Sear... | 5,309,587 |
def endpoint_registry_contract(deploy_tester_contract):
"""Deployed SecretRegistry contract"""
return deploy_tester_contract(CONTRACT_ENDPOINT_REGISTRY) | 5,309,588 |
def generate_input_with_unknown_words(file_path):
"""Reads the file with the given file_path.
Replaces every first occurance of a (word, tag) pair with ("<UNK>", tag).
Creates dictionary of all words encountered in following format:
{(word, tag) : count}"""
seen_tuples = []
label_matches = dict()
file_lin... | 5,309,589 |
def invalid_image_size_popup(request, size_status):
"""If the size status is below 20mb , a popup will display the error."""
if size_status == "invalid":
messages.info(request, 'Photo must be less than 20mb') | 5,309,590 |
def get_file_at_commit(directory, commit, path):
"""
Get the contents of repository `path` at commit `commit` given the
Git working directory `directory`.
:param directory: Git working directory.
:param commit: Commit ID
:param path: In-repository path
:return: File contents as bytes
:r... | 5,309,591 |
def three_body_force_en(env1, env2, d1, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff):
"""3-body single-element kernel between a force component and a local
energy.
Args:
env1 (AtomicEnvironment): Local environment associated with the
force component.
env2 (AtomicEnvironment):... | 5,309,592 |
def _GetTipOfTrunkVersionFile(root):
"""Returns the current Chromium version, from a file in a checkout.
Args:
root: path to the root of the chromium checkout.
"""
version_file = os.path.join(root, 'src', 'chrome', 'VERSION')
chrome_version_info = cros_build_lib.RunCommand(
['cat', version_file],
... | 5,309,593 |
def sieve_of_eratosthenes(n):
"""Yield primes in [2..n] using the "Sieve of Eratosthenes".
"""
assert type(n) == int
# Create a Boolean array "prime[0..n]" and initialize
# all entries in it as true. A value in prime[i] will
# finally be false if i is not a prime, else true.
p, prime = 2, [T... | 5,309,594 |
def include_silently(parser, token):
"""
Include template if it exists.
If it doesn't exist then will not raise any exception.
{% include_silently "mytemplate.html" %}
"""
try:
tag_name, template_name = token.split_contents()
except ValueError:
raise template.TemplateSyntaxEr... | 5,309,595 |
def parse_array(a, separator=' ', dtype=DEFAULT_FLOAT_DTYPE):
"""
Converts given string or array of strings to :class:`ndarray` class.
Parameters
----------
a : unicode or array_like
String or array of strings to convert.
separator : unicode
Separator to split the string with.
... | 5,309,596 |
def dAdzmm_ron_s0_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = uabs_nm2(u0,u0_conj,M2)
M4 = dt*fftshift(ifft(fft(M3)*hf), axes = -1) # creates matrix M4
N = nonlin_ram_nm2(M1, Q, u0, M3... | 5,309,597 |
def test_no_sync_down():
"""
No down syncing, so:
syncer=None
upload_dir=None
Expected results after first checkpoint:
- 4 trials are running
- At least one trial ran on the head node
- At least one trial ran remotely
- Driver has trial checkpoints from hea... | 5,309,598 |
def run():
"""Requirements for Task 1B"""
# Build list of stations
stations = build_station_list(False)
#Find stations within the radius
stations_in_radius = stations_within_radius(stations, (52.2053, 0.1218), 10)
#function to print the station details in a parsable form
def stations_in_r... | 5,309,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.