content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def plotInterpolate(grid, pointextent, dem, show=True, save=None):
"""Function to plot the results of the velocity interpolation process for
a particular image pair.
:param grid: Numpy grid. It is recommended that this is constructed using the interpolateHelper function
:type grid: arr
:... | 5,295,800 |
def test_discrete(dsystem_type):
"""Test discrete time frequency response"""
dsys = dsystem_type
# Set frequency range to just below Nyquist freq (for Bode)
omega_ok = np.linspace(10e-4, 0.99, 100) * np.pi / dsys.dt
# Test frequency response
dsys.frequency_response(omega_ok)
# Check for wa... | 5,295,801 |
def clean_stream(stream, skiplocs=CROSSCORR_SKIPLOCS, verbose=False):
"""
1 - Removes traces whose location is in skiplocs.
2 - Select trace from 1st location if several ids.
@type stream: L{obspy.core.Stream}
@type skiplocs: tuple of str
@rtype: None
"""
if not skiplocs:
skipl... | 5,295,802 |
def qtdmri_isotropic_scaling(data, q, tau):
""" Constructs design matrix for fitting an exponential to the
diffusion time points.
"""
dataclip = np.clip(data, 1e-05, 1.)
logE = -np.log(dataclip)
logE_q = logE / (2 * np.pi ** 2)
logE_tau = logE * 2
B_q = np.array([q * q])
inv_B_q = ... | 5,295,803 |
def createUser(user):
"""Creates a new user in LDAP database.
Args:
user (dict): User ldiff representation. A dict containing the keys:
* uid: username as unique identification.
* cn: first name.
* sn: last name.
* mail: e-mail.
"""
_assertUserDic... | 5,295,804 |
def nested_cv_param_search( # pylint:disable=invalid-name
X: np.ndarray, # noqa
y: np.ndarray,
param_dict: Dict[str, Any],
pipeline: Pipeline,
outer_cv: BaseCrossValidator,
inner_cv: BaseCrossValidator,
groups: Optional[np.ndarray] = None,
hyper_search_params: Optional[Dict[str, Any]] ... | 5,295,805 |
def extract_positive_integer_value(text, key):
"""
Extract an integer value for a given key in a text
Args:
text (str): text to extract value from
key (str): key to extract value for
Raises:
ValueError: value is not a positive integer
Returns:
int: extraced value
... | 5,295,806 |
def delete_from_s3(s3_path: str) -> bool:
"""Delete a path from s3
Args:
s3_path: Full path on s3 in format "s3://<bucket_name>/<obj_path>".
Returns:
Boolean of whether the delete was successful.
"""
bucket, key = decompose_s3_path(s3_path)
s3_client = boto3.client("s3")
tr... | 5,295,807 |
def resnet18_feat(pretrained=False, initpath=None, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet_feat(BasicBlock, [2, 2, 2, 2], deep_base=False, **kwargs)
if pretrained and initpath is not None:
... | 5,295,808 |
def process_generic(infile, station_id, out_folder):
"""Process a generic netCDF input file into a FOWD output file."""
from .generic_source import process_file
from .logs import setup_file_logger
os.makedirs(out_folder, exist_ok=True)
logfile = os.path.join(
out_folder,
f'fowd_gen... | 5,295,809 |
def view_cfncluster_config():
"""Prints contents of cfncluster configuration file.
If the file does not exist, it creates a template version
of it in ~/.cfncluster/config using make_config_file. The contents are
printed to stdout.
Args:
None
Returns:
None
"""
if not o... | 5,295,810 |
def keep_these_labels_only(
dataframe: pandas.DataFrame,
label_column: str,
labels_to_keep: List[Any]
):
"""
Parameters
----------
dataframe: `pandas.DataFrame`, required
The input dataframe
label_column: `str`, required
The name of the labels column
label... | 5,295,811 |
def create_blocks(arr, block_size=(1024, 1024)):
"""Split input array into uniformly-sized blocks
This function will split the input array into uniformly-sized blocks
with the size of each block specified as `block_size`. The input array
will be zero-padded in either or both axes in order to expand th... | 5,295,812 |
def testlinearityofsigma8withAs():
"""Creates Plot of sigma8 varying As for z =0, keeping
other parameters fixed. Should be linear.
"""
#Setup an array of scalar amplitude values
As = np.arange(2.0, 3.0 , 0.1)
As *= 1.0e-9
#Initialize sigma8 array
Sigma8s = np.zeros(len(As))
for i in range(len(As... | 5,295,813 |
def PrintableString(s):
"""For pretty-printing in tests."""
if all(c in string.printable for c in s):
return s
return repr(s) | 5,295,814 |
def expected_regularization():
"""Build the expected alive vectors applying the rules of concat and group."""
concat = REG_STUB['conv1'] + REG_STUB['conv2']
# Grouping: Activation is alive after grouping if one of the constituents is
# alive.
grouped = [max(a, b) for a, b in zip(concat, REG_STUB['conv4'])]
... | 5,295,815 |
def trans_concat(*args):
"""Concat all parts of tag and translate it."""
return _(''.join(args)) | 5,295,816 |
def handleSYNPacketHostPortscanDetector(data=None):
"""
Creates an incident if a single canary receives SYN packets to more than 10 different
ports in less than 50 seconds.
"""
try:
host_scan_key = KEY_TRACK_HOST_PORT_SCAN + data['src_host'] + ':' + data['dst_host']
new_set = False
... | 5,295,817 |
def test_captured_import(start_cluster, tmp_working_dir, option: str):
"""Tests importing a module in the driver and capturing it in a task/actor.
This tests both that this fails *without* the working_dir and that it
passes with it.
"""
cluster, address = start_cluster
def call_ray_init():
... | 5,295,818 |
def mean_normalize_data(data: np.ndarray) -> np.ndarray:
"""
Mean normalization method.
:param data: Data cube.
:return: Normalized data.
"""
for band_id in range(data.shape[SPECTRAL_AXIS]):
max_ = np.amax(data[..., band_id])
min_ = np.amin(data[..., band_id])
mean = np.... | 5,295,819 |
def bitwise_xor(evm: Evm) -> None:
"""
Bitwise XOR operation of the top 2 elements of the stack. Pushes the
result back on the stack.
Parameters
----------
evm :
The current EVM frame.
Raises
------
:py:class:`~ethereum.byzantium.vm.error.StackUnderflowError`
If `le... | 5,295,820 |
def make_intervals(b3, b4):
""" Given the already parsed igs block 3 and 4 dictionaries (aka
'3. GNSS Receiver Information' and '4. GNSS Antenna Information') as
parsed from an IgsLogFile instance (see IgsLogFile::parse_block),
concatenate the intervals based on changes either on the 3 or 4 bl... | 5,295,821 |
def check_first_block(markdown_path, contents_path):
"""Check that first FCB in Markdown is same as the file contents."""
with open(contents_path, "r", encoding="utf-8") as f:
want = f.read()
blocks = phmdoctest.tool.fenced_code_blocks(markdown_path)
got = blocks[0]
verify.a_and_b_are_the_sa... | 5,295,822 |
def discretize_kernel(
kernel, sampling_rate, area_fraction=default_kernel_area_fraction,
num_bins=None, ensure_unit_area=False):
""" Discretizes a kernel.
:param kernel: The kernel or kernel function. If a kernel function is used
it should take exactly one 1-D array as argument.
:t... | 5,295,823 |
def test_split_fullpath_with_route_domain():
"""Test proper behavior of split_fullpath_with_route_domain."""
# Expected input must have route specified, otherwise reject
tests = [
["/Partition/1.2.3.4%0:80", "/Partition", "1.2.3.4", 0, 80],
["/Part/Folder/1.2.3.4%1:443", "/Part/Folder", "1.... | 5,295,824 |
def bitcast_to_bytes(s):
"""
Take a string and return a string(PY2) or a bytes(PY3) object. The returned
object contains the exact same bytes as the input string. (latin1 <->
unicode transformation is an identity operation for the first 256 code
points).
"""
return s if six.PY2 else s.encode... | 5,295,825 |
def waiting_for(func=None, *, timeout=settings.DEFAULT_TIMEOUT):
""" Set maximum execution time for a function
:param func: function to decorate
:param timeout: maximum allowed execution time
:return: result of the func
"""
def _alarm_handler(signal_number, stack_frame):
raise Time... | 5,295,826 |
def useRThreshold(prefix, extraoutsuffix = '', densthresh = 0., rthresh = 1.,whichpofr='3D'):
"""
In this method, you set a density-contrast threshold rthresh.
Voids not exceeding that threshold are not mentioned in the output
file. Voids stop accreting zones if they encounter another zone
with r>r... | 5,295,827 |
def main():
"""Evolve an estimator."""
generations = 50 # Number of times to evolve the population.
population = 50 # Number of estimators in each generation.
x_train, x_test, y_train, y_test = get_dataset()
print(x_train.shape)
param_choices = {
'max_depth': [1, 2, 3, 4, 5, 6, 7, 8... | 5,295,828 |
def test_models_xapi_video_terminated_with_valid_statement(statement):
"""Tests that a video terminated statement has the expected verb.id."""
assert statement.verb.id == "http://adlnet.gov/expapi/verbs/terminated" | 5,295,829 |
def orthogonal_regularizer(scale, scope=None):
""" Return a function that computes orthogonal regularization.
:param scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.
:param scope: An optional scope name.
:return: A function with signature `orthogonal_sum(weights)` that applies orthogon... | 5,295,830 |
def predict_numpy(config, numpy_data, input_names):
"""Get predictions for your pipeline from numpy data and input names"""
from konduit.load import client_from_file
numpy_files = numpy_data.split(",")
input_names = input_names.split(",")
assert len(numpy_files) == len(input_names)
client = cl... | 5,295,831 |
def test_map_column():
"""
Test validation_run.map_column
"""
in_col = " foo "
mapper = {"foo": "bar"}
out = validation_run.map_column(in_col, mapper)
assert out == "bar"
in_col = " foobar"
out = validation_run.map_column(in_col, mapper)
assert out is None | 5,295,832 |
def tabq_learn(t, agent, env, env_state, history, args):
"""Learning loop for TabularQAgent"""
step_type, reward, discount, state = env_state
state = copy.deepcopy(state)
# Act
action = agent.act_explore(state)
step_type, reward, discount, successor = env.step(action)
# Learn
if args.c... | 5,295,833 |
def _lookup(key: str, typ: Type, *args, **kwargs) -> Hashable:
"""
Gets the value of the given key in args, defaulting to the first positional.
:param key: key to find value of in args.
:param typ: type that dispatch is being perform on.
:param args: positional args.
:param kwargs: keyword args... | 5,295,834 |
def MakeStatefulPolicyPreservedStateDiskEntry(messages, stateful_disk_dict):
"""Create StatefulPolicyPreservedState from a list of device names."""
disk_device = messages.StatefulPolicyPreservedStateDiskDevice()
if stateful_disk_dict.get('auto-delete'):
disk_device.autoDelete = (
stateful_disk_dict.ge... | 5,295,835 |
def new_name(location, is_dir=False):
"""
Return a new non-existing location from a `location` usable to write a file
or create directory without overwriting existing files or directories in the same
parent directory, ignoring the case of the filename.
The case of the filename is ignored to ensure ... | 5,295,836 |
def parse_xbrl_noun(fxbrl,file_path):
"""
XBRLからtextを取り出す
parse_xbrl改良 名詞だけ抽出 2019/01/18
"""
ET_xbrl=ET.parse(fxbrl)
root=ET_xbrl.getroot()
#nslist=['jpcrp_cor:*','jpdei_cor:*','jppfs_cor:*']
nslist=[ i+':*' for i in root.nsmap ]
xbrldoc=''
for ele in nslist :
anch... | 5,295,837 |
def _doc(from_func):
"""copy doc from one function to another
use as a decorator eg::
@_doc(file.tell)
def tell(..):
...
"""
def decorator(to_func):
to_func.__doc__ = from_func.__doc__
return to_func
return decorator | 5,295,838 |
async def get_prometheus_rules(ops_test: OpsTest, app_name: str, unit_num: int) -> list:
"""Fetch all Prometheus rules.
Args:
ops_test: pytest-operator plugin
app_name: string name of Prometheus application
unit_num: integer number of a Prometheus juju unit
Returns:
a list ... | 5,295,839 |
def update_view_markers(view=None):
"""
Refresh the cursor position, breakpoint marker icons, etc
"""
if view is None:
view = sublime.active_window().active_view()
fn = view.file_name()
if fn is not None:
fn = normalize(fn)
pos_scope = get_setting("position_scope", "entity.n... | 5,295,840 |
def get_loss_func(config, device, logger, ewc_loss=False):
"""Get a function handle that can be used as task loss function.
Note, this function makes use of function
:func:`sequential.train_utils_sequential.sequential_nll`.
Args:
config (argparse.Namespace): The command line arguments.
... | 5,295,841 |
def demo():
"""Create 100 fake records for demo purposes."""
click.secho('Creating demo records...', fg='green')
for _ in range(100):
create_fake_record()
click.secho('Created records!', fg='green') | 5,295,842 |
def connect_to_sqlite3_db():
"""
Connects to the sqlite3 database.
:return: Connection of type sqlite3.Connection.
"""
config = ConfigParser()
config.read(CFG_FILE)
conn = sqlite3.connect(config['paths']['path_to_database'])
conn.row_factory = sqlite3.Row
return conn | 5,295,843 |
def quote():
"""Get stock quote."""
if request.method == "POST":
stock_info = lookup(request.form.get("symbol"))
if stock_info == None:
return apology("cannot find that stock symbol", 403)
else:
return render_template("quote.html",
... | 5,295,844 |
def is_proc_group_parent(proc) -> bool:
"""
Checks if process is a group parent
"""
if os.uname().sysname == 'Darwin':
fproc_names = filter(lambda x: len(x.cmdline()) > 0, proc.children())
procs_names = [ p.cmdline()[0] for p in fproc_names ]
procs_names.append(proc.cmdline()... | 5,295,845 |
def validate_time_string(value, is_list):
"""
Checks that a "time string" quant is correctly formatted.
A time string can contain three kinds of expressions, separated by + or -:
Base values, which are just numeric (with an optional exponent on e form)
Delta values, which are the same as abo... | 5,295,846 |
def resnet101(rate=1, class_num=10, index=None):
"""
Get ResNet101 neural network.
Args:
class_num (int): Class number.
Returns:
Cell, cell instance of ResNet101 neural network.
Examples:
>>> net = resnet101(1001)
"""
return ResNet(rate,
ResidualB... | 5,295,847 |
def _smart_ceil(x: typing.Union[int, float], order: int = None) -> int:
"""Smart ceil to the nearest round integer.
The 'nearest' is chosen based on the order of the given number
"""
order = int(order) if order else len(str(math.ceil(x)))
if order <= 0:
raise ValueError("`order` must be... | 5,295,848 |
def get_file_storage_impl(request):
"""
Retrieves correct **IFileStorage** instance from the registry.
:param request: Pyramid Request instance
"""
registry = getattr(request, 'registry', None)
if registry is None:
registry = request
return registry.getUtility(IFileStorage) | 5,295,849 |
def test_concat():
"""Test ONNX Concat function. This is a variable number of inputs operator."""
input = (np.ones(3), np.ones(3), np.ones(3))
out = onnx_ops.concat(*input, axis=0)
assert np.allclose(out, np.concatenate(input, axis=0)) | 5,295,850 |
def norm_observation(mat, axis=-1, eps=EPSILON):
"""
L2 normalization for observation vectors
"""
denorm = np.linalg.norm(mat, axis=axis, keepdims=True)
denorm = np.maximum(denorm, eps)
return mat / denorm | 5,295,851 |
def get_commercial_from_lowertext(transcript, video_desp):
"""
Get region with lower case transcript
"""
def is_lower_text(text):
lower = [c for c in text if c.islower()]
alpha = [c for c in text if c.isalpha()]
if len(alpha) == 0:
return False
if 1. * len(lo... | 5,295,852 |
def create_table():
"""
This function creates the category table
"""
create_engine()
engine.execute('CREATE TABLE IF NOT EXISTS categories (id serial PRIMARY KEY, category VARCHAR)')
print('created categories') | 5,295,853 |
async def circuit_sat_prover(
generators, code, x, gf, pivot_choice=cs.PivotChoice.compressed
):
"""Non-interactive implementation of Protocol 8, prover-side,
including Nullity using compressed pivot (Protocol 5).
"""
logger_cs_mpc.debug(f"Enter circuit_sat_prover. pivot_choice={pivot_choice}"... | 5,295,854 |
async def download_chunk(chunk_index: int,
chunk_size: int,
url: str,
file: pathlib.Path,
progress_bar=None):
"""Download specified chunk of file
Download [chunk_index*chunk_size : (chunk_index+1)*(chunk_size-1)... | 5,295,855 |
def rl_modelrl_breakout_ae_medium():
"""Medium set for testing Breakout with an autoencoder."""
hparams = rl_modelrl_ae_medium()
hparams.game = "wrapped_breakout"
return hparams | 5,295,856 |
def miniStartup(thisDir=os.getcwd()):
"""
This is an imitation of the startup script
I don't want to try sourcing the main() of the startup
Or run this in subprocess
"""
Bootstrap.setupLogging(thisDir)
job = Bootstrap.loadJobDefinition()
task = Bootstrap.loadTask(job)
Bootstrap.cre... | 5,295,857 |
def build_process(model, process, sig_in=None, sig_out=None, inc=False):
"""Builds a `.Process` object into a model.
Parameters
----------
model : Model
The model to build into.
process : Process
Process to build.
sig_in : Signal, optional (Default: None)
The input signa... | 5,295,858 |
def layer_norm(inputs,
center=True,
scale=True,
activation_fn=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
begin_norm_axis=1,
begin_params_axi... | 5,295,859 |
def update_schema(schema_type):
"""Compare version and run the update
"""
db_path = Constants.DB_JOBS if schema_type == 'master' else Constants.DB_NODE_JOBS
rdb = RDB(db_path)
current_version = Constants.VERSION
result = rdb.execute_sql_with_results('SELECT name FROM sqlite_master WHERE type="... | 5,295,860 |
def get_dependency_type(dependency):
"""Get dependency type from dependency name"""
if dependency.startswith("."):
return RELATIVE
for internal in INTERNAL_ALLOWED_ORDER:
if dependency.startswith(internal+"/"):
return internal
return EXTERNAL | 5,295,861 |
def generate_paired_images_to_inspect_three_different_ways(dataset_to_use, yhat):
"""
Try pairing images by KLG; by all image features (basically we take the max over feature categories); and by invididual and side. In all cases, the
"high pain" image is on the right, although the way we define "high pain"... | 5,295,862 |
def test_connection_pool_closed_while_request_in_flight():
"""
Closing a connection pool while a request/response is still in-flight
should raise an error.
"""
network_backend = MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Cont... | 5,295,863 |
def reducejson(j):
"""
Not sure if there's a better way to walk the ... interesting result
"""
authors = []
for key in j["data"]["repository"]["commitComments"]["edges"]:
authors.append(key["node"]["author"])
for key in j["data"]["repository"]["issues"]["nodes"]:
auth... | 5,295,864 |
def vis_mask(img: np.ndarray, mask: np.ndarray, col: Tuple[int, int, int], alpha: float = 0.4):
"""
Visualizes a single binary mask by coloring the region inside a binary mask
as a specific color, and then blending it with an RGB image.
Args:
img: Numpy array, representing RGB image with values... | 5,295,865 |
async def async_setup(hass, hass_config):
"""Set up the Plaato component."""
return True | 5,295,866 |
def _get_upstream_seqs(
ica_data: IcaData,
imodulon: Union[str, int],
seq_dict: Dict,
upstream: int,
downstream: int,
):
"""
Get upstream sequences for a table of operons
Parameters
----------
ica_data: IcaData
IcaData object
imodulon: Union[str,int]
Name of ... | 5,295,867 |
def get_view():
"""Responds with the form for the example"""
return render_template(
"eg015_envelope_tab_data.html",
title="Envelope information",
envelope_ok="envelope_id" in session,
source_file=path.basename(path.dirname(__file__)) + "/controller.py",
source_url=DS_CO... | 5,295,868 |
def _saveJob(event):
"""
When a job is saved, if it is a docker run task, add the Dask Bokeh port to
the list of exposed ports.
"""
job = event.info
try:
jobkwargs = json_util.loads(job['kwargs'])
if '--scheduler' in jobkwargs['container_args']:
jobkwargs['ports'] = {... | 5,295,869 |
def json_value(obj):
"""Format obj in the JSON style for a value"""
if type(obj) is bool:
if obj:
return '*true*'
return '*false*'
if type(obj) is str:
return '"' + obj + '"'
if obj is None:
return '*null*'
assert False | 5,295,870 |
def protocol_increasing_persistence_change_pcl():
"""
Change base chloride of persistent synapse model
"""
config_functions = {config_persistent_synapses: change_persist_numbers}
run_protocol(compare_pCl, root="persistent_pcl", timestamp=False, filenames=["distal", "distal_KCC2"],
... | 5,295,871 |
def exp(node) -> Node:
"""Exponential of the node, using np.exp(x)"""
return Node(node, None, np.exp(node.value), 'exp' ) | 5,295,872 |
def tf_disable(user):
""" Disable two factor for user """
tf_clean_session()
user.tf_primary_method = None
user.tf_totp_secret = None
_datastore.put(user)
tf_disabled.send(app._get_current_object(), user=user) | 5,295,873 |
def bias_variable(shape):
"""Generates a bias variable of a given shape."""
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial, name='bias') | 5,295,874 |
def test_subgraph_list(browser):
"""Tests functionality from subgraph_menu.js:
Filter, change subgraph name, delete subgraph, undo delete, add subgraph.
"""
wait = WebDriverWait(browser, 5)
# log in
browser.get(url_for('tool.index', _external=True))
browser.find_element(By.ID, 'username').... | 5,295,875 |
def precompile_dlls(path, dtype="double"):
# type: (str, str) -> List[str]
"""
Precompile the dlls for all builtin models, returning a list of dll paths.
*path* is the directory in which to save the dlls. It will be created if
it does not already exist.
This can be used when build the windows... | 5,295,876 |
def ensure_job_indexed(job_id, es_url, alias):
"""Ensure job is indexed."""
query = {
"query": {
"bool": {
"must": [
{'term': {'_id': job_id}}
]
}
},
"fields": [],
}
logger.info("ensure_job_indexed query... | 5,295,877 |
def main() -> int:
"""Main"""
# TODO(pwbug/456): Refactor the code so that each test bundle generation
# is done in a separate function or script.
# pylint: disable=too-many-locals
args = parse_args()
test_bundle = Bundle()
dev_signed_root = test_bundle.generate_dev_signed_root_metadata()
... | 5,295,878 |
def provide_aws_context():
"""
Authenticates the context to be able use aws resources.
Falls back to awscli default authentication methods via `.aws`` folder.
"""
# TODO: Implement more authentication methods
yield | 5,295,879 |
def padmat(input_mat,left_pad=0,right_pad=0,up_pad=0,down_pad=0):
"""
Helper function to pad zeros to image matrices to edges don't get cut off.
"""
new_mat = np.zeros((input_mat.shape[0]+up_pad+down_pad,input_mat.shape[1]+left_pad+right_pad))
new_mat[up_pad:new_mat.shape[0]-down_pad,left_pad:new_m... | 5,295,880 |
def calc_E_M_C_hs_d_t():
"""冷房設備機器のその他の燃料による一次エネルギー消費量(MJ/h)(22d, 23d)を計算する
Args:
Returns:
ndarray: 冷房設備機器のその他の燃料による一次エネルギー消費量(MJ/h)
"""
return calc_E_M_C_hs_MR_d_t() + calc_E_M_C_hs_OR_d_t() | 5,295,881 |
def load_adjacency_list(file: str, bipartite: bool = False, comment: str = '%#',
delimiter: str = None, ) -> Bunch:
"""Parse Tabulation-Separated, Comma-Separated or Space-Separated (or other) Values datasets in the form of
adjacency lists.
Parameters
----------
file : str
... | 5,295,882 |
def _check_input_args_many_predictors(
predictor_matrix, predictor_names, cmap_object_by_predictor,
cnorm_object_by_predictor, min_colour_value_by_predictor,
max_colour_value_by_predictor, plot_wind_barbs):
"""Error-checks input arguments for `plot_many_predictors*`.
:param predictor_ma... | 5,295,883 |
def users_create(ctx, attributes, file, content_format, out):
"""Creates a new project."""
ctx.obj.create(attributes, file, out) | 5,295,884 |
def __stop_storage__(logger: typing.Any) -> None:
"""Stops the persistent storage.
:param logger: Logger where to log the messages.
:return: None
"""
global FINISH
if __debug__:
logger.debug("Stopping storage")
FINISH() | 5,295,885 |
def sim_real_change(request):
""" Return a dummy YATSM model container with a real change
"Real change" dataset is simply a timeseries drawn from samples of two
normal distributions with greatly different mean values.
"""
np.random.seed(123456789)
dates = np.arange(dt.strptime('2000-01-01', '%Y... | 5,295,886 |
def plugin_reconfigure(handle, new_config):
""" Reconfigures the plugin
it should be called when the configuration of the plugin is changed during the operation of the South service;
The new configuration category should be passed.
Args:
handle: handle returned by the plugin initialisation cal... | 5,295,887 |
def homogenise_dates(d: DataFrame):
"""
Parameters
----------
d
Returns
-------
"""
d.date = to_datetime(d.date, format="%Y-%m-%d")
col_names = d.columns
date = date_range(
start=to_datetime(d.date).min(),
end=to_datetime(d.date).max()
)
dt_time_list... | 5,295,888 |
def compute_x_in_set(x, s):
"""Check if elements in tensor x are in set s.
Args:
x: batch_size, num_candidate
s: batch_size, k (padded with -1)
Returns:
boolean tensor with shape of x
"""
s = tf.expand_dims(s, axis=2)
# batch_size, k, 1
k = tf.shape(s)[1]
x = tf.tile(tf.expand_dims(x, axis... | 5,295,889 |
def checkunique (uniquerules, rule) :
"""check if rule already exists
Parameters
uniquerules : list of unique rules
rule : rule to check
Returns
True or False
"""
for r in uniquerules :
if samerule (r, rule) :
return True
return False | 5,295,890 |
def global_to_body(q, vec):
"""
Convert a vector from global to body coordinates.
Parameters:
-----------
q: quaternion
The rotation quaternion
vec: ndarray
The vector in global coordinates
Returns:
vec: ndarray
The vector in body coordinates
"""
# quate... | 5,295,891 |
def get_hostmask_regex(mask):
"""Get a compiled regex pattern for an IRC hostmask
:param str mask: the hostmask that the pattern should match
:return: a compiled regex pattern matching the given ``mask``
:rtype: :ref:`re.Pattern <python:re-objects>`
"""
mask = re.escape(mask)
mask = mask.re... | 5,295,892 |
def test_atomic_date_time_min_inclusive_3_nistxml_sv_iv_atomic_date_time_min_inclusive_4_4(mode, save_output, output_format):
"""
Type atomic/dateTime is restricted by facet minInclusive with value
2006-07-21T01:32:21.
"""
assert_bindings(
schema="nistData/atomic/dateTime/Schema+Instance/NIS... | 5,295,893 |
def create_map(template_id, report_id, created_by):
"""Submits a request to CARROT's template_report create mapping"""
return request_handler.create_map(
"templates",
template_id,
"reports",
report_id,
[("created_by", created_by)],
) | 5,295,894 |
def dump_parts(object, current_path):
"""
Dumps (converts to formcode) the given object parts using the "normal"
approach.
:type object: Object
:param object: The object to have the parts dumped.
:type String: String
:param String: The current path value.
:rtype: String
:r... | 5,295,895 |
def read_yaml(file: Any) -> dict:
"""Read yaml file. Return dict."""
if isinstance(file, str) and any(file.endswith(x) for x in ('.yml', '.yaml')):
with open(file, "r", encoding='utf-8') as fp:
return yaml.load(fp, Loader=yaml.FullLoader)
data: List[dict] = yaml.load(file, Loader=yaml.Fu... | 5,295,896 |
def pass_alignment_qc(alignment, barcodes):
"""
Check high quality mapping, QC-passing barcode and UMI of alignment.
alignment :
aligned bam segment
barcodes : list
List of cellular barcode strings
Returns
-------
pass_qc : boolean
true if a high quality, QC passing ... | 5,295,897 |
def _netid_admin_url(netid):
"""
Return UWNetId resource for provided netid supported
resources
"""
return "{0}/{1}/admin.json".format(url_base(), netid) | 5,295,898 |
def retrieve(customer, sub_id):
"""
Retrieve a subscription object from Stripe's API
Args:
customer: a legacy argument, we check that the given
subscription belongs to the given customer
sub_id: the Stripe ID of the subscription you are fetching
Returns:
the data fo... | 5,295,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.