Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Next line prediction: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
return masked.MaskedModule(
Continue the code snippet: <|code_start|> """Tests the flax layer pruning module.""" def setUp(self): super().setUp() self._rng = jax.random.PRNGKey(42) self._batch_size = 2 self._input_shape = ((self._batch_size, 28, 28, 1), jnp.float32) self._input = jnp.ones(*self._input_shape) _, initia...
pruned_mask = pruning.prune(self._masked_model, 0.5)
Using the snippet: <|code_start|> class TrainingTest(absltest.TestCase): """Tests functions for training loop and training convenience functions.""" def setUp(self): super().setUp() self._batch_size = 128 # Note: Tests are run on GPU/TPU. self._batch_size_test = 128 self._shuffle_buffer_size = ...
self._dataset = dataset_factory.create_dataset(
Given the following code snippet before the placeholder: <|code_start|> def setUp(self): super().setUp() self._batch_size = 128 # Note: Tests are run on GPU/TPU. self._batch_size_test = 128 self._shuffle_buffer_size = 1024 self._rng = jax.random.PRNGKey(42) self._input_shape = ((self._batch_s...
self._model, self._state = model_factory.create_model(
Predict the next line after this snippet: <|code_start|> self._dataset_name = 'MNIST' self._model_name = 'MNIST_CNN' self._summarywriter = tensorboard.SummaryWriter('/tmp/') self._dataset = dataset_factory.create_dataset( self._dataset_name, self._batch_size, self._batch_size_te...
batch = training._shard_batch(batch)
Predict the next line after this snippet: <|code_start|> # there is a type conflict in passing iterators of different types to # itertools.chain. counts = [ count_permutations_mask_layer(layer, next_layer) for layer, next_layer in utils.pairwise_longest(mask.values()) ] sum_stats = {} for key in...
'sparsity': masked.mask_sparsity(mask),
Given the following code snippet before the placeholder: <|code_start|> mask_stats['zeroed_neurons'] = int(zeroed_count) mask_stats['permutations'] = functools.reduce( operator.mul, (np.math.factorial(t) for t in unique_counts)) mask_stats['unique_neurons'] = len(unique_counts) return mask_stats def co...
for layer, next_layer in utils.pairwise_longest(mask.values())
Using the snippet: <|code_start|> initial_params) def _create_logits_labels(self, correct): """Creates a set of logits/labels resulting from correct classification. Args: correct: If true, creates labels for a correct classifiction, otherwise ...
logits = training._shard_batch(logits)
Continue the code snippet: <|code_start|> """Creates a set of logits/labels resulting from correct classification. Args: correct: If true, creates labels for a correct classifiction, otherwise creates labels for an incorrect classification. Returns: A tuple of logits, labels. """ ...
p_compute_metrics = jax.pmap(utils.compute_metrics, axis_name='batch')
Here is a snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
class CIFAR10Dataset(dataset_base.ImageDataset):
Predict the next line after this snippet: <|code_start|># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for weight_symmetry.pruning.masked.""" class Dense(fl...
return masked.MaskedModule(
Based on the snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
class MNISTDataset(dataset_base.ImageDataset):
Predict the next line for this snippet: <|code_start|># Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
train.main([])
Here is a snippet: <|code_start|> Returns: An `Operation` that applies the specified gradients. If `global_step` was not None, that operation also increments `global_step`. """ def apply_gradient_op(): return self._optimizer.apply_gradients( grads_and_vars, global_step=global_ste...
var_name = sparse_utils.mask_extract_name_fn(mask.name)
Predict the next line for this snippet: <|code_start|> loaded_mask = l_source.pruning_vars[0][1] if shuffle_mask: # tf shuffle shuffles along the first dim, so we need to flatten. loaded_mask = tf.reshape( tf.random.shuffle(tf.reshape(loaded_mask, -1)), loaded_mask.shape...
new_init = init_utils.unit_scaled_init(mask)
Predict the next line for this snippet: <|code_start|> else: raise ValueError('Mode: %s, is not valid' % mode) return p_params # Forked from tensorflow_model_optimization/python/core/sparsity/keras/prune.py def maybe_prune_layer(layer, params, filter_fn): if filter_fn(layer): return PRUNING_WRAPPER(layer...
model = getattr(networks, network_name)(
Given the code snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
DATASET_LIST: Sequence[str] = tuple(dataset_factory.DATASETS.keys())
Using the snippet: <|code_start|> FLAGS.model, rng, ((input_shape, np.float32),), num_classes=dataset.num_classes) if FLAGS.optimizer == 'Adam': optimizer = flax.optim.Adam( learning_rate=FLAGS.lr, weight_decay=FLAGS.weight_decay) elif FLAGS.optimizer == 'Momentum': optimizer = fla...
trainer = training.Trainer(
Here is a snippet: <|code_start|> Returns: A tensor of shape (batch, num_classes), containing the logit output. Raises: ValueError if the number of pooling layers is too many for the given input size, or if the provided mask is not of the correct depth for the model. """ # Note: Fir...
kernel_init=init.sparse_init(
Next line prediction: <|code_start|> """Applies a convolution to the inputs. Args: inputs: Input data with dimensions (batch, spatial_dims..., features). num_classes: Number of classes in the dataset. filter_shape: Shape of the convolutional filters. filters: Number of filters in each co...
masks = masked.generate_model_masks(depth, masks,
Predict the next line for this snippet: <|code_start|> tf.reset_default_graph() g = tf.Graph() with g.as_default(): test_inputs, test_labels = self.get_next() with self.test_session() as sess: test_images_out, test_labels_out = sess.run([test_inputs, test_labels]) self.assertAll...
global_step, _, _, logits = resnet_train_eval.build_model(
Using the snippet: <|code_start|># See the License for the specific language governing permissions and # limitations under the License. r"""Tests for the data_helper input pipeline and the training process. """ from __future__ import absolute_import from __future__ import division from __future__ import print_functio...
test_inputs, test_labels = input_fn(params)
Given snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the s...
mask1 = sparse_utils.get_mask_random(mask, sparsity, tf.int32)
Next line prediction: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
random_mask.main([])
Continue the code snippet: <|code_start|> def weight_magnitude(weights): """Creates weight magnitude-based saliencies, given a weight matrix.""" return jnp.absolute(weights) def prune( model, pruning_rate, saliency_fn = weight_magnitude, mask = None, compare_fn = jnp.greater): """Returns a m...
mask = masked.simple_mask(model, jnp.ones, masked.WEIGHT_PARAM_NAMES)
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
prune.main([])
Given snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
LABELKEY = dataset_base.ImageDataset.LABELKEY
Predict the next line after this snippet: <|code_start|> dataset: The training dataset. rng: Random number generator, i.e. jax.random.PRNGKey, to use for model training, e.g. dropout. summary_writer: An optional tensorboard summary writer for logging self._rng = rng if self._rng is Non...
pruning_rate_fn: The pruning rate function, takes the current epoch as an
Predict the next line for this snippet: <|code_start|>) -> Tuple[flax.optim.Optimizer, flax.deprecated.nn.Collection, float, float]: """Performs training for one minibatch. Args: optimizer: Optimizer to use. batch: Minibatch to train with. rng: Random number generator, i.e. jax.random.PRNGKey, to use f...
loss = utils.cross_entropy_loss(logits, batch[LABELKEY])
Next line prediction: <|code_start|> NUM_FEATURES: int = 32 def apply(self, inputs, mask = None): inputs = inputs.reshape(inputs.shape[0], -1) return masked.MaskedModule( inputs, features=self.NUM_FEATURES, wrapped_module=flax.deprecated.nn.Dense, ma...
return mask_factory.create_mask(
Continue the code snippet: <|code_start|># Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
return masked.MaskedModule(
Based on the snippet: <|code_start|> masked_layer_indices: The layer indices of layers in model to be masked. Returns: A tensor of shape (batch, num_classes), containing the logit output. Raises: ValueError if the number of pooling layers is too many for the given input size. """ ...
kernel_init=init.sparse_init(
Predict the next line after this snippet: <|code_start|> Args: inputs: Input data with dimensions (batch, spatial_dims..., features). num_classes: Number of classes in the dataset. filter_shape: Shape of the convolutional filters. filters: Number of filters in each convolutional layer, and n...
masks = masked.generate_model_masks(depth, masks,
Based on the snippet: <|code_start|> prune --xm_runlocal --dataset=MNIST --model=MNIST_FC --epochs=10 --pruning_rate=0.95 Command for training and pruning an MNIST fully-connected model for 10 epochs, with pruning rates 0.3, 0.6 and 0.95 at epochs 2, 5, and 8 respectively for all layers: prune --xm_runlocal --dataset...
dataset = dataset_factory.create_dataset(
Using the snippet: <|code_start|>Command for doing the same, but performing pruning only on the second layer: prune --xm_runlocal --dataset=MNIST --model=MNIST_FC --epochs=10 --pruning_schedule="{'1': [(2, 0.3), (5, 0.6), (8, 0.95)]}" """ experiment_dir = path.join(FLAGS.experiment_dir, str(work_unit_id)) loggi...
base_model, _ = model_factory.create_model(
Here is a snippet: <|code_start|> lr_fn = lr_schedule.create_constant_learning_rate_schedule( FLAGS.lr, steps_per_epoch) elif FLAGS.lr_schedule == LR_SCHEDULE_STEPPED: lr_schedule_steps = ast.literal_eval(FLAGS.lr_schedule_steps) lr_fn = lr_schedule.create_stepped_learning_rate_schedule( FL...
trainer = training.Trainer(
Based on the snippet: <|code_start|> pruning_rate_fn = pruning_fn_p(pruning_schedule) else: pruning_rate_fn = lr_schedule.create_constant_learning_rate_schedule( FLAGS.pruning_rate, steps_per_epoch) if jax.host_id() == 0: trainer = training.Trainer( optimizer, initial_model, ...
utils.dump_dict_json(best_metrics,
Here is a snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "A...
return masked.MaskedModule(
Given the following code snippet before the placeholder: <|code_start|> def setUp(self): super().setUp() self._rng = jax.random.PRNGKey(42) self._batch_size = 2 self._input_shape = ((self._batch_size, 2, 2, 1), jnp.float32) self._flat_input_shape = ((self._batch_size, 2 * 2 * 1), jnp.float32) ...
stats = symmetry.count_permutations_mask_layer(mask_layer)
Continue the code snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
'CIFAR10': cifar10.CIFAR10Dataset,
Predict the next line after this snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LI...
DATASETS: Mapping[str, Type[dataset_base.Dataset]] = {
Continue the code snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
'MNIST': mnist.MNISTDataset,
Next line prediction: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for weigh...
self.assertIsInstance(dataset, dataset_base.Dataset)
Based on the snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
return dataset_factory.create_dataset(
Using the snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
return model_factory.create_model(
Predict the next line after this snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LI...
'CIFAR10_CNN': cifar10_cnn.CIFAR10CNN,
Predict the next line for this snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICE...
'MNIST_CNN': mnist_cnn.MNISTCNN,
Predict the next line after this snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LI...
'MNIST_FC': mnist_fc.MNISTFC,
Here is a snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
self._dataset = mnist.MNISTDataset(
Predict the next line after this snippet: <|code_start|> 'interpolate', denylist=['model_start', 'model_end', 'model_inter', 'd_set']) def interpolate(model_start, model_end, model_inter, d_set, i_start=-0.2, i_end=1.2, n_interpolation=29): """Interpolates between 2 sparse networks linearly and...
data_train, data_test, info = utils.get_dataset()
Using the snippet: <|code_start|> mask = None): inputs = inputs.reshape(inputs.shape[0], -1) layer_mask = mask['MaskedModule_0'] if mask else None return masked.MaskedModule( inputs, features=self.NUM_FEATURES, wrapped_module=flax.deprecated.nn.Dense, mask=layer_m...
kernel_init=init.kaiming_sparse_normal(
Next line prediction: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
return masked.MaskedModule(
Here is a snippet: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
shuffled_mask.main([])
Given snippet: <|code_start|> outputs. Useful to remove unnecessary dimensions for classification. name: Optional scope for the variables. global_pool: Optional boolean flag. If True, the input to the classification layer is avgpooled to size 1x1, for any input size. (This is not part of the or...
resnet_model.conv2d_fixed_padding,
Given the following code snippet before the placeholder: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed und...
_, initial_params = cifar10_cnn.CIFAR10CNN.init_by_shape(
Using the snippet: <|code_start|> pkfail(*args, **kwargs) else: pkfail('expect={} == actual={}', expect, actual) def pkok(cond, fmt, *args, **kwargs): """If cond is not true, throw PKFail with calling context Args: cond (object): expression which should evaluate to true...
if not re.search(expect_re, pkcompat.from_bytes(actual), flags=flags):
Next line prediction: <|code_start|> pkfail(*fmt_and_args, **kwargs) def pkeq(expect, actual, *args, **kwargs): """If actual is not expect, throw assertion with calling context. Opposite of `pkne`. Args: expect (object): what to test for actual (object): run-time value args (t...
call = pkinspect.caller(ignore_modules=[contextlib])
Continue the code snippet: <|code_start|> #: Type of a regular expression _RE_TYPE = type(re.compile('')) #: _test_file initialized? _init = False #: module being run by `pykern.pkcli.test` _test_file = None class PKFail(AssertionError): pass def assert_object_with_json(basename, actual, ): """Converts ac...
pkio.write_text(a, actual)
Given snippet: <|code_start|> return _snip(r, len(obj)) def _object(obj, depth): depth += 1 c = str(type(obj)()) if isinstance(obj, (list, tuple)) \ else '{}' if depth > cfg.max_depth: return c[0] + SNIP + c[1] m = _dict if isinstance(obj, dict) else _...
value = pkcompat.unicode_unescape(value)
Based on the snippet: <|code_start|> if n == 'MainThread': return 0 m = _THREAD_ID_RE.search(t.name) if m: return int(m.group(1)) return t.ident def _write(self, fmt, args, kwargs, with_control=False): """Provides formatter for message to _process ...
@pkconfig.parse_none
Given snippet: <|code_start|> Returns: object: Redacted and truncated str or obj in exception """ def _dict(obj, depth): return _iterate( sorted(obj), lambda k: _format_arg(k, depth) + ': ' \ + (_redacted(k) or _format_arg(obj[k], depth)), ...
return isinstance(key, pkconst.STRING_TYPES) and SECRETS_RE.search(key) \
Given the code snippet: <|code_start|> try: return json.dumps( obj, sort_keys=True, indent=4, separators=(',', ': '), ) + '\n' except Exception as e: pass if pprint.isreadable(obj): ret...
lambda: pkinspect.Call(record),
Given the following code snippet before the placeholder: <|code_start|> :copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function def default_command(*args): """Run tests one at...
e = PKDict(os.environ)
Given snippet: <|code_start|> Returns: bool: True if is a file not found exception. """ return isinstance(exc, IOError) and exc.errno == errno.ENOENT or isinstance(exc, py.error.ENOENT) def expand_user_path(path): """Calls expanduser on path If `pkunit_prefix` is set, will prefix, too. ...
if isinstance(to_check, pkconst.STRING_TYPES):
Given the code snippet: <|code_start|> a.append(p) if os.path.exists(f): return f _raise_no_file_found(a, relative_filename) def glob_paths(relative_path, caller_context=None, packages=None): """Find all paths that match the relative path in all packages Args: relative_...
lambda m: pkinspect.root_package(importlib.import_module(m)),
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- u"""Where external resources are stored :copyright: Copyright (c) 2015 Bivio Software, Inc. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function # Root module: ...
return pkio.py_path(filename(relative_filename, caller_context, packages))
Predict the next line after this snippet: <|code_start|> Returns: py.path: absolute paths of the matched files """ r = [] a = [] for f, p in _files(relative_path, caller_context, packages): a.append(p) r.extend(glob.glob(f)) return [pkio.py_path(f) for f in r] def _files...
os.path.join(pksetup.PACKAGE_DATA, path),
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- u"""test `pykern.pkconfig` :copyright: Copyright (c) 2015 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function def _custom_p6(v):...
@pkconfig.parse_none
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- u"""Helper functions for to :mod:`inspect`. :copyright: Copyright (c) 2015 RadiaSoft, Inc. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function # Avoid pykern i...
class Call(PKDict):
Here is a snippet: <|code_start|> # process starts. Then polling less frequently # helps avoid thrashing, especially with mpi. t = .5 return s try: stdout = output if isinstance(output, six.string_types): stdout = open(output, 'w') stde...
msg('{}: exception: {} {}', pid, cmd, pkdexc())
Given snippet: <|code_start|>from __future__ import absolute_import, division, print_function def render(out): v = {'k1': 'v1'} <|code_end|> , continue by predicting the next line. Consider current file imports: from pykern import pkresource from pykern import pkjinja and context: # Path: pykern/pkresource.py ...
return pkjinja.render_resource('t1', v, out)
Next line prediction: <|code_start|> Returns: float: current value of the average """ assert self.average is not None, \ 'self.average is None and has not been initialized' return self.average def _Privy(object): """This is a private class that does nothing"""...
cfg = pkconfig.init(
Given the following code snippet before the placeholder: <|code_start|> str: rendered template """ t = pkio.read_text(filename) kw = dict( trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True, extensions=['jinja2.ext.do'], ) if strict_undefined: ...
pkinspect.caller_module(),
Given snippet: <|code_start|># -*- coding: utf-8 -*- u"""Simplify rendering jinja2 :copyright: Copyright (c) 2015 Bivio Software, Inc. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function #: Implicit extension including '...
t = pkio.read_text(filename)
Predict the next line for this snippet: <|code_start|> Returns: str: rendered template """ t = pkio.read_text(filename) kw = dict( trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True, extensions=['jinja2.ext.do'], ) if strict_undefined: ...
pkresource.filename(
Next line prediction: <|code_start|>class C(): pass v = 1 c = C() def caller(ignore_modules=None): <|code_end|> . Use current file imports: (from pykern import pkinspect) and context including class names, function names, or small code snippets from other files: # Path: pykern/pkinspect.py # _VALID_IDENTIFIE...
return pkinspect.caller(ignore_modules=ignore_modules)
Based on the snippet: <|code_start|> def index(request): messages.debug(request, f'Test: {getattr(manager, "test", None)}') messages.debug(request, '%s SQL statements were executed.' % 666) messages.info(request, 'Three credits remain in your account.') messages.success(request, 'Profile details updat...
return MenuModel.objects.get(program_name=program_name)
Here is a snippet: <|code_start|> try: except ImportError: def gravatar(email, size=200): return 'https://www.gravatar.com/avatar/{}?{}'.format( md5(email.lower().encode('utf-8')).hexdigest(), urlencode({ 's': str(size) }) ) def environment(**options): env = Environm...
'adminlte': manager,
Continue the code snippet: <|code_start|>try: except ImportError: register = template.Library() for name in filters.__all__: register.filter(name, getattr(filters, name)) @register.filter def gravatar(email, size=200): return 'https://www.gravatar.com/avatar/{}?{}'.format( md5(email.lower().enco...
locale = config.get(
Based on the snippet: <|code_start|> @register.filter def gravatar(email, size=200): return 'https://www.gravatar.com/avatar/{}?{}'.format( md5(email.lower().encode('utf-8')).hexdigest(), urlencode({ 's': str(size) }) ) @register.filter def humanize(dt): locale = confi...
return manager.with_context(context).get_home_page()
Given snippet: <|code_start|> "It is either read-protected or not readable by the server." ) @requires_csrf_token def handler404(request, exception): return error_page( request, 404, 'Page not found', 'The requested URL was not found on the server.' 'If you entered the URL manua...
success_url = reverse_lazy(config['ADMINLTE_LOGIN_ENDPOINT'])
Predict the next line for this snippet: <|code_start|> description='Convert DNA or AA FASTA to AA ORF-only FASTA', epilog=('Given DNA or AA FASTA on stdin, output AA ORF-only FASTA to ' 'stdout. Optionally, filter by minimum required ORF length ' 'and allow the output of s...
addFASTACommandLineOptions(parser)
Using the snippet: <|code_start|> '(as specified by --minORFLength) will be output as long as ' 'they are open.')) parser.add_argument( '--minORFLength', metavar='LEN', type=int, default=None, help='Only ORFs of at least this length will be written to stdout.') parse...
reads = parseFASTACommandLineOptions(args)
Using the snippet: <|code_start|> formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=('Split sequences in a FASTA file into separate files, named ' 'either by their sequence id or numerically.')) parser.add_argument( '--outDir', default='.', help='The directory to make ...
addFASTACommandLineOptions(parser)
Based on the snippet: <|code_start|> 'either by their sequence id or numerically.')) parser.add_argument( '--outDir', default='.', help='The directory to make the files in.') parser.add_argument( '--verbose', default=False, action='store_true', help='If given, print sequence ids as the...
reads = parseFASTACommandLineOptions(args)
Given snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=('Find sequences that have a specific property (as detected ' 'by the "relabel" function in the fil...
addFASTACommandLineOptions(parser)
Based on the snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=('Find sequences that have a specific property (as detected ' 'by the "relabel" function in ...
reads = parseFASTACommandLineOptions(args)
Using the snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function if __name__ == '__main__': parser = argparse.ArgumentParser( description=( 'Given FASTA on stdin, write the ids, sequences, and ' 'quality strings on a single TAB-separated line to stdou...
addFASTACommandLineOptions(parser)
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function if __name__ == '__main__': parser = argparse.ArgumentParser( description=( 'Given FASTA on stdin, write the ids, sequences, and ' 'quality strings on a single TAB-...
reads = parseFASTACommandLineOptions(args)
Next line prediction: <|code_start|>#!/usr/bin/env python from __future__ import print_function if __name__ == '__main__': parser = argparse.ArgumentParser( description=('Given FASTA on stdin, write a summary of sequence base ' 'categories to stdout. It is currently not possible t...
addFASTACommandLineOptions(parser)
Using the snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function if __name__ == '__main__': parser = argparse.ArgumentParser( description=('Given FASTA on stdin, write a summary of sequence base ' 'categories to stdout. It is currently not possible to '...
reads = parseFASTACommandLineOptions(args)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python from __future__ import print_function, division if __name__ == '__main__': parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=('Given FASTA on stdin a...
addFASTACommandLineOptions(parser)
Predict the next line after this snippet: <|code_start|> 'write filtered FASTA to stdout.')) parser.add_argument( '--quiet', action='store_true', default=False, help=('If True, do not print the final sequence summary.')) parser.add_argument( '--saveAs', choices=('fa...
args, parseFASTACommandLineOptions(args)))
Based on the snippet: <|code_start|> class TestConstants(TestCase): """ Test constants in dark.cigar """ def testOperations(self): """ Make sure the CIGAR operation strings have the expected one-letter codes. """ <|code_end|> , predict the immediate next line with the h...
self.assertEqual('I', CINS_STR)
Predict the next line for this snippet: <|code_start|> class TestConstants(TestCase): """ Test constants in dark.cigar """ def testOperations(self): """ Make sure the CIGAR operation strings have the expected one-letter codes. """ self.assertEqual('I', CINS_STR)...
self.assertEqual('D', CDEL_STR)
Given the following code snippet before the placeholder: <|code_start|> class TestConstants(TestCase): """ Test constants in dark.cigar """ def testOperations(self): """ Make sure the CIGAR operation strings have the expected one-letter codes. """ self.assertEqu...
self.assertEqual('M', CMATCH_STR)
Using the snippet: <|code_start|> class TestConstants(TestCase): """ Test constants in dark.cigar """ def testOperations(self): """ Make sure the CIGAR operation strings have the expected one-letter codes. """ self.assertEqual('I', CINS_STR) self.assertE...
self.assertEqual('=', CEQUAL_STR)
Given snippet: <|code_start|> class TestConstants(TestCase): """ Test constants in dark.cigar """ def testOperations(self): """ Make sure the CIGAR operation strings have the expected one-letter codes. """ self.assertEqual('I', CINS_STR) self.assertEqual...
self.assertEqual('X', CDIFF_STR)
Continue the code snippet: <|code_start|> class TestConstants(TestCase): """ Test constants in dark.cigar """ def testOperations(self): """ Make sure the CIGAR operation strings have the expected one-letter codes. """ self.assertEqual('I', CINS_STR) self...
self.assertRaisesRegex(ValueError, error, dna2cigar, 'hey', 'there')
Given snippet: <|code_start|> self.assertEqual('2M', dna2cigar('GA', 'TA', concise=True)) def testMixedMatch(self): """ If two strings with matching and non-matching regions must result in the expected CIGAR string. """ self.assertEqual('3=4X5=2X', ...
self.assertRaisesRegex(ValueError, error, makeCigar, '', 'ACGT')