Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|>
class LearnedLung(LungEnv):
"""Learned lung."""
params: list = deluca.field(jaxed=True)
init_rng: jnp.array = deluca.field(jaxed=False)
u_window: int = deluca.field(5, jaxed=False)
p_window: int = deluca.field(3, jaxed=False)
u_history_len: int = deluca.field(5, jaxed=False)
p_history_len: int = deluca.field(5, jaxed=False)
u_normalizer: ShiftScaleTransform = deluca.field(jaxed=False)
p_normalizer: ShiftScaleTransform = deluca.field(jaxed=False)
seed: int = deluca.field(0, jaxed=False)
flow: int = deluca.field(0, jaxed=False)
transition_threshold: int = deluca.field(0, jaxed=False)
default_model_parameters: Dict[str, Any] = deluca.field(jaxed=False)
num_boundary_models: int = deluca.field(5, jaxed=False)
boundary_out_dim: int = deluca.field(1, jaxed=False)
boundary_hidden_dim: int = deluca.field(100, jaxed=False)
reset_normalized_peep: float = deluca.field(0.0, jaxed=False)
default_model_name: str = deluca.field("MLP", jaxed=False)
default_model: nn.module = deluca.field(jaxed=False)
boundary_models: list = deluca.field(default_factory=list, jaxed=False)
ensemble_models: list = deluca.field(default_factory=list, jaxed=False)
def setup(self):
self.u_history_len = max(self.u_window, self.num_boundary_models)
self.p_history_len = max(self.p_window, self.num_boundary_models)
<|code_end|>
with the help of current file imports:
import functools
import deluca.core
import flax.linen as nn
import jax
import jax.numpy as jnp
from typing import Any, Dict
from deluca.lung.core import LungEnv
from deluca.lung.utils.data.transform import ShiftScaleTransform
from deluca.lung.utils.nn import MLP
from deluca.lung.utils.nn import ShallowBoundaryModel
and context from other files:
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
#
# Path: deluca/lung/utils/data/transform.py
# class ShiftScaleTransform:
# """Data normalizer."""
#
# # vectors is an array of vectors
# def __init__(self, vectors):
# vectors_concat = jnp.concatenate(vectors)
# self.mean = jnp.mean(vectors_concat)
# self.std = jnp.std(vectors_concat)
# print(self.mean, self.std)
#
# def _transform(self, x, mean, std):
# return (x - mean) / std
#
# def _inverse_transform(self, x, mean, std):
# return (x * std) + mean
#
# def __call__(self, vector):
# return self._transform(vector, self.mean, self.std)
#
# def inverse(self, vector):
# return self._inverse_transform(vector, self.mean, self.std)
#
# Path: deluca/lung/utils/nn/mlp.py
# class MLP(nn.Module):
# """multilayered perceptron."""
# hidden_dim: int = 10
# out_dim: int = 1
# n_layers: int = 2
# droprate: float = 0.0
# activation_fn: Callable = nn.relu
#
# @nn.compact
# def __call__(self, x):
# for i in range(self.n_layers - 1):
# x = nn.Dense(
# features=self.hidden_dim, use_bias=True, name=f"MLP_fc{i}")(
# x)
# x = nn.Dropout(
# rate=self.droprate, deterministic=False)(
# x, rng=jax.random.PRNGKey(0))
# x = self.activation_fn(x)
# x = nn.Dense(features=self.out_dim, use_bias=True, name=f"MLP_fc{i + 1}")(x)
# return x.squeeze() # squeeze for consistent shape w/ boundary model output
#
# Path: deluca/lung/utils/nn/shallow_boundary_model.py
# class ShallowBoundaryModel(nn.Module):
# """Shallow boundary module."""
# out_dim: int = 1
# hidden_dim: int = 100
# model_num: int = 0
#
# @nn.compact
# def __call__(self, x):
# # need to flatten extra dimensions required by CNN and LSTM
# x = x.squeeze()
# x = nn.Dense(
# features=self.hidden_dim,
# use_bias=False,
# name=f"shallow_fc{1}_model" + str(self.model_num),
# )(
# x)
# x = nn.tanh(x)
# x = nn.Dense(
# features=self.out_dim,
# use_bias=True,
# name=f"shallow_fc{2}_model" + str(self.model_num))(
# x)
# return x.squeeze() # squeeze for consistent shape w/ boundary model output
, which may contain function names, class names, or code. Output only the next line. | self.default_model = MLP( |
Based on the snippet: <|code_start|> u_normalizer: ShiftScaleTransform = deluca.field(jaxed=False)
p_normalizer: ShiftScaleTransform = deluca.field(jaxed=False)
seed: int = deluca.field(0, jaxed=False)
flow: int = deluca.field(0, jaxed=False)
transition_threshold: int = deluca.field(0, jaxed=False)
default_model_parameters: Dict[str, Any] = deluca.field(jaxed=False)
num_boundary_models: int = deluca.field(5, jaxed=False)
boundary_out_dim: int = deluca.field(1, jaxed=False)
boundary_hidden_dim: int = deluca.field(100, jaxed=False)
reset_normalized_peep: float = deluca.field(0.0, jaxed=False)
default_model_name: str = deluca.field("MLP", jaxed=False)
default_model: nn.module = deluca.field(jaxed=False)
boundary_models: list = deluca.field(default_factory=list, jaxed=False)
ensemble_models: list = deluca.field(default_factory=list, jaxed=False)
def setup(self):
self.u_history_len = max(self.u_window, self.num_boundary_models)
self.p_history_len = max(self.p_window, self.num_boundary_models)
self.default_model = MLP(
hidden_dim=self.default_model_parameters["hidden_dim"],
out_dim=self.default_model_parameters["out_dim"],
n_layers=self.default_model_parameters["n_layers"],
droprate=self.default_model_parameters["droprate"],
activation_fn=self.default_model_parameters["activation_fn"])
default_params = self.default_model.init(
jax.random.PRNGKey(0),
jnp.ones([self.u_history_len + self.p_history_len]))["params"]
self.boundary_models = [
<|code_end|>
, predict the immediate next line with the help of imports:
import functools
import deluca.core
import flax.linen as nn
import jax
import jax.numpy as jnp
from typing import Any, Dict
from deluca.lung.core import LungEnv
from deluca.lung.utils.data.transform import ShiftScaleTransform
from deluca.lung.utils.nn import MLP
from deluca.lung.utils.nn import ShallowBoundaryModel
and context (classes, functions, sometimes code) from other files:
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
#
# Path: deluca/lung/utils/data/transform.py
# class ShiftScaleTransform:
# """Data normalizer."""
#
# # vectors is an array of vectors
# def __init__(self, vectors):
# vectors_concat = jnp.concatenate(vectors)
# self.mean = jnp.mean(vectors_concat)
# self.std = jnp.std(vectors_concat)
# print(self.mean, self.std)
#
# def _transform(self, x, mean, std):
# return (x - mean) / std
#
# def _inverse_transform(self, x, mean, std):
# return (x * std) + mean
#
# def __call__(self, vector):
# return self._transform(vector, self.mean, self.std)
#
# def inverse(self, vector):
# return self._inverse_transform(vector, self.mean, self.std)
#
# Path: deluca/lung/utils/nn/mlp.py
# class MLP(nn.Module):
# """multilayered perceptron."""
# hidden_dim: int = 10
# out_dim: int = 1
# n_layers: int = 2
# droprate: float = 0.0
# activation_fn: Callable = nn.relu
#
# @nn.compact
# def __call__(self, x):
# for i in range(self.n_layers - 1):
# x = nn.Dense(
# features=self.hidden_dim, use_bias=True, name=f"MLP_fc{i}")(
# x)
# x = nn.Dropout(
# rate=self.droprate, deterministic=False)(
# x, rng=jax.random.PRNGKey(0))
# x = self.activation_fn(x)
# x = nn.Dense(features=self.out_dim, use_bias=True, name=f"MLP_fc{i + 1}")(x)
# return x.squeeze() # squeeze for consistent shape w/ boundary model output
#
# Path: deluca/lung/utils/nn/shallow_boundary_model.py
# class ShallowBoundaryModel(nn.Module):
# """Shallow boundary module."""
# out_dim: int = 1
# hidden_dim: int = 100
# model_num: int = 0
#
# @nn.compact
# def __call__(self, x):
# # need to flatten extra dimensions required by CNN and LSTM
# x = x.squeeze()
# x = nn.Dense(
# features=self.hidden_dim,
# use_bias=False,
# name=f"shallow_fc{1}_model" + str(self.model_num),
# )(
# x)
# x = nn.tanh(x)
# x = nn.Dense(
# features=self.out_dim,
# use_bias=True,
# name=f"shallow_fc{2}_model" + str(self.model_num))(
# x)
# return x.squeeze() # squeeze for consistent shape w/ boundary model output
. Output only the next line. | ShallowBoundaryModel( |
Given the code snippet: <|code_start|># limitations under the License.
"""Delay Lung."""
class Observation(deluca.Obj):
predicted_pressure: float = 0.0
time: float = 0.0
class SimulatorState(deluca.Obj):
in_history: jnp.array
out_history: jnp.array
steps: int = 0
time: float = 0.0
volume: float = 0.0
predicted_pressure: float = 0.0
pipe_pressure: float = 0.0
target: float = 0.0
class DelayLung(LungEnv):
"""Delay lung."""
min_volume: float = deluca.field(1.5, jaxed=False)
R: int = deluca.field(10, jaxed=False)
C: int = deluca.field(6, jaxed=False)
delay: int = deluca.field(25, jaxed=False)
inertia: float = deluca.field(0.995, jaxed=False)
control_gain: float = deluca.field(0.02, jaxed=False)
dt: float = deluca.field(0.03, jaxed=False)
<|code_end|>
, generate the next line using the imports in this file:
import deluca.core
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import LungEnv
and context (functions, classes, or occasionally code) from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
. Output only the next line. | waveform: BreathWaveform = deluca.field(jaxed=False) |
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 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.
"""Delay Lung."""
class Observation(deluca.Obj):
predicted_pressure: float = 0.0
time: float = 0.0
class SimulatorState(deluca.Obj):
in_history: jnp.array
out_history: jnp.array
steps: int = 0
time: float = 0.0
volume: float = 0.0
predicted_pressure: float = 0.0
pipe_pressure: float = 0.0
target: float = 0.0
<|code_end|>
, predict the next line using imports from the current file:
import deluca.core
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import LungEnv
and context including class names, function names, and sometimes code from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
. Output only the next line. | class DelayLung(LungEnv): |
Predict the next line after this snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
"""@author: Olivier Sigaud A merge between two sources:
* Adaptation of the MountainCar Environment from the "FAReinforcement" library
* of Jose Antonio Martin H.
(version 1.0), adapted by 'Tom Schaul, tom@idsia.ch' and then modified by
Arnaud de Broissia * the OpenAI/gym MountainCar environment itself from
http://incompleteideas.net/sutton/MountainCar/MountainCar1.cp permalink:
https://perma.cc/6Z2N-PFWC
"""
# pylint:disable=g-long-lambda
<|code_end|>
using the current file's imports:
from deluca.core import Env
from deluca.core import field
import jax
import jax.numpy as jnp
and any relevant context from other files:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
. Output only the next line. | class MountainCar(Env): |
Here is a snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
"""@author: Olivier Sigaud A merge between two sources:
* Adaptation of the MountainCar Environment from the "FAReinforcement" library
* of Jose Antonio Martin H.
(version 1.0), adapted by 'Tom Schaul, tom@idsia.ch' and then modified by
Arnaud de Broissia * the OpenAI/gym MountainCar environment itself from
http://incompleteideas.net/sutton/MountainCar/MountainCar1.cp permalink:
https://perma.cc/6Z2N-PFWC
"""
# pylint:disable=g-long-lambda
class MountainCar(Env):
"""MountainCar."""
<|code_end|>
. Write the next line using the current file imports:
from deluca.core import Env
from deluca.core import field
import jax
import jax.numpy as jnp
and context from other files:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
, which may include functions, classes, or code. Output only the next line. | key: jnp.ndarray = field(jaxed=False) |
Continue the code 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 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 specific language governing permissions and
# limitations under the License.
"""Acrobot."""
__copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy"
__credits__ = [
"Alborz Geramifard",
"Robert H. Klein",
"Christoph Dann",
"William Dabney",
"Jonathan P. How",
]
__license__ = "BSD 3-Clause"
__author__ = "Christoph Dann <cdann@cdann.de>"
# SOURCE:
# https://github.com/rlpy/rlpy/blob/master/rlpy/Domains/Acrobot.py
<|code_end|>
. Use current file imports:
from deluca.core import Env
from deluca.core import field
import jax
import jax.numpy as jnp
and context (classes, functions, or code) from other files:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
. Output only the next line. | class Acrobot(Env): |
Predict the next line after this 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 "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.
"""Acrobot."""
__copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy"
__credits__ = [
"Alborz Geramifard",
"Robert H. Klein",
"Christoph Dann",
"William Dabney",
"Jonathan P. How",
]
__license__ = "BSD 3-Clause"
__author__ = "Christoph Dann <cdann@cdann.de>"
# SOURCE:
# https://github.com/rlpy/rlpy/blob/master/rlpy/Domains/Acrobot.py
class Acrobot(Env):
"""Acrobot."""
<|code_end|>
using the current file's imports:
from deluca.core import Env
from deluca.core import field
import jax
import jax.numpy as jnp
and any relevant context from other files:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
. Output only the next line. | key: jnp.ndarray = field(jaxed=False) |
Given the following code snippet before the placeholder: <|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 specific language governing permissions and
# limitations under the License.
"""Residual controller."""
class CompositeState(deluca.Obj):
"""Combined state of two controller states."""
base_state: deluca.Obj
resid_state: deluca.Obj
@property
def time(self):
return self.base_state.time
@property
def steps(self):
return self.base_state.steps
@property
def dt(self):
return self.base_state.dt
<|code_end|>
, predict the next line using imports from the current file:
import deluca.core
import jax
import jax.numpy as jnp
from deluca.lung import core
and context including class names, function names, and sometimes code from other files:
# Path: deluca/lung/core.py
# ROOT = os.path.dirname(os.path.realpath(os.path.join(__file__, "../..")))
# DEFAULT_XP = [0.0, 1.0, 1.5, 3.0 - 1e-8, 3.0]
# DEFAULT_DT = 0.03
# class BreathWaveform(deluca.Obj):
# class LungEnv(deluca.Env):
# class LungEnvState(deluca.Obj):
# class ControllerState(deluca.Obj):
# class Controller(deluca.Agent):
# def setup(self):
# def at(self, t):
# def static_interp(t, xp, fp, period):
# def elapsed(self, t):
# def is_in(self, t):
# def is_ex(self, t):
# def time(self, state):
# def dt(self):
# def physical(self):
# def should_abort(self):
# def wait(self, duration):
# def cleanup(self):
# def proper_time(t):
# def init(self, waveform=None):
# def max(self):
# def min(self):
# def decay(self, waveform, t):
# def false_func():
. Output only the next line. | class CompositeController(core.Controller): |
Next line prediction: <|code_start|># 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 specific language governing permissions and
# limitations under the License.
def hessian(f, arg):
return jax.jacfwd(jax.jacrev(f, argnums=arg), argnums=arg)
def iLQR(
env,
cost,
U,
T,
k=None,
K=None,
X=None,
info="true",
start_state=None,
H=None,
verbose=True,
alpha=0.5,
backtracking=True,
):
r = 1
if H == None:
H = env.H
<|code_end|>
. Use current file imports:
(import os
import time
import jax.numpy as jnp
import jax
from deluca.igpc.rollout import rollout, compute_ders
from deluca.igpc.lqr_solver import LQR)
and context including class names, function names, or small code snippets from other files:
# Path: deluca/igpc/rollout.py
# @partial(jax.jit, static_argnums=(1,))
# def rollout(env,
# cost_func,
# U_old,
# k=None,
# K=None,
# X_old=None,
# alpha=1.0,
# H=None,
# start_state=None):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a
# derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# ## problematic
# # if H == None:
# # H = env.H
# H = env.H
# X, U = [None] * (H + 1), [None] * (H)
# if start_state is None:
# start_state = env.init()
# X[0], cost = start_state, 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# X_flat = X[h].flatten()
# X_old_flat = X_old[h].flatten()
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X_flat - X_old_flat)
#
# X[h + 1], _ = env(X[h], U[h])
# cost += cost_func(X[h], U[h], env)
# return X, U, cost
#
# def compute_ders(env, cost, X, U, H=None):
# D, F, C = compute_ders_inner(env, cost, X, U, H=None)
# F = list(zip(*F))
# C = list(zip(*C))
# return D, F, C
#
# Path: deluca/igpc/lqr_solver.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
#
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# # V_x, V_xx = jnp.zeros(d), jnp.zeros((d, d))
#
# # F_x, F_u = F
# # C_x, C_u, C_xx, C_uu = C
#
# # def loop(carry, args):
# # v_x, v_xx = carry
# # f_x, f_u, c_x, c_u, c_xx, c_uu = args
#
# # q_x, q_u = c_x + f_x.T @ v_x, c_u + f_u.T @ v_x
# # q_xx, q_ux, q_uu = (
# # c_xx + f_x.T @ v_xx @ f_x,
# # f_u.T @ v_xx @ f_x,
# # c_uu + f_u.T @ v_xx @ f_u,
# # )
#
# # K, k = -jnp.linalg.inv(q_uu) @ q_ux, -jnp.linalg.inv(q_uu) @ q_u
# # v_x = q_x - K.T @ q_uu @ k
# # v_xx = q_xx - K.T @ q_uu @ K
# # v_xx = (v_xx + v_xx.T) / 2
#
# # return (v_x, v_xx), (K, k)
#
# # _, (K, k) = jax.lax.scan(loop, (V_x, V_xx), (F_x, F_u, C_x, C_u, C_xx, C_uu))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
#
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
. Output only the next line. | X, U, c = rollout(env, cost, U, k, K, X, start_state=start_state, H=H) |
Using the snippet: <|code_start|>
def hessian(f, arg):
return jax.jacfwd(jax.jacrev(f, argnums=arg), argnums=arg)
def iLQR(
env,
cost,
U,
T,
k=None,
K=None,
X=None,
info="true",
start_state=None,
H=None,
verbose=True,
alpha=0.5,
backtracking=True,
):
r = 1
if H == None:
H = env.H
X, U, c = rollout(env, cost, U, k, K, X, start_state=start_state, H=H)
if verbose:
print(f"iLQR ({info}): t = -1, r = 1, c = {c}")
for t in range(T):
# s = time.time()
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import jax.numpy as jnp
import jax
from deluca.igpc.rollout import rollout, compute_ders
from deluca.igpc.lqr_solver import LQR
and context (class names, function names, or code) available:
# Path: deluca/igpc/rollout.py
# @partial(jax.jit, static_argnums=(1,))
# def rollout(env,
# cost_func,
# U_old,
# k=None,
# K=None,
# X_old=None,
# alpha=1.0,
# H=None,
# start_state=None):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a
# derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# ## problematic
# # if H == None:
# # H = env.H
# H = env.H
# X, U = [None] * (H + 1), [None] * (H)
# if start_state is None:
# start_state = env.init()
# X[0], cost = start_state, 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# X_flat = X[h].flatten()
# X_old_flat = X_old[h].flatten()
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X_flat - X_old_flat)
#
# X[h + 1], _ = env(X[h], U[h])
# cost += cost_func(X[h], U[h], env)
# return X, U, cost
#
# def compute_ders(env, cost, X, U, H=None):
# D, F, C = compute_ders_inner(env, cost, X, U, H=None)
# F = list(zip(*F))
# C = list(zip(*C))
# return D, F, C
#
# Path: deluca/igpc/lqr_solver.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
#
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# # V_x, V_xx = jnp.zeros(d), jnp.zeros((d, d))
#
# # F_x, F_u = F
# # C_x, C_u, C_xx, C_uu = C
#
# # def loop(carry, args):
# # v_x, v_xx = carry
# # f_x, f_u, c_x, c_u, c_xx, c_uu = args
#
# # q_x, q_u = c_x + f_x.T @ v_x, c_u + f_u.T @ v_x
# # q_xx, q_ux, q_uu = (
# # c_xx + f_x.T @ v_xx @ f_x,
# # f_u.T @ v_xx @ f_x,
# # c_uu + f_u.T @ v_xx @ f_u,
# # )
#
# # K, k = -jnp.linalg.inv(q_uu) @ q_ux, -jnp.linalg.inv(q_uu) @ q_u
# # v_x = q_x - K.T @ q_uu @ k
# # v_xx = q_xx - K.T @ q_uu @ K
# # v_xx = (v_xx + v_xx.T) / 2
#
# # return (v_x, v_xx), (K, k)
#
# # _, (K, k) = jax.lax.scan(loop, (V_x, V_xx), (F_x, F_u, C_x, C_u, C_xx, C_uu))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
#
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
. Output only the next line. | _, F, C = compute_ders(env, cost, X, U) |
Predict the next line for this snippet: <|code_start|>def hessian(f, arg):
return jax.jacfwd(jax.jacrev(f, argnums=arg), argnums=arg)
def iLQR(
env,
cost,
U,
T,
k=None,
K=None,
X=None,
info="true",
start_state=None,
H=None,
verbose=True,
alpha=0.5,
backtracking=True,
):
r = 1
if H == None:
H = env.H
X, U, c = rollout(env, cost, U, k, K, X, start_state=start_state, H=H)
if verbose:
print(f"iLQR ({info}): t = -1, r = 1, c = {c}")
for t in range(T):
# s = time.time()
_, F, C = compute_ders(env, cost, X, U)
# t = time.time()
# print('der time ', t-s)
<|code_end|>
with the help of current file imports:
import os
import time
import jax.numpy as jnp
import jax
from deluca.igpc.rollout import rollout, compute_ders
from deluca.igpc.lqr_solver import LQR
and context from other files:
# Path: deluca/igpc/rollout.py
# @partial(jax.jit, static_argnums=(1,))
# def rollout(env,
# cost_func,
# U_old,
# k=None,
# K=None,
# X_old=None,
# alpha=1.0,
# H=None,
# start_state=None):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a
# derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# ## problematic
# # if H == None:
# # H = env.H
# H = env.H
# X, U = [None] * (H + 1), [None] * (H)
# if start_state is None:
# start_state = env.init()
# X[0], cost = start_state, 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# X_flat = X[h].flatten()
# X_old_flat = X_old[h].flatten()
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X_flat - X_old_flat)
#
# X[h + 1], _ = env(X[h], U[h])
# cost += cost_func(X[h], U[h], env)
# return X, U, cost
#
# def compute_ders(env, cost, X, U, H=None):
# D, F, C = compute_ders_inner(env, cost, X, U, H=None)
# F = list(zip(*F))
# C = list(zip(*C))
# return D, F, C
#
# Path: deluca/igpc/lqr_solver.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
#
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# # V_x, V_xx = jnp.zeros(d), jnp.zeros((d, d))
#
# # F_x, F_u = F
# # C_x, C_u, C_xx, C_uu = C
#
# # def loop(carry, args):
# # v_x, v_xx = carry
# # f_x, f_u, c_x, c_u, c_xx, c_uu = args
#
# # q_x, q_u = c_x + f_x.T @ v_x, c_u + f_u.T @ v_x
# # q_xx, q_ux, q_uu = (
# # c_xx + f_x.T @ v_xx @ f_x,
# # f_u.T @ v_xx @ f_x,
# # c_uu + f_u.T @ v_xx @ f_u,
# # )
#
# # K, k = -jnp.linalg.inv(q_uu) @ q_ux, -jnp.linalg.inv(q_uu) @ q_u
# # v_x = q_x - K.T @ q_uu @ k
# # v_xx = q_xx - K.T @ q_uu @ K
# # v_xx = (v_xx + v_xx.T) / 2
#
# # return (v_x, v_xx), (K, k)
#
# # _, (K, k) = jax.lax.scan(loop, (V_x, V_xx), (F_x, F_u, C_x, C_u, C_xx, C_uu))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
#
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
, which may contain function names, class names, or code. Output only the next line. | k, K = LQR(F, C) |
Predict the next line for this snippet: <|code_start|> use_cached: whether or not to use self.cached_breaths
breath_length: length of a breath
Returns:
list of endpoints so that u_out[lo:hi] == 1
"""
if not use_cached or not hasattr(self, "cached_breaths"):
d_u_out = np.diff(self.u_out, prepend=1)
starts = np.where(d_u_out == -1)[0]
ends = np.where(d_u_out == 1)[0]
self.cached_breaths = list(zip(starts, ends))
# Return a single breath of the entire length
return self.cached_breaths or [(0, breath_length)]
###########################################################################
# Metric methods
###########################################################################
def losses_per_breath(self,
target,
clip=(0, None),
loss_fn=None,
breath_length=29):
"""compute losses per breath."""
# computes trapezoidally integrated loss per inferred breath
loss_fn = loss_fn or np.square
# handle polymorphic targets
<|code_end|>
with the help of current file imports:
import pickle
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from deluca.lung.core import BreathWaveform
and context from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
, which may contain function names, class names, or code. Output only the next line. | if isinstance(target, BreathWaveform): |
Predict the next line after this snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
def iLC_closed(
env_true,
env_sim,
cost_func,
U,
T,
k=None,
K=None,
X=None,
ref_alpha=1.0,
verbose=True,
backtracking=True,
):
alpha, r = ref_alpha, 1
<|code_end|>
using the current file's imports:
import os
import time
import jax.numpy as jnp
import jax
from deluca.igpc.rollout import rollout, compute_ders
from deluca.igpc.lqr_solver import LQR
and any relevant context from other files:
# Path: deluca/igpc/rollout.py
# @partial(jax.jit, static_argnums=(1,))
# def rollout(env,
# cost_func,
# U_old,
# k=None,
# K=None,
# X_old=None,
# alpha=1.0,
# H=None,
# start_state=None):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a
# derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# ## problematic
# # if H == None:
# # H = env.H
# H = env.H
# X, U = [None] * (H + 1), [None] * (H)
# if start_state is None:
# start_state = env.init()
# X[0], cost = start_state, 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# X_flat = X[h].flatten()
# X_old_flat = X_old[h].flatten()
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X_flat - X_old_flat)
#
# X[h + 1], _ = env(X[h], U[h])
# cost += cost_func(X[h], U[h], env)
# return X, U, cost
#
# def compute_ders(env, cost, X, U, H=None):
# D, F, C = compute_ders_inner(env, cost, X, U, H=None)
# F = list(zip(*F))
# C = list(zip(*C))
# return D, F, C
#
# Path: deluca/igpc/lqr_solver.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
#
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# # V_x, V_xx = jnp.zeros(d), jnp.zeros((d, d))
#
# # F_x, F_u = F
# # C_x, C_u, C_xx, C_uu = C
#
# # def loop(carry, args):
# # v_x, v_xx = carry
# # f_x, f_u, c_x, c_u, c_xx, c_uu = args
#
# # q_x, q_u = c_x + f_x.T @ v_x, c_u + f_u.T @ v_x
# # q_xx, q_ux, q_uu = (
# # c_xx + f_x.T @ v_xx @ f_x,
# # f_u.T @ v_xx @ f_x,
# # c_uu + f_u.T @ v_xx @ f_u,
# # )
#
# # K, k = -jnp.linalg.inv(q_uu) @ q_ux, -jnp.linalg.inv(q_uu) @ q_u
# # v_x = q_x - K.T @ q_uu @ k
# # v_xx = q_xx - K.T @ q_uu @ K
# # v_xx = (v_xx + v_xx.T) / 2
#
# # return (v_x, v_xx), (K, k)
#
# # _, (K, k) = jax.lax.scan(loop, (V_x, V_xx), (F_x, F_u, C_x, C_u, C_xx, C_uu))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
#
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
. Output only the next line. | X, U, c = rollout(env_true, cost_func, U, k, K, X) |
Continue the code snippet: <|code_start|># 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 "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.
def iLC_closed(
env_true,
env_sim,
cost_func,
U,
T,
k=None,
K=None,
X=None,
ref_alpha=1.0,
verbose=True,
backtracking=True,
):
alpha, r = ref_alpha, 1
X, U, c = rollout(env_true, cost_func, U, k, K, X)
print(f"iLC: t = {-1}, r = {r}, c = {c}")
prev_loop_fail = False
for t in range(T):
<|code_end|>
. Use current file imports:
import os
import time
import jax.numpy as jnp
import jax
from deluca.igpc.rollout import rollout, compute_ders
from deluca.igpc.lqr_solver import LQR
and context (classes, functions, or code) from other files:
# Path: deluca/igpc/rollout.py
# @partial(jax.jit, static_argnums=(1,))
# def rollout(env,
# cost_func,
# U_old,
# k=None,
# K=None,
# X_old=None,
# alpha=1.0,
# H=None,
# start_state=None):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a
# derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# ## problematic
# # if H == None:
# # H = env.H
# H = env.H
# X, U = [None] * (H + 1), [None] * (H)
# if start_state is None:
# start_state = env.init()
# X[0], cost = start_state, 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# X_flat = X[h].flatten()
# X_old_flat = X_old[h].flatten()
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X_flat - X_old_flat)
#
# X[h + 1], _ = env(X[h], U[h])
# cost += cost_func(X[h], U[h], env)
# return X, U, cost
#
# def compute_ders(env, cost, X, U, H=None):
# D, F, C = compute_ders_inner(env, cost, X, U, H=None)
# F = list(zip(*F))
# C = list(zip(*C))
# return D, F, C
#
# Path: deluca/igpc/lqr_solver.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
#
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# # V_x, V_xx = jnp.zeros(d), jnp.zeros((d, d))
#
# # F_x, F_u = F
# # C_x, C_u, C_xx, C_uu = C
#
# # def loop(carry, args):
# # v_x, v_xx = carry
# # f_x, f_u, c_x, c_u, c_xx, c_uu = args
#
# # q_x, q_u = c_x + f_x.T @ v_x, c_u + f_u.T @ v_x
# # q_xx, q_ux, q_uu = (
# # c_xx + f_x.T @ v_xx @ f_x,
# # f_u.T @ v_xx @ f_x,
# # c_uu + f_u.T @ v_xx @ f_u,
# # )
#
# # K, k = -jnp.linalg.inv(q_uu) @ q_ux, -jnp.linalg.inv(q_uu) @ q_u
# # v_x = q_x - K.T @ q_uu @ k
# # v_xx = q_xx - K.T @ q_uu @ K
# # v_xx = (v_xx + v_xx.T) / 2
#
# # return (v_x, v_xx), (K, k)
#
# # _, (K, k) = jax.lax.scan(loop, (V_x, V_xx), (F_x, F_u, C_x, C_u, C_xx, C_uu))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
#
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
. Output only the next line. | _, F, C = compute_ders(env_sim, cost_func, X, U) |
Based on the 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 specific language governing permissions and
# limitations under the License.
def iLC_closed(
env_true,
env_sim,
cost_func,
U,
T,
k=None,
K=None,
X=None,
ref_alpha=1.0,
verbose=True,
backtracking=True,
):
alpha, r = ref_alpha, 1
X, U, c = rollout(env_true, cost_func, U, k, K, X)
print(f"iLC: t = {-1}, r = {r}, c = {c}")
prev_loop_fail = False
for t in range(T):
_, F, C = compute_ders(env_sim, cost_func, X, U)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import time
import jax.numpy as jnp
import jax
from deluca.igpc.rollout import rollout, compute_ders
from deluca.igpc.lqr_solver import LQR
and context (classes, functions, sometimes code) from other files:
# Path: deluca/igpc/rollout.py
# @partial(jax.jit, static_argnums=(1,))
# def rollout(env,
# cost_func,
# U_old,
# k=None,
# K=None,
# X_old=None,
# alpha=1.0,
# H=None,
# start_state=None):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a
# derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# ## problematic
# # if H == None:
# # H = env.H
# H = env.H
# X, U = [None] * (H + 1), [None] * (H)
# if start_state is None:
# start_state = env.init()
# X[0], cost = start_state, 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# X_flat = X[h].flatten()
# X_old_flat = X_old[h].flatten()
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X_flat - X_old_flat)
#
# X[h + 1], _ = env(X[h], U[h])
# cost += cost_func(X[h], U[h], env)
# return X, U, cost
#
# def compute_ders(env, cost, X, U, H=None):
# D, F, C = compute_ders_inner(env, cost, X, U, H=None)
# F = list(zip(*F))
# C = list(zip(*C))
# return D, F, C
#
# Path: deluca/igpc/lqr_solver.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
#
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# # V_x, V_xx = jnp.zeros(d), jnp.zeros((d, d))
#
# # F_x, F_u = F
# # C_x, C_u, C_xx, C_uu = C
#
# # def loop(carry, args):
# # v_x, v_xx = carry
# # f_x, f_u, c_x, c_u, c_xx, c_uu = args
#
# # q_x, q_u = c_x + f_x.T @ v_x, c_u + f_u.T @ v_x
# # q_xx, q_ux, q_uu = (
# # c_xx + f_x.T @ v_xx @ f_x,
# # f_u.T @ v_xx @ f_x,
# # c_uu + f_u.T @ v_xx @ f_u,
# # )
#
# # K, k = -jnp.linalg.inv(q_uu) @ q_ux, -jnp.linalg.inv(q_uu) @ q_u
# # v_x = q_x - K.T @ q_uu @ k
# # v_xx = q_xx - K.T @ q_uu @ K
# # v_xx = (v_xx + v_xx.T) / 2
#
# # return (v_x, v_xx), (K, k)
#
# # _, (K, k) = jax.lax.scan(loop, (V_x, V_xx), (F_x, F_u, C_x, C_u, C_xx, C_uu))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
#
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
. Output only the next line. | k, K = LQR(F, C) |
Here is a snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
# from deluca.agents._ilqr import LQR
def iLC_closed(env_true, env_sim, U, T, k=None, K=None, X=None, ref_alpha=1.0, log=None):
alpha, r = ref_alpha, 1
X, U, c = rollout(env_true, U, k, K, X)
print("initial cost:" + str(c))
for t in range(T):
<|code_end|>
. Write the next line using the current file imports:
import jax.numpy as jnp
from deluca.agents.core import Agent
from deluca.utils.planning import f_at_x
from deluca.utils.planning import LQR
from deluca.utils.planning import rollout
and context from other files:
# Path: deluca/utils/planning.py
# def f_at_x(env, X, U, H=None):
# if H is None:
# H = env.H
# D, F, C = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# for h in range(H):
# D[h] = X[h + 1] - env.f(X[h], U[h])
# F[h] = env.f_x(X[h], U[h]), env.f_u(X[h], U[h])
# C[h] = (
# env.c_x(X[h], U[h]),
# env.c_u(X[h], U[h]),
# env.c_xx(X[h], U[h]),
# env.c_uu(X[h], U[h]),
# )
# return D, F, C
#
# Path: deluca/utils/planning.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
#
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
#
# Path: deluca/utils/planning.py
# def rollout(
# env, U_old, k=None, K=None, X_old=None, alpha=1.0, D=None, F=None, H=None, start_state=None,
# ):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# if H is None:
# H = env.H
# X, U = [None for _ in range(H + 1)], [None for _ in range(H)]
# if start_state is not None:
# X[0], cost = env.reset_model(start_state), 0.0
# else:
# X[0], cost = env.reset(), 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X[h] - X_old[h])
#
# if D is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# elif F is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# X[h + 1] += D[h]
# else:
# X[h + 1] = X_old[h + 1] + F[h][0] @ (X[h] - X_old[h]) + F[h][1] @ (U[h] - U_old[h])
# instant_cost = env.c(X[h], U[h], h)
#
# cost += instant_cost
# return X, U, cost
, which may include functions, classes, or code. Output only the next line. | _, F, C = f_at_x(env_sim, X, U) |
Continue the code snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
# from deluca.agents._ilqr import LQR
def iLC_closed(env_true, env_sim, U, T, k=None, K=None, X=None, ref_alpha=1.0, log=None):
alpha, r = ref_alpha, 1
X, U, c = rollout(env_true, U, k, K, X)
print("initial cost:" + str(c))
for t in range(T):
_, F, C = f_at_x(env_sim, X, U)
<|code_end|>
. Use current file imports:
import jax.numpy as jnp
from deluca.agents.core import Agent
from deluca.utils.planning import f_at_x
from deluca.utils.planning import LQR
from deluca.utils.planning import rollout
and context (classes, functions, or code) from other files:
# Path: deluca/utils/planning.py
# def f_at_x(env, X, U, H=None):
# if H is None:
# H = env.H
# D, F, C = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# for h in range(H):
# D[h] = X[h + 1] - env.f(X[h], U[h])
# F[h] = env.f_x(X[h], U[h]), env.f_u(X[h], U[h])
# C[h] = (
# env.c_x(X[h], U[h]),
# env.c_u(X[h], U[h]),
# env.c_xx(X[h], U[h]),
# env.c_uu(X[h], U[h]),
# )
# return D, F, C
#
# Path: deluca/utils/planning.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
#
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
#
# Path: deluca/utils/planning.py
# def rollout(
# env, U_old, k=None, K=None, X_old=None, alpha=1.0, D=None, F=None, H=None, start_state=None,
# ):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# if H is None:
# H = env.H
# X, U = [None for _ in range(H + 1)], [None for _ in range(H)]
# if start_state is not None:
# X[0], cost = env.reset_model(start_state), 0.0
# else:
# X[0], cost = env.reset(), 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X[h] - X_old[h])
#
# if D is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# elif F is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# X[h + 1] += D[h]
# else:
# X[h + 1] = X_old[h + 1] + F[h][0] @ (X[h] - X_old[h]) + F[h][1] @ (U[h] - U_old[h])
# instant_cost = env.c(X[h], U[h], h)
#
# cost += instant_cost
# return X, U, cost
. Output only the next line. | k, K = LQR(F, C) |
Given snippet: <|code_start|># limitations under the License.
"""PlanarQuadrotor."""
def dissipative(x, y, wind):
"""Dissipative wind function."""
return [wind * x, wind * y]
def constant(x, y, wind):
"""Constant wind function."""
return [wind * jnp.cos(jnp.pi / 4.0), wind * jnp.sin(jnp.pi / 4.0)]
class PlanarQuadrotorState(Obj):
"""PlanarQuadrotorState."""
arr: jnp.ndarray = field(jaxed=True)
h: float = field(0.0, jaxed=True)
last_action: jnp.ndarray = field(jaxed=True)
def flatten(self):
return self.arr
def unflatten(self, arr):
return PlanarQuadrotorState(arr=arr, h=self.h, last_action=self.last_action)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from typing import Callable
from typing import List
from deluca.core import Env
from deluca.core import field
from deluca.core import Obj
import jax.numpy as jnp
and context:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
#
# Path: deluca/core.py
# class Obj:
#
# def freeze(self):
# object.__setattr__(self, "__frozen__", True)
#
# def unfreeze(self):
# object.__setattr__(self, "__frozen__", False)
#
# def is_frozen(self):
# return not hasattr(self, "__frozen__") or getattr(self, "__frozen__")
#
# def __new__(cls, *args, **kwargs):
# """A true bastardization of __new__..."""
#
# def __setattr__(self, name, value):
# if self.is_frozen():
# raise dataclasses.FrozenInstanceError
# object.__setattr__(self, name, value)
#
# def replace(self, **updates):
# obj = dataclasses.replace(self, **updates)
# obj.freeze()
# return obj
#
# cls.__setattr__ = __setattr__
# cls.replace = replace
#
# obj = object.__new__(cls)
# obj.unfreeze()
#
# return obj
#
# @classmethod
# def __init_subclass__(cls, *args, **kwargs):
# flax.struct.dataclass(cls)
#
# @classmethod
# def create(cls, *args, **kwargs):
# # NOTE: Oh boy, this is so janky
# obj = cls(*args, **kwargs)
# obj.setup()
# obj.freeze()
#
# return obj
#
# @classmethod
# def unflatten(cls, treedef, leaves):
# """Expost a default unflatten method"""
# return jax.tree_util.tree_unflatten(treedef, leaves)
#
# def setup(self):
# """Used in place of __init__"""
#
# def flatten(self):
# """Expose a default flatten method"""
# return jax.tree_util.tree_flatten(self)[0]
which might include code, classes, or functions. Output only the next line. | class PlanarQuadrotor(Env): |
Given the following code snippet before the placeholder: <|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 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 specific language governing permissions and
# limitations under the License.
"""PlanarQuadrotor."""
def dissipative(x, y, wind):
"""Dissipative wind function."""
return [wind * x, wind * y]
def constant(x, y, wind):
"""Constant wind function."""
return [wind * jnp.cos(jnp.pi / 4.0), wind * jnp.sin(jnp.pi / 4.0)]
class PlanarQuadrotorState(Obj):
"""PlanarQuadrotorState."""
<|code_end|>
, predict the next line using imports from the current file:
from typing import Callable
from typing import List
from deluca.core import Env
from deluca.core import field
from deluca.core import Obj
import jax.numpy as jnp
and context including class names, function names, and sometimes code from other files:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
#
# Path: deluca/core.py
# class Obj:
#
# def freeze(self):
# object.__setattr__(self, "__frozen__", True)
#
# def unfreeze(self):
# object.__setattr__(self, "__frozen__", False)
#
# def is_frozen(self):
# return not hasattr(self, "__frozen__") or getattr(self, "__frozen__")
#
# def __new__(cls, *args, **kwargs):
# """A true bastardization of __new__..."""
#
# def __setattr__(self, name, value):
# if self.is_frozen():
# raise dataclasses.FrozenInstanceError
# object.__setattr__(self, name, value)
#
# def replace(self, **updates):
# obj = dataclasses.replace(self, **updates)
# obj.freeze()
# return obj
#
# cls.__setattr__ = __setattr__
# cls.replace = replace
#
# obj = object.__new__(cls)
# obj.unfreeze()
#
# return obj
#
# @classmethod
# def __init_subclass__(cls, *args, **kwargs):
# flax.struct.dataclass(cls)
#
# @classmethod
# def create(cls, *args, **kwargs):
# # NOTE: Oh boy, this is so janky
# obj = cls(*args, **kwargs)
# obj.setup()
# obj.freeze()
#
# return obj
#
# @classmethod
# def unflatten(cls, treedef, leaves):
# """Expost a default unflatten method"""
# return jax.tree_util.tree_unflatten(treedef, leaves)
#
# def setup(self):
# """Used in place of __init__"""
#
# def flatten(self):
# """Expose a default flatten method"""
# return jax.tree_util.tree_flatten(self)[0]
. Output only the next line. | arr: jnp.ndarray = field(jaxed=True) |
Given the code snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
"""PlanarQuadrotor."""
def dissipative(x, y, wind):
"""Dissipative wind function."""
return [wind * x, wind * y]
def constant(x, y, wind):
"""Constant wind function."""
return [wind * jnp.cos(jnp.pi / 4.0), wind * jnp.sin(jnp.pi / 4.0)]
<|code_end|>
, generate the next line using the imports in this file:
from typing import Callable
from typing import List
from deluca.core import Env
from deluca.core import field
from deluca.core import Obj
import jax.numpy as jnp
and context (functions, classes, or occasionally code) from other files:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
#
# Path: deluca/core.py
# class Obj:
#
# def freeze(self):
# object.__setattr__(self, "__frozen__", True)
#
# def unfreeze(self):
# object.__setattr__(self, "__frozen__", False)
#
# def is_frozen(self):
# return not hasattr(self, "__frozen__") or getattr(self, "__frozen__")
#
# def __new__(cls, *args, **kwargs):
# """A true bastardization of __new__..."""
#
# def __setattr__(self, name, value):
# if self.is_frozen():
# raise dataclasses.FrozenInstanceError
# object.__setattr__(self, name, value)
#
# def replace(self, **updates):
# obj = dataclasses.replace(self, **updates)
# obj.freeze()
# return obj
#
# cls.__setattr__ = __setattr__
# cls.replace = replace
#
# obj = object.__new__(cls)
# obj.unfreeze()
#
# return obj
#
# @classmethod
# def __init_subclass__(cls, *args, **kwargs):
# flax.struct.dataclass(cls)
#
# @classmethod
# def create(cls, *args, **kwargs):
# # NOTE: Oh boy, this is so janky
# obj = cls(*args, **kwargs)
# obj.setup()
# obj.freeze()
#
# return obj
#
# @classmethod
# def unflatten(cls, treedef, leaves):
# """Expost a default unflatten method"""
# return jax.tree_util.tree_unflatten(treedef, leaves)
#
# def setup(self):
# """Used in place of __init__"""
#
# def flatten(self):
# """Expose a default flatten method"""
# return jax.tree_util.tree_flatten(self)[0]
. Output only the next line. | class PlanarQuadrotorState(Obj): |
Predict the next line after this 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 specific language governing permissions and
# limitations under the License.
"""Single comp lung."""
class Observation(deluca.Obj):
predicted_pressure: float = 0.0
time: float = 0.0
class SimulatorState(deluca.Obj):
steps: int = 0
volume: float = 0.0
time: float = 0.0
def PropValve(x):
y = 3.0 * x
flow_new = 1.0 * (jnp.tanh(0.03 * (y - 130)) + 1.0)
flow_new = jnp.clip(flow_new, 0.0, 1.72)
return flow_new
<|code_end|>
using the current file's imports:
import deluca.core
import jax.numpy as jnp
from deluca.lung.core import LungEnv
and any relevant context from other files:
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
. Output only the next line. | class SingleCompLung(LungEnv): |
Continue the code snippet: <|code_start|># 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 "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.
"""bang bang controller."""
class BangBang(Controller):
"""bang bang controller."""
waveform: BreathWaveform = deluca.field(jaxed=False)
min_action: float = deluca.field(0.0, jaxed=False)
max_action: float = deluca.field(100.0, jaxed=False)
def setup(self):
if self.waveform is None:
self.waveform = BreathWaveform.create()
def __call__(self, controller_state, obs):
pressure, t = obs.predicted_pressure, obs.time
target = self.waveform.at(t)
action = jax.lax.cond(pressure < target, lambda x: self.max_action,
lambda x: self.min_action, None)
# update controller_state
new_dt = jnp.max(
<|code_end|>
. Use current file imports:
import deluca.core
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time
and context (classes, functions, or code) from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | jnp.array([DEFAULT_DT, t - proper_time(controller_state.time)])) |
Given snippet: <|code_start|># 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 "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.
"""bang bang controller."""
class BangBang(Controller):
"""bang bang controller."""
waveform: BreathWaveform = deluca.field(jaxed=False)
min_action: float = deluca.field(0.0, jaxed=False)
max_action: float = deluca.field(100.0, jaxed=False)
def setup(self):
if self.waveform is None:
self.waveform = BreathWaveform.create()
def __call__(self, controller_state, obs):
pressure, t = obs.predicted_pressure, obs.time
target = self.waveform.at(t)
action = jax.lax.cond(pressure < target, lambda x: self.max_action,
lambda x: self.min_action, None)
# update controller_state
new_dt = jnp.max(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import deluca.core
import jax
import jax.numpy as jnp
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import DEFAULT_DT
from deluca.lung.core import proper_time
and context:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# DEFAULT_DT = 0.03
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
which might include code, classes, or functions. Output only the next line. | jnp.array([DEFAULT_DT, t - proper_time(controller_state.time)])) |
Here is a snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
"""Tests for transform."""
class TransformTest(chex.TestCase):
def setUp(self):
super().setUp()
x = jnp.array([jnp.arange(5)])
<|code_end|>
. Write the next line using the current file imports:
from absl.testing import absltest
from deluca.lung.utils.data.transform import ShiftScaleTransform
import chex
import jax.numpy as jnp
and context from other files:
# Path: deluca/lung/utils/data/transform.py
# class ShiftScaleTransform:
# """Data normalizer."""
#
# # vectors is an array of vectors
# def __init__(self, vectors):
# vectors_concat = jnp.concatenate(vectors)
# self.mean = jnp.mean(vectors_concat)
# self.std = jnp.std(vectors_concat)
# print(self.mean, self.std)
#
# def _transform(self, x, mean, std):
# return (x - mean) / std
#
# def _inverse_transform(self, x, mean, std):
# return (x * std) + mean
#
# def __call__(self, vector):
# return self._transform(vector, self.mean, self.std)
#
# def inverse(self, vector):
# return self._inverse_transform(vector, self.mean, self.std)
, which may include functions, classes, or code. Output only the next line. | self.transform = ShiftScaleTransform(x) |
Predict the next line for this snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
"""Cartpole."""
# pylint:disable=invalid-name
class CartpoleState(Obj):
"""CartpoleState."""
arr: jnp.ndarray = field(jaxed=True)
h: int = field(0, jaxed=True)
offset: float = field(0.0, jaxed=False)
<|code_end|>
with the help of current file imports:
from deluca.core import Env
from deluca.core import field
from deluca.core import Obj
import jax.numpy as jnp
and context from other files:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
#
# Path: deluca/core.py
# class Obj:
#
# def freeze(self):
# object.__setattr__(self, "__frozen__", True)
#
# def unfreeze(self):
# object.__setattr__(self, "__frozen__", False)
#
# def is_frozen(self):
# return not hasattr(self, "__frozen__") or getattr(self, "__frozen__")
#
# def __new__(cls, *args, **kwargs):
# """A true bastardization of __new__..."""
#
# def __setattr__(self, name, value):
# if self.is_frozen():
# raise dataclasses.FrozenInstanceError
# object.__setattr__(self, name, value)
#
# def replace(self, **updates):
# obj = dataclasses.replace(self, **updates)
# obj.freeze()
# return obj
#
# cls.__setattr__ = __setattr__
# cls.replace = replace
#
# obj = object.__new__(cls)
# obj.unfreeze()
#
# return obj
#
# @classmethod
# def __init_subclass__(cls, *args, **kwargs):
# flax.struct.dataclass(cls)
#
# @classmethod
# def create(cls, *args, **kwargs):
# # NOTE: Oh boy, this is so janky
# obj = cls(*args, **kwargs)
# obj.setup()
# obj.freeze()
#
# return obj
#
# @classmethod
# def unflatten(cls, treedef, leaves):
# """Expost a default unflatten method"""
# return jax.tree_util.tree_unflatten(treedef, leaves)
#
# def setup(self):
# """Used in place of __init__"""
#
# def flatten(self):
# """Expose a default flatten method"""
# return jax.tree_util.tree_flatten(self)[0]
, which may contain function names, class names, or code. Output only the next line. | class Cartpole(Env): |
Predict the next line for this snippet: <|code_start|> B (jnp.ndarray): system dynamics
Q (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
R (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
K (jnp.ndarray): Starting policy (optional). Defaults to LQR gain.
start_time (int):
cost_fn (Callable[[jnp.ndarray, jnp.ndarray], Real]):
H (postive int): history of the controller
HH (positive int): history of the system
lr_scale (Real):
lr_scale_decay (Real):
decay (Real):
"""
cost_fn = cost_fn or quad_loss
d_state, d_action = B.shape # State & Action Dimensions
self.A, self.B = A, B # System Dynamics
self.t = 0 # Time Counter (for decaying learning rate)
self.H, self.HH = H, HH
self.lr_scale, self.decay = lr_scale, decay
self.bias = 0
# Model Parameters
# initial linear policy / perturbation contributions / bias
# TODO: need to address problem of LQR with jax.lax.scan
<|code_end|>
with the help of current file imports:
from numbers import Real
from typing import Callable
from jax import grad
from jax import jit
from deluca.agents._lqr import LQR
from deluca.agents.core import Agent
import jax
import jax.numpy as jnp
import numpy as np
and context from other files:
# Path: deluca/agents/_lqr.py
# class LQR(Agent):
# """
# LQR
# """
#
# # TODO: need to address problem of LQR with jax.lax.scan
#
# def __init__(
# self, A: jnp.ndarray, B: jnp.ndarray, Q: jnp.ndarray = None, R: jnp.ndarray = None
# ) -> None:
# """
# Description: Initialize the infinite-time horizon LQR.
# Args:
# A (jnp.ndarray): system dynamics
# B (jnp.ndarray): system dynamics
# Q (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
# R (jnp.ndarray): cost matrices (i.e. cost = x^TQx + u^TRu)
#
# Returns:
# None
# """
#
# state_size, action_size = B.shape
#
# if Q is None:
# Q = jnp.identity(state_size, dtype=jnp.float32)
#
# if R is None:
# R = jnp.identity(action_size, dtype=jnp.float32)
#
# # solve the ricatti equation
# X = dare(A, B, Q, R)
#
# # compute LQR gain
# self.K = jnp.linalg.inv(B.T @ X @ B + R) @ (B.T @ X @ A)
#
# def __call__(self, state) -> jnp.ndarray:
# """
# Description: Return the action based on current state and internal parameters.
#
# Args:
# state (float/numpy.ndarray): current state
#
# Returns:
# jnp.ndarray: action to take
# """
# return -self.K @ state
, which may contain function names, class names, or code. Output only the next line. | self.K = K if K is not None else LQR(self.A, self.B, Q, R).K |
Continue the code snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
"""Pendulum."""
class PendulumState(Obj):
"""PendulumState."""
arr: jnp.ndarray = field(jaxed=True)
h: int = field(0, jaxed=True)
<|code_end|>
. Use current file imports:
from deluca.core import Env
from deluca.core import field
from deluca.core import Obj
import jax.numpy as jnp
and context (classes, functions, or code) from other files:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
#
# Path: deluca/core.py
# class Obj:
#
# def freeze(self):
# object.__setattr__(self, "__frozen__", True)
#
# def unfreeze(self):
# object.__setattr__(self, "__frozen__", False)
#
# def is_frozen(self):
# return not hasattr(self, "__frozen__") or getattr(self, "__frozen__")
#
# def __new__(cls, *args, **kwargs):
# """A true bastardization of __new__..."""
#
# def __setattr__(self, name, value):
# if self.is_frozen():
# raise dataclasses.FrozenInstanceError
# object.__setattr__(self, name, value)
#
# def replace(self, **updates):
# obj = dataclasses.replace(self, **updates)
# obj.freeze()
# return obj
#
# cls.__setattr__ = __setattr__
# cls.replace = replace
#
# obj = object.__new__(cls)
# obj.unfreeze()
#
# return obj
#
# @classmethod
# def __init_subclass__(cls, *args, **kwargs):
# flax.struct.dataclass(cls)
#
# @classmethod
# def create(cls, *args, **kwargs):
# # NOTE: Oh boy, this is so janky
# obj = cls(*args, **kwargs)
# obj.setup()
# obj.freeze()
#
# return obj
#
# @classmethod
# def unflatten(cls, treedef, leaves):
# """Expost a default unflatten method"""
# return jax.tree_util.tree_unflatten(treedef, leaves)
#
# def setup(self):
# """Used in place of __init__"""
#
# def flatten(self):
# """Expose a default flatten method"""
# return jax.tree_util.tree_flatten(self)[0]
. Output only the next line. | class Pendulum(Env): |
Continue the code snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
"""functions to train controller."""
# from flax.metrics import tensorboard
# pylint: disable=invalid-name
# pylint: disable=dangerous-default-value
@functools.partial(jax.jit, static_argnums=(6,))
def rollout(controller, sim, tt, use_noise, peep, pip, loss_fn, loss):
"""rollout function."""
waveform = BreathWaveform.create(peep=peep, pip=pip)
<|code_end|>
. Use current file imports:
import copy
import functools
import jax
import jax.numpy as jnp
import optax
from clu import metric_writers
from deluca.lung.controllers._expiratory import Expiratory
from deluca.lung.core import BreathWaveform
from deluca.lung.utils.scripts.test_controller import test_controller
and context (classes, functions, or code) from other files:
# Path: deluca/lung/controllers/_expiratory.py
# class Expiratory(Controller):
# """Expiratory."""
# waveform: BreathWaveform = deluca.field(jaxed=False)
#
# # TODO(dsuo): Handle dataclass initialization of jax objects
# def setup(self):
# if self.waveform is None:
# self.waveform = BreathWaveform.create()
#
# @jax.jit
# def __call__(self, state, obs, *args, **kwargs):
# time = obs.time
# u_out = jax.lax.cond(
# self.waveform.is_in(time), lambda x: 0, lambda x: 1,
# jnp.zeros_like(time))
# new_dt = jnp.max(jnp.array([DEFAULT_DT, time - proper_time(state.time)]))
# new_time = time
# new_steps = state.steps + 1
# state = state.replace(time=new_time, steps=new_steps, dt=new_dt)
# return state, u_out
#
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/utils/scripts/test_controller.py
# @jax.jit
# def test_controller(controller, sim, pips, peep):
# """Test controller."""
# # new_controller = controller.replace(use_leaky_clamp=False)
# score = 0.0
# horizon = 29
# for pip in pips:
# waveform = BreathWaveform.create(peep=peep, pip=pip)
# result = run_controller_scan(
# controller,
# T=horizon,
# abort=horizon,
# env=sim,
# waveform=waveform,
# init_controller=True,
# )
# analyzer = Analyzer(result)
# preds = analyzer.pressure # shape = (29,)
# truth = analyzer.target # shape = (29,)
# # print('preds.shape: %s', str(preds.shape))
# # print('truth.shape: %s', str(truth.shape))
# score += jnp.abs(preds - truth).mean()
# score = score / len(pips)
# return score
. Output only the next line. | expiratory = Expiratory.create(waveform=waveform) |
Using the snippet: <|code_start|> cosine_scheduler_fn = optax.cosine_decay_schedule(
init_value=optim_params["learning_rate"], decay_steps=decay_steps)
optim_params["learning_rate"] = cosine_scheduler_fn
print("optim_params:" + str(optim_params))
optim = optimizer(**optim_params)
optim_state = optim.init(controller)
# setup Tensorboard writer
if tensorboard_dir is not None:
trial_name = str(model_parameters)
write_path = tensorboard_dir + trial_name
summary_writer = metric_writers.create_default_writer(
logdir=write_path, just_logging=jax.process_index() != 0)
# summary_writer = tensorboard.SummaryWriter(write_path)
summary_writer.write_hparams(model_parameters)
tt = jnp.linspace(0, duration, int(duration / dt))
losses = []
for epoch in range(epochs):
if pip_feed == "parallel":
value, grad = jax.value_and_grad(rollout_parallel)(controller, sim, tt,
use_noise, peep,
jnp.array(pips),
loss_fn)
updates, optim_state = optim.update(grad, optim_state, controller)
controller = optax.apply_updates(controller, updates)
per_step_loss = value / len(tt)
losses.append(per_step_loss)
if epoch % print_loss == 0:
# make new controller with trained parameters and normal clamp
<|code_end|>
, determine the next line of code. You have imports:
import copy
import functools
import jax
import jax.numpy as jnp
import optax
from clu import metric_writers
from deluca.lung.controllers._expiratory import Expiratory
from deluca.lung.core import BreathWaveform
from deluca.lung.utils.scripts.test_controller import test_controller
and context (class names, function names, or code) available:
# Path: deluca/lung/controllers/_expiratory.py
# class Expiratory(Controller):
# """Expiratory."""
# waveform: BreathWaveform = deluca.field(jaxed=False)
#
# # TODO(dsuo): Handle dataclass initialization of jax objects
# def setup(self):
# if self.waveform is None:
# self.waveform = BreathWaveform.create()
#
# @jax.jit
# def __call__(self, state, obs, *args, **kwargs):
# time = obs.time
# u_out = jax.lax.cond(
# self.waveform.is_in(time), lambda x: 0, lambda x: 1,
# jnp.zeros_like(time))
# new_dt = jnp.max(jnp.array([DEFAULT_DT, time - proper_time(state.time)]))
# new_time = time
# new_steps = state.steps + 1
# state = state.replace(time=new_time, steps=new_steps, dt=new_dt)
# return state, u_out
#
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/utils/scripts/test_controller.py
# @jax.jit
# def test_controller(controller, sim, pips, peep):
# """Test controller."""
# # new_controller = controller.replace(use_leaky_clamp=False)
# score = 0.0
# horizon = 29
# for pip in pips:
# waveform = BreathWaveform.create(peep=peep, pip=pip)
# result = run_controller_scan(
# controller,
# T=horizon,
# abort=horizon,
# env=sim,
# waveform=waveform,
# init_controller=True,
# )
# analyzer = Analyzer(result)
# preds = analyzer.pressure # shape = (29,)
# truth = analyzer.target # shape = (29,)
# # print('preds.shape: %s', str(preds.shape))
# # print('truth.shape: %s', str(truth.shape))
# score += jnp.abs(preds - truth).mean()
# score = score / len(pips)
# return score
. Output only the next line. | score = test_controller(controller, sim, pips, peep) |
Based on the snippet: <|code_start|> # 3 choices for w are f-g, (f-g)-(f-g last time), (f- LIN(g) with OFF).
if w_is == "de":
w = X[h + 1] - env_sim.f(X[h], U[h])
elif w_is == "dede":
w = (X[h + 1] - env_sim.f(X[h], U[h])) - D[h]
else:
w = X[h + 1] - (
X_old[h + 1] + F[h][0] @ (X[h] - X_old[h]) + F[h][1] @ (U[h] - U_old[h])
)
W = W.at[0].set(w)
W = jnp.roll(W, -1, axis=0)
if h >= H:
delta_E, delta_off = grad_loss(
E, off, W, H, M, X[h - H], h - H, env_sim, U_old, k, K, X_old, D, F, w_is, alpha, C,
)
E -= lr / h * delta_E
off -= lr / h * delta_off
# print(norm_U_old, norm_other, norm_off, norm_U_delta, norm_U_vals)
return X, U, cost
def igpc_closed(
env_true, env_sim, U, T, k=None, K=None, X=None, w_is="de", lr=None, ref_alpha=1.0, log=None
):
alpha, r = ref_alpha, 1
X, U, c = rollout(env_true, U, k, K, X)
print("initial cost:" + str(c))
assert w_is in ["de", "dede", "delin"]
for t in range(T):
<|code_end|>
, predict the immediate next line with the help of imports:
import jax
import jax.numpy as jnp
from deluca.agents.core import Agent
from deluca.utils.planning import f_at_x
from deluca.utils.planning import LQR
from deluca.utils.planning import rollout
and context (classes, functions, sometimes code) from other files:
# Path: deluca/utils/planning.py
# def f_at_x(env, X, U, H=None):
# if H is None:
# H = env.H
# D, F, C = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# for h in range(H):
# D[h] = X[h + 1] - env.f(X[h], U[h])
# F[h] = env.f_x(X[h], U[h]), env.f_u(X[h], U[h])
# C[h] = (
# env.c_x(X[h], U[h]),
# env.c_u(X[h], U[h]),
# env.c_xx(X[h], U[h]),
# env.c_uu(X[h], U[h]),
# )
# return D, F, C
#
# Path: deluca/utils/planning.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
#
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
#
# Path: deluca/utils/planning.py
# def rollout(
# env, U_old, k=None, K=None, X_old=None, alpha=1.0, D=None, F=None, H=None, start_state=None,
# ):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# if H is None:
# H = env.H
# X, U = [None for _ in range(H + 1)], [None for _ in range(H)]
# if start_state is not None:
# X[0], cost = env.reset_model(start_state), 0.0
# else:
# X[0], cost = env.reset(), 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X[h] - X_old[h])
#
# if D is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# elif F is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# X[h + 1] += D[h]
# else:
# X[h + 1] = X_old[h + 1] + F[h][0] @ (X[h] - X_old[h]) + F[h][1] @ (U[h] - U_old[h])
# instant_cost = env.c(X[h], U[h], h)
#
# cost += instant_cost
# return X, U, cost
. Output only the next line. | D, F, C = f_at_x(env_sim, X, U) |
Here is a snippet: <|code_start|> if w_is == "de":
w = X[h + 1] - env_sim.f(X[h], U[h])
elif w_is == "dede":
w = (X[h + 1] - env_sim.f(X[h], U[h])) - D[h]
else:
w = X[h + 1] - (
X_old[h + 1] + F[h][0] @ (X[h] - X_old[h]) + F[h][1] @ (U[h] - U_old[h])
)
W = W.at[0].set(w)
W = jnp.roll(W, -1, axis=0)
if h >= H:
delta_E, delta_off = grad_loss(
E, off, W, H, M, X[h - H], h - H, env_sim, U_old, k, K, X_old, D, F, w_is, alpha, C,
)
E -= lr / h * delta_E
off -= lr / h * delta_off
# print(norm_U_old, norm_other, norm_off, norm_U_delta, norm_U_vals)
return X, U, cost
def igpc_closed(
env_true, env_sim, U, T, k=None, K=None, X=None, w_is="de", lr=None, ref_alpha=1.0, log=None
):
alpha, r = ref_alpha, 1
X, U, c = rollout(env_true, U, k, K, X)
print("initial cost:" + str(c))
assert w_is in ["de", "dede", "delin"]
for t in range(T):
D, F, C = f_at_x(env_sim, X, U)
<|code_end|>
. Write the next line using the current file imports:
import jax
import jax.numpy as jnp
from deluca.agents.core import Agent
from deluca.utils.planning import f_at_x
from deluca.utils.planning import LQR
from deluca.utils.planning import rollout
and context from other files:
# Path: deluca/utils/planning.py
# def f_at_x(env, X, U, H=None):
# if H is None:
# H = env.H
# D, F, C = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# for h in range(H):
# D[h] = X[h + 1] - env.f(X[h], U[h])
# F[h] = env.f_x(X[h], U[h]), env.f_u(X[h], U[h])
# C[h] = (
# env.c_x(X[h], U[h]),
# env.c_u(X[h], U[h]),
# env.c_xx(X[h], U[h]),
# env.c_uu(X[h], U[h]),
# )
# return D, F, C
#
# Path: deluca/utils/planning.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
#
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
#
# Path: deluca/utils/planning.py
# def rollout(
# env, U_old, k=None, K=None, X_old=None, alpha=1.0, D=None, F=None, H=None, start_state=None,
# ):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# if H is None:
# H = env.H
# X, U = [None for _ in range(H + 1)], [None for _ in range(H)]
# if start_state is not None:
# X[0], cost = env.reset_model(start_state), 0.0
# else:
# X[0], cost = env.reset(), 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X[h] - X_old[h])
#
# if D is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# elif F is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# X[h + 1] += D[h]
# else:
# X[h + 1] = X_old[h + 1] + F[h][0] @ (X[h] - X_old[h]) + F[h][1] @ (U[h] - U_old[h])
# instant_cost = env.c(X[h], U[h], h)
#
# cost += instant_cost
# return X, U, cost
, which may include functions, classes, or code. Output only the next line. | k, K = LQR(F, C) |
Predict the next line after this snippet: <|code_start|> U[h] = U_old[h] + alpha * k[h] + K[h] @ (X[h] - X_old[h]) + C * U_delta[h]
X[h + 1], instant_cost, _, _ = env_true.step(U[h])
cost += instant_cost
# 3 choices for w are f-g, (f-g)-(f-g last time), (f- LIN(g) with OFF).
if w_is == "de":
w = X[h + 1] - env_sim.f(X[h], U[h])
elif w_is == "dede":
w = (X[h + 1] - env_sim.f(X[h], U[h])) - D[h]
else:
w = X[h + 1] - (
X_old[h + 1] + F[h][0] @ (X[h] - X_old[h]) + F[h][1] @ (U[h] - U_old[h])
)
W = W.at[0].set(w)
W = jnp.roll(W, -1, axis=0)
if h >= H:
delta_E, delta_off = grad_loss(
E, off, W, H, M, X[h - H], h - H, env_sim, U_old, k, K, X_old, D, F, w_is, alpha, C,
)
E -= lr / h * delta_E
off -= lr / h * delta_off
# print(norm_U_old, norm_other, norm_off, norm_U_delta, norm_U_vals)
return X, U, cost
def igpc_closed(
env_true, env_sim, U, T, k=None, K=None, X=None, w_is="de", lr=None, ref_alpha=1.0, log=None
):
alpha, r = ref_alpha, 1
<|code_end|>
using the current file's imports:
import jax
import jax.numpy as jnp
from deluca.agents.core import Agent
from deluca.utils.planning import f_at_x
from deluca.utils.planning import LQR
from deluca.utils.planning import rollout
and any relevant context from other files:
# Path: deluca/utils/planning.py
# def f_at_x(env, X, U, H=None):
# if H is None:
# H = env.H
# D, F, C = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# for h in range(H):
# D[h] = X[h + 1] - env.f(X[h], U[h])
# F[h] = env.f_x(X[h], U[h]), env.f_u(X[h], U[h])
# C[h] = (
# env.c_x(X[h], U[h]),
# env.c_u(X[h], U[h]),
# env.c_xx(X[h], U[h]),
# env.c_uu(X[h], U[h]),
# )
# return D, F, C
#
# Path: deluca/utils/planning.py
# def LQR(F, C):
# H, d = len(C), C[0][0].shape[0]
# K, k = (
# [None for _ in range(H)],
# [None for _ in range(H)],
# )
# V_x, V_xx = np.zeros(d), np.zeros((d, d))
# for h in range(H - 1, -1, -1):
# f_x, f_u = F[h]
# c_x, c_u, c_xx, c_uu = C[h]
# Q_x, Q_u = c_x + f_x.T @ V_x, c_u + f_u.T @ V_x
# Q_xx, Q_ux, Q_uu = (
# c_xx + f_x.T @ V_xx @ f_x,
# f_u.T @ V_xx @ f_x,
# c_uu + f_u.T @ V_xx @ f_u,
# )
#
# K[h], k[h] = -np.linalg.inv(Q_uu) @ Q_ux, -np.linalg.inv(Q_uu) @ Q_u
# V_x = Q_x - K[h].T @ Q_uu @ k[h]
# V_xx = Q_xx - K[h].T @ Q_uu @ K[h]
# V_xx = (V_xx + V_xx.T) / 2
# return k, K
#
# Path: deluca/utils/planning.py
# def rollout(
# env, U_old, k=None, K=None, X_old=None, alpha=1.0, D=None, F=None, H=None, start_state=None,
# ):
# """
# Arg List
# env: The environment to do the rollout on. This is treated as a derstructible copy.
# U_old: A base open loop control sequence
# k: open loop gain (iLQR)
# K: closed loop gain (iLQR)
# X_old: Previous trajectory to compute gain (iLQR)
# alpha: Optional multplier to the open loop gain (iLQR)
# D: Optional noise vectors for the rollout (GPC)
# F: Linearization shift ??? (GPC)
# H: The horizon length to perform a rollout.
# """
# if H is None:
# H = env.H
# X, U = [None for _ in range(H + 1)], [None for _ in range(H)]
# if start_state is not None:
# X[0], cost = env.reset_model(start_state), 0.0
# else:
# X[0], cost = env.reset(), 0.0
# for h in range(H):
# if k is None:
# U[h] = U_old[h]
# else:
# U[h] = U_old[h] + alpha * k[h] + K[h] @ (X[h] - X_old[h])
#
# if D is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# elif F is None:
# X[h + 1], instant_cost, _, _ = env.step(U[h])
# X[h + 1] += D[h]
# else:
# X[h + 1] = X_old[h + 1] + F[h][0] @ (X[h] - X_old[h]) + F[h][1] @ (U[h] - U_old[h])
# instant_cost = env.c(X[h], U[h], h)
#
# cost += instant_cost
# return X, U, cost
. Output only the next line. | X, U, c = rollout(env_true, U, k, K, X) |
Given the code snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
"""Tests for deluca-lung."""
# pylint: disable=invalid-name
class BreathWaveformTest(chex.TestCase):
def test_pip(self):
pip = 10
<|code_end|>
, generate the next line using the imports in this file:
from absl.testing import absltest
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import LungEnv
from deluca.lung.core import LungEnvState
from deluca.lung.core import proper_time
import chex
import jax.numpy as jnp
and context (functions, classes, or occasionally code) from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
#
# Path: deluca/lung/core.py
# class LungEnvState(deluca.Obj):
# t_in: int = 0
# steps: int = 0
# predicted_pressure: float = 0.0
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | waveform = BreathWaveform.create(peep=0, pip=10) |
Predict the next line after this snippet: <|code_start|> state = LungEnvState(
t_in=0.03,
steps=1,
predicted_pressure=0.0,
)
self.assertEqual(lung.time(state), 0.03)
def test_dt(self):
lung = LungEnv()
self.assertEqual(lung.dt, 0.03)
def test_physical(self):
lung = LungEnv()
self.assertEqual(lung.physical, False)
def test_should_abort(self):
lung = LungEnv()
self.assertEqual(lung.should_abort(), False)
class proper_timeTest(chex.TestCase):
def test_proper_time(self):
self.assertEqual(proper_time(float('inf')), 0)
self.assertEqual(proper_time(10.0), 10.0)
class ControllerTest(chex.TestCase):
def test_init(self):
<|code_end|>
using the current file's imports:
from absl.testing import absltest
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import LungEnv
from deluca.lung.core import LungEnvState
from deluca.lung.core import proper_time
import chex
import jax.numpy as jnp
and any relevant context from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
#
# Path: deluca/lung/core.py
# class LungEnvState(deluca.Obj):
# t_in: int = 0
# steps: int = 0
# predicted_pressure: float = 0.0
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | controller = Controller() |
Based on the snippet: <|code_start|> def test_is_in(self):
waveform = BreathWaveform.create()
self.assertEqual(waveform.is_in(0.5), True)
self.assertEqual(waveform.is_in(1.0), True)
self.assertEqual(waveform.is_in(1.5), False)
def test_is_ex(self):
waveform = BreathWaveform.create()
self.assertEqual(waveform.is_ex(0.5), False)
self.assertEqual(waveform.is_ex(1.0), False)
self.assertEqual(waveform.is_ex(1.5), True)
def test_at(self):
waveform = BreathWaveform.create()
self.assertEqual(waveform.at(0.), 35.0)
self.assertEqual(waveform.at(0.5), 35.0)
self.assertEqual(waveform.at(1.0), 35.0)
self.assertEqual(waveform.at(1.25), 20.0)
self.assertEqual(waveform.at(1.5), 5)
self.assertEqual(waveform.at(3.0), 35.0)
def test_elapsed(self):
waveform = BreathWaveform.create()
assert jnp.allclose(
waveform.elapsed(1.3), waveform.elapsed(1.3 + waveform.period))
class LungEnvTest(chex.TestCase):
def test_time(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import LungEnv
from deluca.lung.core import LungEnvState
from deluca.lung.core import proper_time
import chex
import jax.numpy as jnp
and context (classes, functions, sometimes code) from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
#
# Path: deluca/lung/core.py
# class LungEnvState(deluca.Obj):
# t_in: int = 0
# steps: int = 0
# predicted_pressure: float = 0.0
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | lung = LungEnv() |
Based on the snippet: <|code_start|> waveform = BreathWaveform.create()
self.assertEqual(waveform.is_in(0.5), True)
self.assertEqual(waveform.is_in(1.0), True)
self.assertEqual(waveform.is_in(1.5), False)
def test_is_ex(self):
waveform = BreathWaveform.create()
self.assertEqual(waveform.is_ex(0.5), False)
self.assertEqual(waveform.is_ex(1.0), False)
self.assertEqual(waveform.is_ex(1.5), True)
def test_at(self):
waveform = BreathWaveform.create()
self.assertEqual(waveform.at(0.), 35.0)
self.assertEqual(waveform.at(0.5), 35.0)
self.assertEqual(waveform.at(1.0), 35.0)
self.assertEqual(waveform.at(1.25), 20.0)
self.assertEqual(waveform.at(1.5), 5)
self.assertEqual(waveform.at(3.0), 35.0)
def test_elapsed(self):
waveform = BreathWaveform.create()
assert jnp.allclose(
waveform.elapsed(1.3), waveform.elapsed(1.3 + waveform.period))
class LungEnvTest(chex.TestCase):
def test_time(self):
lung = LungEnv()
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import LungEnv
from deluca.lung.core import LungEnvState
from deluca.lung.core import proper_time
import chex
import jax.numpy as jnp
and context (classes, functions, sometimes code) from other files:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
#
# Path: deluca/lung/core.py
# class LungEnvState(deluca.Obj):
# t_in: int = 0
# steps: int = 0
# predicted_pressure: float = 0.0
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | state = LungEnvState( |
Using the snippet: <|code_start|> waveform.elapsed(1.3), waveform.elapsed(1.3 + waveform.period))
class LungEnvTest(chex.TestCase):
def test_time(self):
lung = LungEnv()
state = LungEnvState(
t_in=0.03,
steps=1,
predicted_pressure=0.0,
)
self.assertEqual(lung.time(state), 0.03)
def test_dt(self):
lung = LungEnv()
self.assertEqual(lung.dt, 0.03)
def test_physical(self):
lung = LungEnv()
self.assertEqual(lung.physical, False)
def test_should_abort(self):
lung = LungEnv()
self.assertEqual(lung.should_abort(), False)
class proper_timeTest(chex.TestCase):
def test_proper_time(self):
<|code_end|>
, determine the next line of code. You have imports:
from absl.testing import absltest
from deluca.lung.core import BreathWaveform
from deluca.lung.core import Controller
from deluca.lung.core import LungEnv
from deluca.lung.core import LungEnvState
from deluca.lung.core import proper_time
import chex
import jax.numpy as jnp
and context (class names, function names, or code) available:
# Path: deluca/lung/core.py
# class BreathWaveform(deluca.Obj):
# r"""Waveform generator with shape |‾\_."""
# peep: float = deluca.field(5., jaxed=False)
# pip: float = deluca.field(35., jaxed=False)
# bpm: int = deluca.field(20, jaxed=False)
# fp: jnp.array = deluca.field(jaxed=False)
# xp: jnp.array = deluca.field(jaxed=False)
# in_bounds: Tuple[int, int] = deluca.field((0, 1), jaxed=False)
# ex_bounds: Tuple[int, int] = deluca.field((2, 4), jaxed=False)
# period: float = deluca.field(jaxed=False)
# dt: float = deluca.field(DEFAULT_DT, jaxed=False)
# dtype: jax._src.numpy.lax_numpy._ScalarMeta = deluca.field(
# jnp.float32, jaxed=False)
#
# def setup(self):
# if self.fp is None:
# self.fp = jnp.array([self.pip, self.pip, self.peep, self.peep, self.pip])
# if self.xp is None:
# self.xp = jnp.array(DEFAULT_XP)
# self.period = 60 / self.bpm
#
# def at(self, t):
#
# @functools.partial(jax.jit, static_argnums=(3,))
# def static_interp(t, xp, fp, period):
# return jnp.interp(t, xp, fp, period=period)
#
# return static_interp(t, self.xp, self.fp, self.period).astype(self.dtype)
#
# def elapsed(self, t):
# return t % self.period
#
# def is_in(self, t):
# return self.elapsed(t) <= self.xp[self.in_bounds[1]]
#
# def is_ex(self, t):
# return not self.is_in(t)
#
# Path: deluca/lung/core.py
# class Controller(deluca.Agent):
# """Controller."""
#
# def init(self, waveform=None):
# if waveform is None:
# waveform = BreathWaveform.create()
# return ControllerState()
#
# @property
# def max(self):
# return 100
#
# @property
# def min(self):
# return 0
#
# def decay(self, waveform, t):
# elapsed = waveform.elapsed(t)
#
# def false_func():
# result = jax.lax.cond(
# elapsed < waveform.xp[waveform.ex_bounds[0]], lambda x: 0.0,
# lambda x: 5 * (1 - jnp.exp(5 * (waveform.xp[waveform.ex_bounds[
# 0]] - elapsed))).astype(waveform.dtype), None)
# return result
#
# # float(inf) as substitute to None since cond requries same type output
# result = jax.lax.cond(elapsed < waveform.xp[waveform.in_bounds[1]],
# lambda x: float("inf"), lambda x: false_func(), None)
# return result
#
# Path: deluca/lung/core.py
# class LungEnv(deluca.Env):
# """Lung environment."""
#
# def time(self, state):
# return self.dt * state.steps
#
# @property
# def dt(self):
# return DEFAULT_DT
#
# @property
# def physical(self):
# return False
#
# def should_abort(self):
# return False
#
# def wait(self, duration):
# pass
#
# def cleanup(self):
# pass
#
# Path: deluca/lung/core.py
# class LungEnvState(deluca.Obj):
# t_in: int = 0
# steps: int = 0
# predicted_pressure: float = 0.0
#
# Path: deluca/lung/core.py
# def proper_time(t):
# return jax.lax.cond(t == float("inf"), lambda x: 0., lambda x: x, t)
. Output only the next line. | self.assertEqual(proper_time(float('inf')), 0) |
Predict the next line after this snippet: <|code_start|> logging.info("decay_steps: %s", str(decay_steps))
cosine_scheduler_fn = optax.cosine_decay_schedule(
init_value=optimizer_params["learning_rate"], decay_steps=decay_steps)
optimizer_params["learning_rate"] = cosine_scheduler_fn
logging.info("optimizer_params: %s", str(optimizer_params))
optim = optimizer(**optimizer_params)
optim_state = optim.init(model)
loop_over_loader_partial = functools.partial(
loop_over_loader, optim=optim, rollout_fn=rollout, scheduler=scheduler)
# Tensorboard writer
if use_tensorboard:
config = copy.deepcopy(model.default_model_parameters)
del config["activation_fn"]
config["activation_fn_name"] = activation_fn_name
if mode == "train":
file_name = str(config)
write_path = tb_dir + file_name
summary_writer = metric_writers.create_default_writer(
logdir=write_path, just_logging=jax.process_index() != 0)
summary_writer = tensorboard.SummaryWriter(write_path)
summary_writer.write_hparams(dict(config))
# Main Training Loop
prng_key = jax.random.PRNGKey(0)
for epoch in range(epochs + 1):
if epoch % 10 == 0:
logging.info("epoch: %s", str(epoch))
<|code_end|>
using the current file's imports:
import copy
import functools
import jax
import jax.numpy as jnp
import optax
from absl import logging
from clu import metric_writers
from deluca.lung.utils.data.breath_dataset import get_shuffled_and_batched_data
from flax.metrics import tensorboard
and any relevant context from other files:
# Path: deluca/lung/utils/data/breath_dataset.py
# def get_shuffled_and_batched_data(dataset, batch_size, key, prng_key):
# """function to shuffle and batch data."""
# x, y = dataset.data[key]
# x = jax.random.permutation(prng_key, x)
# y = jax.random.permutation(prng_key, y)
# prng_key, _ = jax.random.split(prng_key)
# num_batches = x.shape[0] // batch_size
# trunc_len = num_batches * batch_size
# trunc_x = x[:trunc_len]
# trunc_y = y[:trunc_len]
# batched_x = jnp.reshape(trunc_x, (num_batches, batch_size, trunc_x.shape[1]))
# batched_y = jnp.reshape(trunc_y, (num_batches, batch_size, trunc_y.shape[1]))
# return batched_x, batched_y, prng_key
. Output only the next line. | X, y, prng_key = get_shuffled_and_batched_data(dataset, batch_size, |
Here is a snippet: <|code_start|> """ReacherState.
Attributes:
arr:
h:
"""
arr: jnp.ndarray = field(jaxed=True)
h: float = field(0.0, jaxed=True)
def flatten(self):
"""flatten.
Returns:
"""
return self.arr
# TODO(dsuo): this should be a classmethod.
def unflatten(self, arr):
"""unflatten.
Args:
arr:
Returns:
"""
return ReacherState(arr=arr, h=self.h)
<|code_end|>
. Write the next line using the current file imports:
from deluca.core import Env
from deluca.core import field
from deluca.core import Obj
import jax.numpy as jnp
and context from other files:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
#
# Path: deluca/core.py
# class Obj:
#
# def freeze(self):
# object.__setattr__(self, "__frozen__", True)
#
# def unfreeze(self):
# object.__setattr__(self, "__frozen__", False)
#
# def is_frozen(self):
# return not hasattr(self, "__frozen__") or getattr(self, "__frozen__")
#
# def __new__(cls, *args, **kwargs):
# """A true bastardization of __new__..."""
#
# def __setattr__(self, name, value):
# if self.is_frozen():
# raise dataclasses.FrozenInstanceError
# object.__setattr__(self, name, value)
#
# def replace(self, **updates):
# obj = dataclasses.replace(self, **updates)
# obj.freeze()
# return obj
#
# cls.__setattr__ = __setattr__
# cls.replace = replace
#
# obj = object.__new__(cls)
# obj.unfreeze()
#
# return obj
#
# @classmethod
# def __init_subclass__(cls, *args, **kwargs):
# flax.struct.dataclass(cls)
#
# @classmethod
# def create(cls, *args, **kwargs):
# # NOTE: Oh boy, this is so janky
# obj = cls(*args, **kwargs)
# obj.setup()
# obj.freeze()
#
# return obj
#
# @classmethod
# def unflatten(cls, treedef, leaves):
# """Expost a default unflatten method"""
# return jax.tree_util.tree_unflatten(treedef, leaves)
#
# def setup(self):
# """Used in place of __init__"""
#
# def flatten(self):
# """Expose a default flatten method"""
# return jax.tree_util.tree_flatten(self)[0]
, which may include functions, classes, or code. Output only the next line. | class Reacher(Env): |
Given snippet: <|code_start|># Copyright 2022 The Deluca 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 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 specific language governing permissions and
# limitations under the License.
"""Reacher."""
# pylint:disable=invalid-name
class ReacherState(Obj):
"""ReacherState.
Attributes:
arr:
h:
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from deluca.core import Env
from deluca.core import field
from deluca.core import Obj
import jax.numpy as jnp
and context:
# Path: deluca/core.py
# class Env(Obj):
#
# @abstractmethod
# def init(self):
# """Return an initialized state"""
#
# @abstractmethod
# def __call__(self, state, action, *args, **kwargs):
# """Return an updated state"""
#
# Path: deluca/core.py
# def field(default=None, jaxed=True, **kwargs):
# if "default_factory" not in kwargs:
# kwargs["default"] = default
# kwargs["pytree_node"] = jaxed
# return flax.struct.field(**kwargs)
#
# Path: deluca/core.py
# class Obj:
#
# def freeze(self):
# object.__setattr__(self, "__frozen__", True)
#
# def unfreeze(self):
# object.__setattr__(self, "__frozen__", False)
#
# def is_frozen(self):
# return not hasattr(self, "__frozen__") or getattr(self, "__frozen__")
#
# def __new__(cls, *args, **kwargs):
# """A true bastardization of __new__..."""
#
# def __setattr__(self, name, value):
# if self.is_frozen():
# raise dataclasses.FrozenInstanceError
# object.__setattr__(self, name, value)
#
# def replace(self, **updates):
# obj = dataclasses.replace(self, **updates)
# obj.freeze()
# return obj
#
# cls.__setattr__ = __setattr__
# cls.replace = replace
#
# obj = object.__new__(cls)
# obj.unfreeze()
#
# return obj
#
# @classmethod
# def __init_subclass__(cls, *args, **kwargs):
# flax.struct.dataclass(cls)
#
# @classmethod
# def create(cls, *args, **kwargs):
# # NOTE: Oh boy, this is so janky
# obj = cls(*args, **kwargs)
# obj.setup()
# obj.freeze()
#
# return obj
#
# @classmethod
# def unflatten(cls, treedef, leaves):
# """Expost a default unflatten method"""
# return jax.tree_util.tree_unflatten(treedef, leaves)
#
# def setup(self):
# """Used in place of __init__"""
#
# def flatten(self):
# """Expose a default flatten method"""
# return jax.tree_util.tree_flatten(self)[0]
which might include code, classes, or functions. Output only the next line. | arr: jnp.ndarray = field(jaxed=True) |
Using the snippet: <|code_start|>
class DataLoader:
def __init__(self, data=[], data_type='', amino_acid_property=[]):
"""
:param data: list with the information required to access data in json file
:param data_type: str must be one of the following: 'CDR_positions', 'NumberingSchemes' or 'AminoAcidProperties'
:param amino_acid_property: temporary parameter
:param misc: temporary parameter
"""
self.amino_acid_property = amino_acid_property
<|code_end|>
, determine the next line of code. You have imports:
import json
from abpytools.home import Home
and context (class names, function names, or code) available:
# Path: abpytools/home.py
# class Home:
#
# def __init__(self):
#
# self.homedir = os.path.dirname(os.path.abspath(__file__))
. Output only the next line. | self.directory_name = Home().homedir |
Given the code snippet: <|code_start|> result = self._align(self.target, seq, **kwargs)
self._aligned_collection[seq.name] = result[0]
self._alignment_scores[seq.name] = result[1]
self._aligned = True
def print_aligned_sequences(self):
if not self._aligned:
raise ValueError("Method align_sequences must be called first to perform alignment.")
final_string = self._aligned_sequences_string()
print(*final_string, sep='\n')
@property
def target_sequence(self):
return self.target.sequence
@property
def aligned_sequences(self):
return self._aligned_collection
@property
def score(self):
return self._alignment_scores
def _align(self, seq_1, seq_2, **kwargs):
# loads the function object that is then called
<|code_end|>
, generate the next line using the imports in this file:
from .analysis_helper_functions import load_alignment_algorithm, load_substitution_matrix
and context (functions, classes, or occasionally code) from other files:
# Path: abpytools/analysis/analysis_helper_functions.py
# def load_alignment_algorithm(algorithm):
# if algorithm.lower() == 'needleman_wunsch':
# return needleman_wunsch
#
# else:
# raise ValueError("Unknown algorithm")
#
# def load_substitution_matrix(substitution_matrix):
#
# abpytools_directory = Home().homedir
#
# if substitution_matrix in SUPPORTED_SUBSITUTION_MATRICES:
# with open('{}/data/{}.txt'.format(abpytools_directory, substitution_matrix), 'rb') as f:
# matrix = cPickle.load(f)
# else:
# raise ValueError("Unknown substitution matrix")
#
# return matrix
. Output only the next line. | self._algorithm_function = load_alignment_algorithm(self._algorithm) |
Here is a snippet: <|code_start|>
class SequenceAlignment:
"""
Sequence alignment with two chain objects
"""
def __init__(self, target, collection, algorithm, substitution_matrix):
"""
:param chain_1:
:param collection:
:param algorithm:
:param substitution_matrix:
"""
self._algorithm = algorithm
<|code_end|>
. Write the next line using the current file imports:
from .analysis_helper_functions import load_alignment_algorithm, load_substitution_matrix
and context from other files:
# Path: abpytools/analysis/analysis_helper_functions.py
# def load_alignment_algorithm(algorithm):
# if algorithm.lower() == 'needleman_wunsch':
# return needleman_wunsch
#
# else:
# raise ValueError("Unknown algorithm")
#
# def load_substitution_matrix(substitution_matrix):
#
# abpytools_directory = Home().homedir
#
# if substitution_matrix in SUPPORTED_SUBSITUTION_MATRICES:
# with open('{}/data/{}.txt'.format(abpytools_directory, substitution_matrix), 'rb') as f:
# matrix = cPickle.load(f)
# else:
# raise ValueError("Unknown substitution matrix")
#
# return matrix
, which may include functions, classes, or code. Output only the next line. | self._substitution_matrix = load_substitution_matrix(substitution_matrix) |
Given the code snippet: <|code_start|>
class CacheTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.data = [[0, 1], 'n', ('tuple', 0), 3.1415]
cls.names = ['a', 'b', 'c', 'd']
cls.data_dict = {key: value for key, value in zip(cls.names, cls.data)}
def test_cache_instantiation(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from abpytools.core.cache import Cache
and context (functions, classes, or occasionally code) from other files:
# Path: abpytools/core/cache.py
# class Cache:
# def __init__(self, max_cache_size=10):
# self.max_cache_size = max_cache_size
# self.cache = {}
# self._cache_size = 0
# self._cache_keys = []
#
# def update(self, key, data, override=True):
# # make space if the cache is full and override is True
# if len(self) >= self.max_cache_size and override:
# self._clear_cache()
#
# if len(self) >= self.max_cache_size and not override:
# raise ValueError("Cache is full, either increase the size of cache, "
# "remove items from cache or allow override")
#
# if key not in self:
# self.add(key, data)
#
# def _clear_cache(self):
# while len(self) >= self.max_cache_size:
# # clear up cache until reaching max_cache_size - 1
# self.remove(self._cache_keys[0])
#
# def remove(self, key):
# self.cache.pop(key)
# self._cache_keys.pop(self._cache_keys.index(key))
# self._cache_size -= 1
#
# def add(self, key, data):
# self.cache[key] = data
# self._cache_keys.append(key)
# self._cache_size += 1
#
# def empty_cache(self):
# self.cache = {}
# self._cache_keys = []
# self._cache_size = 0
#
# def _string_summary_basic(self):
# return "abpytools.Cache size: {}".format(len(self))
#
# def __getitem__(self, item):
# return self.cache[item]
#
# def __contains__(self, item):
# if item in self._cache_keys:
# return True
# else:
# return False
#
# def __len__(self):
# return self._cache_size
#
# def __repr__(self):
# return "<%s at 0x%02x>" % (self._string_summary_basic(), id(self))
#
# def __setitem__(self, key, value):
# self.update(key, value)
. Output only the next line. | cache = Cache() |
Given snippet: <|code_start|> if only_cdr3:
if plot_title is None:
ax.set_title('CDR3 Length', size=18)
else:
ax.set_title(plot_title, size=18)
sns.distplot(self.cdr_lengths()[:, 2], hist=hist, ax=ax, **kwargs)
ax.set_ylabel('Density', size=14)
ax.set_xlabel('CDR Length', size=14)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
else:
if plot_title is None:
plt.suptitle('CDR Length', size=20)
else:
plt.suptitle(plot_title, size=20)
for i, cdr in enumerate(['CDR 1', 'CDR 2', 'CDR 3']):
ax[i].set_title(cdr, size=16)
sns.distplot(self.cdr_lengths()[:, i], hist=hist, ax=ax[i])
if i == 0:
ax[i].set_ylabel('Density', size=16)
if i == 1:
ax[i].set_xlabel('CDR Length', size=16)
ax[i].xaxis.set_major_locator(MaxNLocator(integer=True))
plt.tight_layout()
plt.subplots_adjust(top=0.85)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from matplotlib import pyplot as plt
from abpytools.utils import PythonConfig
from abpytools.features.regions import ChainDomains
from matplotlib.ticker import MaxNLocator
from .analysis_helper_functions import switch_interactive_mode
import seaborn as sns
import os
and context:
# Path: abpytools/utils/python_config.py
# class PythonConfig:
# def __init__(self):
# self._backend = get_ipython_info()
# self._matplotlib_interactive = plt.isinteractive()
#
# @property
# def ipython_info(self):
# return self._backend
#
# @property
# def matplotlib_interactive(self):
# return self._matplotlib_interactive # pragma: no cover
#
# Path: abpytools/features/regions.py
# class ChainDomains(ChainCollection):
#
# def __init__(self, antibody_objects=None, path=None, verbose=True, show_progressbar=True, n_threads=10):
# super().__init__(antibody_objects=antibody_objects)
# if antibody_objects:
# self.load()
# else:
# self.__init__(antibody_objects=ChainCollection.load_from_file(path=path, verbose=verbose,
# show_progressbar=show_progressbar,
# n_threads=n_threads))
#
# self._cache = Cache(max_cache_size=5)
#
# def cdr_lengths(self):
# """
# method to obtain cdr_lengths
# :return: m by n matrix with CDR lengths, where m is the number of antibodies in ChainCollection and n is
# three, corresponding to the three CDRs.
# """
#
# if 'cdr_lengths' not in self._cache:
#
# cdr_length_matrix = np.zeros((self.n_ab, 3), dtype=np.int)
# cdr_sequences = self.cdr_sequences()
#
# for m, antibody in enumerate(self.antibody_objects):
# for n, cdr in enumerate(['CDR1', 'CDR2', 'CDR3']):
# cdr_length_matrix[m, n] = len(cdr_sequences[antibody.name][cdr])
#
# self._cache.update(key='cdr_lengths', data=cdr_length_matrix)
#
# return self._cache['cdr_lengths']
#
# def cdr_sequences(self):
# """
# method that returns sequences of each cdr
# :return: list of dictionaries with keys 'CDR1', 'CDR2' and 'CDR3' containing a string with the respective amino
# acid sequence
# """
#
# if 'cdr_sequences' not in self._cache:
#
# cdr_sequences = dict()
#
# for antibody in self.antibody_objects:
# dict_i = dict()
# for cdr in ['CDR1', 'CDR2', 'CDR3']:
# self.sequence_splitter_helper(antibody=antibody,
# region=cdr,
# index=0,
# dict_i=dict_i)
# cdr_sequences[antibody.name] = dict_i
#
# self._cache.update(key='cdr_sequences', data=cdr_sequences)
#
# return self._cache['cdr_sequences']
#
# def framework_length(self):
# framework_length_matrix = np.zeros((self.n_ab, 4), dtype=np.int)
# fr_sequences = self.framework_sequences()
# for m, antibody in enumerate(self.antibody_objects):
# for n, framework in enumerate(['FR1', 'FR2', 'FR3', 'FR4']):
# framework_length_matrix[m, n] = len(fr_sequences[antibody.name][framework])
#
# return framework_length_matrix
#
# def framework_sequences(self):
#
# framework_sequences = dict()
#
# for antibody in self.antibody_objects:
# dict_i = dict()
# for framework in ['FR1', 'FR2', 'FR3', 'FR4']:
# self.sequence_splitter_helper(antibody=antibody,
# region=framework,
# index=1,
# dict_i=dict_i)
# framework_sequences[antibody.name] = dict_i
#
# return framework_sequences
#
# @staticmethod
# def sequence_splitter_helper(antibody, region, index, dict_i):
# seq_i = list()
# indices = antibody.ab_regions()[index][region]
# for i in indices:
# seq_i.append(antibody.sequence[i])
# dict_i[region] = ''.join(seq_i)
#
# Path: abpytools/analysis/analysis_helper_functions.py
# def switch_interactive_mode(save=False):
# ipython_config = PythonConfig()
# if ipython_config.ipython_info == 'notebook' and save is False:
# if ipython_config.matplotlib_interactive is False:
# # turns on interactive mode
# plt.ion()
which might include code, classes, or functions. Output only the next line. | ipython_config = PythonConfig() |
Given the following code snippet before the placeholder: <|code_start|>
class CDRLength(ChainDomains):
def __init__(self, path=None, antibody_objects=None, verbose=True, show_progressbar=True, n_threads=10):
super().__init__(path=path, antibody_objects=antibody_objects, verbose=verbose,
show_progressbar=show_progressbar, n_threads=n_threads)
def plot_cdr(self, only_cdr3=True, save=False, plot_path='./', plot_name='CDR_length',
plot_title=None, hist=True, ax=None, **kwargs):
<|code_end|>
, predict the next line using imports from the current file:
from matplotlib import pyplot as plt
from abpytools.utils import PythonConfig
from abpytools.features.regions import ChainDomains
from matplotlib.ticker import MaxNLocator
from .analysis_helper_functions import switch_interactive_mode
import seaborn as sns
import os
and context including class names, function names, and sometimes code from other files:
# Path: abpytools/utils/python_config.py
# class PythonConfig:
# def __init__(self):
# self._backend = get_ipython_info()
# self._matplotlib_interactive = plt.isinteractive()
#
# @property
# def ipython_info(self):
# return self._backend
#
# @property
# def matplotlib_interactive(self):
# return self._matplotlib_interactive # pragma: no cover
#
# Path: abpytools/features/regions.py
# class ChainDomains(ChainCollection):
#
# def __init__(self, antibody_objects=None, path=None, verbose=True, show_progressbar=True, n_threads=10):
# super().__init__(antibody_objects=antibody_objects)
# if antibody_objects:
# self.load()
# else:
# self.__init__(antibody_objects=ChainCollection.load_from_file(path=path, verbose=verbose,
# show_progressbar=show_progressbar,
# n_threads=n_threads))
#
# self._cache = Cache(max_cache_size=5)
#
# def cdr_lengths(self):
# """
# method to obtain cdr_lengths
# :return: m by n matrix with CDR lengths, where m is the number of antibodies in ChainCollection and n is
# three, corresponding to the three CDRs.
# """
#
# if 'cdr_lengths' not in self._cache:
#
# cdr_length_matrix = np.zeros((self.n_ab, 3), dtype=np.int)
# cdr_sequences = self.cdr_sequences()
#
# for m, antibody in enumerate(self.antibody_objects):
# for n, cdr in enumerate(['CDR1', 'CDR2', 'CDR3']):
# cdr_length_matrix[m, n] = len(cdr_sequences[antibody.name][cdr])
#
# self._cache.update(key='cdr_lengths', data=cdr_length_matrix)
#
# return self._cache['cdr_lengths']
#
# def cdr_sequences(self):
# """
# method that returns sequences of each cdr
# :return: list of dictionaries with keys 'CDR1', 'CDR2' and 'CDR3' containing a string with the respective amino
# acid sequence
# """
#
# if 'cdr_sequences' not in self._cache:
#
# cdr_sequences = dict()
#
# for antibody in self.antibody_objects:
# dict_i = dict()
# for cdr in ['CDR1', 'CDR2', 'CDR3']:
# self.sequence_splitter_helper(antibody=antibody,
# region=cdr,
# index=0,
# dict_i=dict_i)
# cdr_sequences[antibody.name] = dict_i
#
# self._cache.update(key='cdr_sequences', data=cdr_sequences)
#
# return self._cache['cdr_sequences']
#
# def framework_length(self):
# framework_length_matrix = np.zeros((self.n_ab, 4), dtype=np.int)
# fr_sequences = self.framework_sequences()
# for m, antibody in enumerate(self.antibody_objects):
# for n, framework in enumerate(['FR1', 'FR2', 'FR3', 'FR4']):
# framework_length_matrix[m, n] = len(fr_sequences[antibody.name][framework])
#
# return framework_length_matrix
#
# def framework_sequences(self):
#
# framework_sequences = dict()
#
# for antibody in self.antibody_objects:
# dict_i = dict()
# for framework in ['FR1', 'FR2', 'FR3', 'FR4']:
# self.sequence_splitter_helper(antibody=antibody,
# region=framework,
# index=1,
# dict_i=dict_i)
# framework_sequences[antibody.name] = dict_i
#
# return framework_sequences
#
# @staticmethod
# def sequence_splitter_helper(antibody, region, index, dict_i):
# seq_i = list()
# indices = antibody.ab_regions()[index][region]
# for i in indices:
# seq_i.append(antibody.sequence[i])
# dict_i[region] = ''.join(seq_i)
#
# Path: abpytools/analysis/analysis_helper_functions.py
# def switch_interactive_mode(save=False):
# ipython_config = PythonConfig()
# if ipython_config.ipython_info == 'notebook' and save is False:
# if ipython_config.matplotlib_interactive is False:
# # turns on interactive mode
# plt.ion()
. Output only the next line. | switch_interactive_mode(save=save) |
Given the code snippet: <|code_start|>
available_regions = ['FR1', 'CDR1', 'FR2', 'CDR2', 'FR3', 'CDR3', 'FR4']
def numbering_table_sequences(region, numbering_scheme, chain):
# next two conditionals are used to only extract the needed data with FR and CDR positions
# it makes the loading of the data quicker when there are only CDRs or FRs
if any([True if x.startswith('CDR') else False for x in region]):
<|code_end|>
, generate the next line using the imports in this file:
from ..utils import DataLoader
import itertools
import pandas as pd
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: abpytools/utils/data_loader.py
# class DataLoader:
#
# def __init__(self, data=[], data_type='', amino_acid_property=[]):
#
# """
#
# :param data: list with the information required to access data in json file
# :param data_type: str must be one of the following: 'CDR_positions', 'NumberingSchemes' or 'AminoAcidProperties'
# :param amino_acid_property: temporary parameter
# :param misc: temporary parameter
# """
# self.amino_acid_property = amino_acid_property
# self.directory_name = Home().homedir
# self.data = data
# self.data_types = ['CDR_positions', 'NumberingSchemes', 'AminoAcidProperties', 'Framework_positions']
#
# if data_type not in self.data_types:
# raise ValueError("{} is not a valid data type. Available data types: {}".format(
# data_type, ', '.join(self.data_types)))
# else:
# self.data_type = data_type
#
# # checks values when object is instantiated
# if self.data_type == 'CDR_positions' or self.data_type == 'NumberingSchemes' \
# or self.data_type == 'Framework_positions':
# if len(self.data) != 2:
# raise ValueError("Expected 2, instead of {} values.".format(len(self.data)))
# if self.data[0] not in ['chothia', 'kabat', 'chothia_ext']:
# raise ValueError("Got {}, but only {} is available".format(self.data[0], 'chothia'))
# if self.data[1] not in ["light", "heavy"]:
# raise ValueError("Got {}, but only light and heavy are available".format(self.data[1]))
# else:
# if len(self.data) != 2:
# raise ValueError("Expected 2, instead of {} values.".format(len(self.data)))
# if self.data[0] not in ["hydrophobicity", "pI", "MolecularWeight", "ExtinctionCoefficient"]:
# raise ValueError("Got {}, but only {} are available".format(self.data[0],
# """hydrophobicity, pI, ExtinctionCoefficient
# and MolecularWeight"""))
#
# if self.data[1] not in ["kdHydrophobicity", "wwHydrophobicity", "hhHydrophobicity", "mfHydrophobicity",
# "ewHydrophobicity", "EMBOSS", "DTASetect", "Solomon", "Sillero", "Rodwell",
# "Wikipedia", "Lehninger", "Grimsley", "average", "monoisotopic", "Standard",
# "Standard_reduced"]:
# raise ValueError("Got {}, but only {} are available".format(self.data[1],
# """
# kdHydrophobicity ,wwHydrophobicity,
# hhHydrophobicity, mfHydrophobicity,
# ewHydrophobicity, EMBOSS, DTASetect,
# Solomon, Sillero, Rodwell,
# Wikipedia, Lehninger, Grimsley,
# average, monoisotopic, Standard and
# Standard_reduced
# """
# ))
#
# def get_data(self):
#
# if self.data_type == 'CDR_positions':
# with open('{}/data/CDR_positions.json'.format(self.directory_name), 'r') as f:
# # need to access numbering scheme and chain type
# data = json.load(f)[self.data[0]][self.data[1]]
# elif self.data_type == 'Framework_positions':
# with open('{}/data/Framework_positions.json'.format(self.directory_name), 'r') as f:
# # need to access numbering scheme and chain type
# data = json.load(f)[self.data[0]][self.data[1]]
# elif self.data_type == 'NumberingSchemes':
# with open('{}/data/NumberingSchemes.json'.format(self.directory_name), 'r') as f:
# # need to access numbering scheme and chain type
# data = json.load(f)[self.data[0]][self.data[1]]
# else:
# with open('{}/data/AminoAcidProperties.json'.format(self.directory_name), 'r') as f:
# data = json.load(f)[self.data[0]][self.data[1]]
#
# return data
. Output only the next line. | cdr_list = DataLoader(data_type='CDR_positions', |
Next line prediction: <|code_start|>
SUPPORTED_SUBSITUTION_MATRICES = ['BLOSUM45', 'BLOSUM62', 'BLOSUM80']
def load_alignment_algorithm(algorithm):
if algorithm.lower() == 'needleman_wunsch':
return needleman_wunsch
else:
raise ValueError("Unknown algorithm")
def load_substitution_matrix(substitution_matrix):
<|code_end|>
. Use current file imports:
(import warnings
import _pickle as cPickle
import matplotlib.pyplot as plt
from abpytools.home import Home
from ..utils.python_config import PythonConfig)
and context including class names, function names, or small code snippets from other files:
# Path: abpytools/home.py
# class Home:
#
# def __init__(self):
#
# self.homedir = os.path.dirname(os.path.abspath(__file__))
#
# Path: abpytools/utils/python_config.py
# class PythonConfig:
# def __init__(self):
# self._backend = get_ipython_info()
# self._matplotlib_interactive = plt.isinteractive()
#
# @property
# def ipython_info(self):
# return self._backend
#
# @property
# def matplotlib_interactive(self):
# return self._matplotlib_interactive # pragma: no cover
. Output only the next line. | abpytools_directory = Home().homedir |
Predict the next line after this snippet: <|code_start|> while current != 'done':
# is aligned
if current == 'diag':
# aligned_seq_1.append(next(iter_seq_1))
# aligned_seq_2.append(next(iter_seq_2))
# aligned_seq_1.append(seq_1[column])
aligned_seq_2.append(seq_2[row])
row -= 1
column -= 1
# leave a gap
elif current == 'left':
# aligned_seq_1.append(next(iter_seq_1))
# aligned_seq_1.append(seq_1[column])
aligned_seq_2.append('-')
column -= 1
# leave a gap
else:
# aligned_seq_1.append(next(iter_seq_1))
# aligned_seq_1.append(seq_1[column])
aligned_seq_2.append('-')
row -= 1
current = traceback_matrix[row][column]
return ''.join(aligned_seq_2)[::-1]
def switch_interactive_mode(save=False):
<|code_end|>
using the current file's imports:
import warnings
import _pickle as cPickle
import matplotlib.pyplot as plt
from abpytools.home import Home
from ..utils.python_config import PythonConfig
and any relevant context from other files:
# Path: abpytools/home.py
# class Home:
#
# def __init__(self):
#
# self.homedir = os.path.dirname(os.path.abspath(__file__))
#
# Path: abpytools/utils/python_config.py
# class PythonConfig:
# def __init__(self):
# self._backend = get_ipython_info()
# self._matplotlib_interactive = plt.isinteractive()
#
# @property
# def ipython_info(self):
# return self._backend
#
# @property
# def matplotlib_interactive(self):
# return self._matplotlib_interactive # pragma: no cover
. Output only the next line. | ipython_config = PythonConfig() |
Using the snippet: <|code_start|>
urlpatterns = [
re_path(r'^app/', include('app.urls')),
re_path(r'^api/', include('api.urls')),
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from django.conf.urls import include, url
from django.conf import settings
from app import views
from django.conf.urls.static import static, serve
from django.urls import re_path
and context (class names, function names, or code) available:
# Path: app/views.py
# def index(request):
# def flags_new(request):
# def flags_all(request):
# def open_flags(request):
# def flag(request, flag_id):
# def sh0ts_new(request):
# def sh0ts_all(request):
# def sh0t(request, sh0t_id):
# def assessments_new(request):
# def assessments_all(request):
# def assessment(request, assessment_id):
# def projects_new(request):
# def projects_all(request):
# def project(request, project_id):
# def templates(request):
# def template(request, template_id):
# def case_masters(request):
# def case_master(request, case_master_id):
# def module_masters(request):
# def module_master(request, module_master_id):
# def methodology_masters(request):
# def methodology_master(request, methodology_id):
# def logout_user(request):
. Output only the next line. | re_path(r'^logout/$', views.logout_user), |
Given the code snippet: <|code_start|>
sh00t_path = dirname(dirname(abspath(__file__)))
sys.path.append(sh00t_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sh00t.settings")
django.setup()
first_timer = False
for arg in sys.argv:
if "first_timer" == arg:
first_timer = True
break
if first_timer:
answer = "yes"
else:
print("If you have setup Sh00t in this directory before, this action will reset everything and set up as fresh.")
print("Are sure you wanna do this?")
answer = input("[No] | Yes?\n") or ""
if "yes" == answer.lower():
order = ""
description_consolidated = ""
CaseMaster.objects.all().delete()
ModuleMaster.objects.all().delete()
<|code_end|>
, generate the next line using the imports in this file:
import json
import os
import django
import sys
from os.path import dirname, abspath
from configuration.models import MethodologyMaster, ModuleMaster, CaseMaster
from app.models import Project
and context (functions, classes, or occasionally code) from other files:
# Path: configuration/models.py
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | MethodologyMaster.objects.all().delete() |
Using the snippet: <|code_start|>
sh00t_path = dirname(dirname(abspath(__file__)))
sys.path.append(sh00t_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sh00t.settings")
django.setup()
first_timer = False
for arg in sys.argv:
if "first_timer" == arg:
first_timer = True
break
if first_timer:
answer = "yes"
else:
print("If you have setup Sh00t in this directory before, this action will reset everything and set up as fresh.")
print("Are sure you wanna do this?")
answer = input("[No] | Yes?\n") or ""
if "yes" == answer.lower():
order = ""
description_consolidated = ""
CaseMaster.objects.all().delete()
<|code_end|>
, determine the next line of code. You have imports:
import json
import os
import django
import sys
from os.path import dirname, abspath
from configuration.models import MethodologyMaster, ModuleMaster, CaseMaster
from app.models import Project
and context (class names, function names, or code) available:
# Path: configuration/models.py
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | ModuleMaster.objects.all().delete() |
Given snippet: <|code_start|>
sh00t_path = dirname(dirname(abspath(__file__)))
sys.path.append(sh00t_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sh00t.settings")
django.setup()
first_timer = False
for arg in sys.argv:
if "first_timer" == arg:
first_timer = True
break
if first_timer:
answer = "yes"
else:
print("If you have setup Sh00t in this directory before, this action will reset everything and set up as fresh.")
print("Are sure you wanna do this?")
answer = input("[No] | Yes?\n") or ""
if "yes" == answer.lower():
order = ""
description_consolidated = ""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import os
import django
import sys
from os.path import dirname, abspath
from configuration.models import MethodologyMaster, ModuleMaster, CaseMaster
from app.models import Project
and context:
# Path: configuration/models.py
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
which might include code, classes, or functions. Output only the next line. | CaseMaster.objects.all().delete() |
Given the following code snippet before the placeholder: <|code_start|>
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('name', 'added')
class AssessmentSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from app.models import Project, Assessment, Sh0t, Flag, Template
from configuration.models import CaseMaster, ModuleMaster, MethodologyMaster
from rest_framework import serializers
and context including class names, function names, and sometimes code from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | model = Assessment |
Predict the next line after this snippet: <|code_start|>
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('name', 'added')
class AssessmentSerializer(serializers.ModelSerializer):
class Meta:
model = Assessment
fields = ('name', 'added', 'project')
class FlagSerializer(serializers.ModelSerializer):
class Meta:
model = Flag
fields = ('id', 'title', 'note', 'done', 'assessment')
class Sh0tSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
using the current file's imports:
from app.models import Project, Assessment, Sh0t, Flag, Template
from configuration.models import CaseMaster, ModuleMaster, MethodologyMaster
from rest_framework import serializers
and any relevant context from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | model = Sh0t |
Given the code snippet: <|code_start|>
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('name', 'added')
class AssessmentSerializer(serializers.ModelSerializer):
class Meta:
model = Assessment
fields = ('name', 'added', 'project')
class FlagSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
from app.models import Project, Assessment, Sh0t, Flag, Template
from configuration.models import CaseMaster, ModuleMaster, MethodologyMaster
from rest_framework import serializers
and context (functions, classes, or occasionally code) from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | model = Flag |
Given the following code snippet before the placeholder: <|code_start|>
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('name', 'added')
class AssessmentSerializer(serializers.ModelSerializer):
class Meta:
model = Assessment
fields = ('name', 'added', 'project')
class FlagSerializer(serializers.ModelSerializer):
class Meta:
model = Flag
fields = ('id', 'title', 'note', 'done', 'assessment')
class Sh0tSerializer(serializers.ModelSerializer):
class Meta:
model = Sh0t
fields = ('title', 'severity', 'body', 'added', 'assessment')
class TemplateSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from app.models import Project, Assessment, Sh0t, Flag, Template
from configuration.models import CaseMaster, ModuleMaster, MethodologyMaster
from rest_framework import serializers
and context including class names, function names, and sometimes code from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | model = Template |
Given snippet: <|code_start|> model = Project
fields = ('name', 'added')
class AssessmentSerializer(serializers.ModelSerializer):
class Meta:
model = Assessment
fields = ('name', 'added', 'project')
class FlagSerializer(serializers.ModelSerializer):
class Meta:
model = Flag
fields = ('id', 'title', 'note', 'done', 'assessment')
class Sh0tSerializer(serializers.ModelSerializer):
class Meta:
model = Sh0t
fields = ('title', 'severity', 'body', 'added', 'assessment')
class TemplateSerializer(serializers.ModelSerializer):
class Meta:
model = Template
fields = ('name', 'body')
class CaseMasterSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from app.models import Project, Assessment, Sh0t, Flag, Template
from configuration.models import CaseMaster, ModuleMaster, MethodologyMaster
from rest_framework import serializers
and context:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
which might include code, classes, or functions. Output only the next line. | model = CaseMaster |
Using the snippet: <|code_start|> model = Assessment
fields = ('name', 'added', 'project')
class FlagSerializer(serializers.ModelSerializer):
class Meta:
model = Flag
fields = ('id', 'title', 'note', 'done', 'assessment')
class Sh0tSerializer(serializers.ModelSerializer):
class Meta:
model = Sh0t
fields = ('title', 'severity', 'body', 'added', 'assessment')
class TemplateSerializer(serializers.ModelSerializer):
class Meta:
model = Template
fields = ('name', 'body')
class CaseMasterSerializer(serializers.ModelSerializer):
class Meta:
model = CaseMaster
fields = ('name', 'description', 'order', 'module')
class ModuleMasterSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, determine the next line of code. You have imports:
from app.models import Project, Assessment, Sh0t, Flag, Template
from configuration.models import CaseMaster, ModuleMaster, MethodologyMaster
from rest_framework import serializers
and context (class names, function names, or code) available:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | model = ModuleMaster |
Given the code snippet: <|code_start|> model = Flag
fields = ('id', 'title', 'note', 'done', 'assessment')
class Sh0tSerializer(serializers.ModelSerializer):
class Meta:
model = Sh0t
fields = ('title', 'severity', 'body', 'added', 'assessment')
class TemplateSerializer(serializers.ModelSerializer):
class Meta:
model = Template
fields = ('name', 'body')
class CaseMasterSerializer(serializers.ModelSerializer):
class Meta:
model = CaseMaster
fields = ('name', 'description', 'order', 'module')
class ModuleMasterSerializer(serializers.ModelSerializer):
class Meta:
model = ModuleMaster
fields = ('name', 'description', 'order', 'methodology')
class MethodologyMasterSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
from app.models import Project, Assessment, Sh0t, Flag, Template
from configuration.models import CaseMaster, ModuleMaster, MethodologyMaster
from rest_framework import serializers
and context (functions, classes, or occasionally code) from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | model = MethodologyMaster |
Given the following code snippet before the placeholder: <|code_start|>USE_L10N = True
USE_TZ = True
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_USERNAME = "sh00t"
DEFAULT_PASSWORD = DEFAULT_USERNAME
LOGIN_URL = '/admin/login/'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'app/static'),
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAdminUser',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 20,
}
SECRET_FILE = os.path.join(THIS_DIR, 'secret.txt')
try:
SECRET_KEY
except NameError:
<|code_end|>
, predict the next line using imports from the current file:
import os
from .utils import get_secret_key
and context including class names, function names, and sometimes code from other files:
# Path: sh00t/utils.py
# def get_secret_key(secret_file):
# secret_key = " "
# # Do not create secret for migrate
# if "manage.py" == sys.argv[0]:
# if "migrate" == sys.argv[1]:
# return secret_key
#
# try:
# secret_key = open(secret_file).read().strip()
# except IOError:
# secret_key = generate_secret_key(secret_file)
# return secret_key
. Output only the next line. | SECRET_KEY = get_secret_key(SECRET_FILE) # Defined in utils.py |
Given the following code snippet before the placeholder: <|code_start|>
class ProjectTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
name = tables.TemplateColumn('<a href="/app/project/{{ record.pk }}"> {{ record.name }}</a>')
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
import django_tables2 as tables
from .models import Project, Flag, Sh0t, Assessment, Project
and context including class names, function names, and sometimes code from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | model = Project |
Predict the next line for this snippet: <|code_start|>
class ProjectTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
name = tables.TemplateColumn('<a href="/app/project/{{ record.pk }}"> {{ record.name }}</a>')
class Meta:
model = Project
template_name = "django_tables2/bootstrap-responsive.html"
sequence = ('selection', 'name', 'added')
fields = ('name', 'added')
class FlagTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
title = tables.TemplateColumn('<a href="/app/flag/{{ record.pk }}"> {{ record.title }}</a>')
done = tables.BooleanColumn(yesno='done,')
project = tables.TemplateColumn('<a href="/app/project/{{ record.assessment.project.pk}}">{{ record.assessment.project }}</a>')
assessment = tables.TemplateColumn('<a href="/app/assessment/{{ record.assessment.pk}}"> '
'{{ record.assessment }}</a>')
class Meta:
<|code_end|>
with the help of current file imports:
import django_tables2 as tables
from .models import Project, Flag, Sh0t, Assessment, Project
and context from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
, which may contain function names, class names, or code. Output only the next line. | model = Flag |
Given snippet: <|code_start|> class Meta:
model = Flag
template_name = "django_tables2/bootstrap-responsive.html"
sequence = ('selection', 'id', 'title', 'done', 'assessment', 'added')
fields = ('id', 'title', 'added', 'done', 'assessment')
empty_text = "No Flags yet"
class OpenFlagTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
name = tables.TemplateColumn('<a href="/app/flag/{{ record.pk }}"> {{ record.title }}</a>')
project = tables.TemplateColumn('<a href="/app/project/{{ record.assessment.project.pk}}">{{ record.assessment.project }}</a>')
assessment = tables.TemplateColumn('<a href="/app/assessment/{{ record.assessment.pk}}"> '
'{{ record.assessment }}</a>')
class Meta:
model = Flag
template_name = "django_tables2/bootstrap-responsive.html"
sequence = ('selection', 'id', 'name', 'project', 'assessment', 'added')
fields = ('id', 'name', 'added', 'project', 'assessment')
class Sh0tTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
severity = tables.TemplateColumn('<span class="bc-badge bc-badge--p{{ record.severity }}">P{{ record.severity }}</span>')
title = tables.TemplateColumn('<a href="/app/sh0t/{{ record.pk }}">{{ record.title }}</a>')
project = tables.TemplateColumn('<a href="/app/project/{{ record.assessment.project.pk}}">{{ record.assessment.project }}</a>')
assessment = tables.TemplateColumn('<a href="/app/assessment/{{ record.assessment.pk}}">{{ record.assessment }}</a>')
class Meta:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import django_tables2 as tables
from .models import Project, Flag, Sh0t, Assessment, Project
and context:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
which might include code, classes, or functions. Output only the next line. | model = Sh0t |
Continue the code snippet: <|code_start|> '{{ record.assessment }}</a>')
class Meta:
model = Flag
template_name = "django_tables2/bootstrap-responsive.html"
sequence = ('selection', 'id', 'name', 'project', 'assessment', 'added')
fields = ('id', 'name', 'added', 'project', 'assessment')
class Sh0tTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
severity = tables.TemplateColumn('<span class="bc-badge bc-badge--p{{ record.severity }}">P{{ record.severity }}</span>')
title = tables.TemplateColumn('<a href="/app/sh0t/{{ record.pk }}">{{ record.title }}</a>')
project = tables.TemplateColumn('<a href="/app/project/{{ record.assessment.project.pk}}">{{ record.assessment.project }}</a>')
assessment = tables.TemplateColumn('<a href="/app/assessment/{{ record.assessment.pk}}">{{ record.assessment }}</a>')
class Meta:
model = Sh0t
template_name = "django_tables2/bootstrap-responsive.html"
sequence = ('selection','title', 'severity', 'assessment', 'project', 'added')
fields = ('title', 'severity', 'assessment', 'project', 'added')
class AssessmentTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk', attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False)
name = tables.TemplateColumn('<a href="/app/assessment/{{ record.pk }}"> {{ record.name }}</a>')
project = tables.TemplateColumn('<a href="/app/project/{{ record.project.pk}}"> '
'{{ record.project }}</a>')
class Meta:
<|code_end|>
. Use current file imports:
import django_tables2 as tables
from .models import Project, Flag, Sh0t, Assessment, Project
and context (classes, functions, or code) from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | model = Assessment |
Next line prediction: <|code_start|>
class ModelTests(TestCase):
new_project_name = "Project created by automated testing"
new_flag_name = "Flag created by automated testing"
new_sh0t_name = "Sh0t created by automated testing"
new_assessment_name = "Assessment created by automated testing"
new_template_name = "Template created by automated testing"
new_template_body = ""
def __create_a_project(self):
<|code_end|>
. Use current file imports:
(from django.test import TestCase
from .models import Project, Assessment, Sh0t, Flag, Template)
and context including class names, function names, or small code snippets from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | new_project = Project.objects.create(name=self.new_project_name) |
Given the code snippet: <|code_start|>
class ModelTests(TestCase):
new_project_name = "Project created by automated testing"
new_flag_name = "Flag created by automated testing"
new_sh0t_name = "Sh0t created by automated testing"
new_assessment_name = "Assessment created by automated testing"
new_template_name = "Template created by automated testing"
new_template_body = ""
def __create_a_project(self):
new_project = Project.objects.create(name=self.new_project_name)
return new_project
def __create_an_assessment(self):
new_project = self.__create_a_project()
<|code_end|>
, generate the next line using the imports in this file:
from django.test import TestCase
from .models import Project, Assessment, Sh0t, Flag, Template
and context (functions, classes, or occasionally code) from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | new_assessment = Assessment.objects.create(name=self.new_assessment_name, project=new_project) |
Given snippet: <|code_start|>
class ModelTests(TestCase):
new_project_name = "Project created by automated testing"
new_flag_name = "Flag created by automated testing"
new_sh0t_name = "Sh0t created by automated testing"
new_assessment_name = "Assessment created by automated testing"
new_template_name = "Template created by automated testing"
new_template_body = ""
def __create_a_project(self):
new_project = Project.objects.create(name=self.new_project_name)
return new_project
def __create_an_assessment(self):
new_project = self.__create_a_project()
new_assessment = Assessment.objects.create(name=self.new_assessment_name, project=new_project)
new_assessment.save()
return new_assessment
def __create_a_flag(self):
new_assessment = self.__create_an_assessment()
new_flag = Flag.objects.create(title=self.new_flag_name, assessment=new_assessment)
return new_flag
def __create_a_sh0t(self):
new_assessment = self.__create_an_assessment()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from .models import Project, Assessment, Sh0t, Flag, Template
and context:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
which might include code, classes, or functions. Output only the next line. | new_sh0t = Sh0t.objects.create(title=self.new_sh0t_name, assessment=new_assessment) |
Given snippet: <|code_start|>
class ModelTests(TestCase):
new_project_name = "Project created by automated testing"
new_flag_name = "Flag created by automated testing"
new_sh0t_name = "Sh0t created by automated testing"
new_assessment_name = "Assessment created by automated testing"
new_template_name = "Template created by automated testing"
new_template_body = ""
def __create_a_project(self):
new_project = Project.objects.create(name=self.new_project_name)
return new_project
def __create_an_assessment(self):
new_project = self.__create_a_project()
new_assessment = Assessment.objects.create(name=self.new_assessment_name, project=new_project)
new_assessment.save()
return new_assessment
def __create_a_flag(self):
new_assessment = self.__create_an_assessment()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from .models import Project, Assessment, Sh0t, Flag, Template
and context:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
which might include code, classes, or functions. Output only the next line. | new_flag = Flag.objects.create(title=self.new_flag_name, assessment=new_assessment) |
Given snippet: <|code_start|>
class ModelTests(TestCase):
new_project_name = "Project created by automated testing"
new_flag_name = "Flag created by automated testing"
new_sh0t_name = "Sh0t created by automated testing"
new_assessment_name = "Assessment created by automated testing"
new_template_name = "Template created by automated testing"
new_template_body = ""
def __create_a_project(self):
new_project = Project.objects.create(name=self.new_project_name)
return new_project
def __create_an_assessment(self):
new_project = self.__create_a_project()
new_assessment = Assessment.objects.create(name=self.new_assessment_name, project=new_project)
new_assessment.save()
return new_assessment
def __create_a_flag(self):
new_assessment = self.__create_an_assessment()
new_flag = Flag.objects.create(title=self.new_flag_name, assessment=new_assessment)
return new_flag
def __create_a_sh0t(self):
new_assessment = self.__create_an_assessment()
new_sh0t = Sh0t.objects.create(title=self.new_sh0t_name, assessment=new_assessment)
return new_sh0t
def __create_a_template(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from .models import Project, Assessment, Sh0t, Flag, Template
and context:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
which might include code, classes, or functions. Output only the next line. | new_template = Template.objects.create(name=self.new_template_name, body=self.new_template_body) |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
class MethodologyMasterAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'order']
list_display = ['name', 'description', 'order', 'created', 'updated']
search_fields = ['name', 'description']
ordering = ['order', 'name']
class ModuleMasterAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'methodology', 'order']
list_display = ['name', 'description', 'methodology', 'order', 'created', 'updated']
search_fields = ['name', 'description']
ordering = ['order', 'name']
class CaseMasterAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'module', 'order']
list_display = ['name', 'description', 'module', 'methodology', 'order', 'created', 'updated']
search_fields = ['name', 'description']
ordering = ['order', 'name']
@staticmethod
def methodology(case):
return case.module.methodology
admin.site.register(MethodologyMaster, MethodologyMasterAdmin)
admin.site.register(ModuleMaster, ModuleMasterAdmin)
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from .models import CaseMaster, ModuleMaster, MethodologyMaster
and context including class names, function names, and sometimes code from other files:
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | admin.site.register(CaseMaster, CaseMasterAdmin) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class MethodologyMasterAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'order']
list_display = ['name', 'description', 'order', 'created', 'updated']
search_fields = ['name', 'description']
ordering = ['order', 'name']
class ModuleMasterAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'methodology', 'order']
list_display = ['name', 'description', 'methodology', 'order', 'created', 'updated']
search_fields = ['name', 'description']
ordering = ['order', 'name']
class CaseMasterAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'module', 'order']
list_display = ['name', 'description', 'module', 'methodology', 'order', 'created', 'updated']
search_fields = ['name', 'description']
ordering = ['order', 'name']
@staticmethod
def methodology(case):
return case.module.methodology
admin.site.register(MethodologyMaster, MethodologyMasterAdmin)
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from .models import CaseMaster, ModuleMaster, MethodologyMaster
and context from other files:
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
, which may include functions, classes, or code. Output only the next line. | admin.site.register(ModuleMaster, ModuleMasterAdmin) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class MethodologyMasterAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'order']
list_display = ['name', 'description', 'order', 'created', 'updated']
search_fields = ['name', 'description']
ordering = ['order', 'name']
class ModuleMasterAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'methodology', 'order']
list_display = ['name', 'description', 'methodology', 'order', 'created', 'updated']
search_fields = ['name', 'description']
ordering = ['order', 'name']
class CaseMasterAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'module', 'order']
list_display = ['name', 'description', 'module', 'methodology', 'order', 'created', 'updated']
search_fields = ['name', 'description']
ordering = ['order', 'name']
@staticmethod
def methodology(case):
return case.module.methodology
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from .models import CaseMaster, ModuleMaster, MethodologyMaster
and context from other files:
# Path: configuration/models.py
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
, which may contain function names, class names, or code. Output only the next line. | admin.site.register(MethodologyMaster, MethodologyMasterAdmin) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ModelTests(TestCase):
new_methodology_name = "Methodology created by automated testing"
new_module_name = "Module created by automated testing"
new_case_name = "Case created by automated testing"
def __create_a_methodology(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from .models import MethodologyMaster, ModuleMaster, CaseMaster
and context:
# Path: configuration/models.py
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
which might include code, classes, or functions. Output only the next line. | new_methodology = MethodologyMaster.objects.create(name=self.new_methodology_name) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ModelTests(TestCase):
new_methodology_name = "Methodology created by automated testing"
new_module_name = "Module created by automated testing"
new_case_name = "Case created by automated testing"
def __create_a_methodology(self):
new_methodology = MethodologyMaster.objects.create(name=self.new_methodology_name)
return new_methodology
def __create_a_module(self):
new_methodology = self.__create_a_methodology()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase
from .models import MethodologyMaster, ModuleMaster, CaseMaster
and context (classes, functions, sometimes code) from other files:
# Path: configuration/models.py
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | new_module = ModuleMaster.objects.create(name=self.new_module_name, methodology=new_methodology) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ModelTests(TestCase):
new_methodology_name = "Methodology created by automated testing"
new_module_name = "Module created by automated testing"
new_case_name = "Case created by automated testing"
def __create_a_methodology(self):
new_methodology = MethodologyMaster.objects.create(name=self.new_methodology_name)
return new_methodology
def __create_a_module(self):
new_methodology = self.__create_a_methodology()
new_module = ModuleMaster.objects.create(name=self.new_module_name, methodology=new_methodology)
new_module.save()
return new_module
def __create_a_case(self):
new_module = self.__create_a_module()
<|code_end|>
with the help of current file imports:
from django.test import TestCase
from .models import MethodologyMaster, ModuleMaster, CaseMaster
and context from other files:
# Path: configuration/models.py
# class MethodologyMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="methodology_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="methodology_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(MethodologyMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class ModuleMaster(models.Model):
# name = models.CharField(max_length=100)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# methodology = models.ForeignKey(MethodologyMaster, on_delete=models.CASCADE, null=True, default=None)
# created_by = models.ForeignKey(User, related_name="module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(ModuleMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
#
# class CaseMaster(models.Model):
# name = models.CharField(max_length=100)
# module = models.ForeignKey(ModuleMaster, on_delete=models.CASCADE)
# description = models.TextField(default="")
# order = models.IntegerField(default=0)
# created_by = models.ForeignKey(User, related_name="case_module_created_by", null=True, on_delete=models.CASCADE)
# created = models.DateTimeField(default=datetime.now)
# updated_by = models.ForeignKey(User, related_name="case_module_updated_by", null=True, on_delete=models.CASCADE)
# updated = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# def save(self, *args, **kwargs):
# if not self.id:
# self.created = timezone.now()
# self.updated = timezone.now()
# return super(CaseMaster, self).save(*args, **kwargs)
#
# class Meta:
# ordering = ('name',)
, which may contain function names, class names, or code. Output only the next line. | new_case = CaseMaster.objects.create(name=self.new_case_name, module=new_module) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class FlagAdmin(admin.ModelAdmin):
list_display = ('title', 'assessment', 'added', 'order')
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from .models import Project, Assessment, Sh0t, Flag, Template
and context from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
, which may include functions, classes, or code. Output only the next line. | admin.site.register(Project) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class FlagAdmin(admin.ModelAdmin):
list_display = ('title', 'assessment', 'added', 'order')
admin.site.register(Project)
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from .models import Project, Assessment, Sh0t, Flag, Template
and context (functions, classes, or occasionally code) from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | admin.site.register(Assessment) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class FlagAdmin(admin.ModelAdmin):
list_display = ('title', 'assessment', 'added', 'order')
admin.site.register(Project)
admin.site.register(Assessment)
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from .models import Project, Assessment, Sh0t, Flag, Template
and context (class names, function names, or code) available:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | admin.site.register(Sh0t) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class FlagAdmin(admin.ModelAdmin):
list_display = ('title', 'assessment', 'added', 'order')
admin.site.register(Project)
admin.site.register(Assessment)
admin.site.register(Sh0t)
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from .models import Project, Assessment, Sh0t, Flag, Template
and context (class names, function names, or code) available:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | admin.site.register(Flag, FlagAdmin) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class FlagAdmin(admin.ModelAdmin):
list_display = ('title', 'assessment', 'added', 'order')
admin.site.register(Project)
admin.site.register(Assessment)
admin.site.register(Sh0t)
admin.site.register(Flag, FlagAdmin)
<|code_end|>
. Use current file imports:
(from django.contrib import admin
from .models import Project, Assessment, Sh0t, Flag, Template)
and context including class names, function names, or small code snippets from other files:
# Path: app/models.py
# class Project(models.Model):
# name = models.CharField(max_length=100)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Assessment(models.Model):
# name = models.CharField(max_length=100)
# project = models.ForeignKey(Project, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
#
# class Sh0t(models.Model):
# title = models.CharField(max_length=200)
# body = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# added = models.DateTimeField(default=datetime.now)
# severity = models.IntegerField(default=5, validators=[MinValueValidator(0), MaxValueValidator(5)])
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('severity','title',)
#
# class Flag(models.Model):
# title = models.CharField(max_length=100)
# note = models.TextField(default="")
# assessment = models.ForeignKey(Assessment, null=True, on_delete=models.CASCADE)
# done = models.BooleanField(default=False)
# added = models.DateTimeField(default=datetime.now)
# order = models.IntegerField(default=1)
#
# def __str__(self): # __unicode__ on Python 2
# return self.title
#
# class Meta:
# ordering = ('title',)
#
# class Template(models.Model):
# name = models.CharField(max_length=100)
# body = models.TextField(default="")
# added = models.DateTimeField(default=datetime.now)
#
# def __str__(self): # __unicode__ on Python 2
# return self.name
#
# class Meta:
# ordering = ('name',)
. Output only the next line. | admin.site.register(Template) |
Predict the next line for this snippet: <|code_start|>def create_sparse_from_host(values, row_idx, col_idx, nrows, ncols, storage = STORAGE.CSR):
"""
Create a sparse matrix from it's constituent parts.
Parameters
----------
values : Any datatype that can be converted to array.
- Contains the non zero elements of the sparse array.
row_idx : Any datatype that can be converted to array.
- Contains row indices of the sparse array.
col_idx : Any datatype that can be converted to array.
- Contains column indices of the sparse array.
nrows : int.
- specifies the number of rows in sparse matrix.
ncols : int.
- specifies the number of columns in sparse matrix.
storage : optional: arrayfire.STORAGE. default: arrayfire.STORAGE.CSR.
- Can be one of arrayfire.STORAGE.CSR, arrayfire.STORAGE.COO.
Returns
-------
A sparse matrix.
"""
<|code_end|>
with the help of current file imports:
from .library import *
from .array import *
from .interop import to_array
import numbers
and context from other files:
# Path: arrayfire/interop.py
# def to_array(in_array, copy = True):
# """
# Helper function to convert input from a different module to af.Array
#
# Parameters
# -------------
#
# in_array : array like object
# Can be one of the following:
# - numpy.ndarray
# - pycuda.GPUArray
# - pyopencl.Array
# - numba.cuda.cudadrv.devicearray.DeviceNDArray
# - array.array
# - list
# copy : Bool specifying if array is to be copied.
# Default is true.
# Can only be False if array is fortran contiguous.
#
# Returns
# --------------
# af.Array of same dimensions as input after copying the data from the input
#
# """
# if AF_NUMPY_FOUND and isinstance(in_array, NumpyArray):
# return np_to_af_array(in_array, copy)
# if AF_PYCUDA_FOUND and isinstance(in_array, CudaArray):
# return pycuda_to_af_array(in_array, copy)
# if AF_PYOPENCL_FOUND and isinstance(in_array, OpenclArray):
# return pyopencl_to_af_array(in_array, copy)
# if AF_NUMBA_FOUND and isinstance(in_array, NumbaCudaArray):
# return numba_to_af_array(in_array, copy)
# return Array(src=in_array)
, which may contain function names, class names, or code. Output only the next line. | return create_sparse(to_array(values), |
Given the following code snippet before the placeholder: <|code_start|>#######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
########################################################
"""
Functions specific to OpenCL backend.
This module provides interoperability with other OpenCL libraries.
"""
class DEVICE_TYPE(_Enum):
"""
ArrayFire wrapper for CL_DEVICE_TYPE
"""
<|code_end|>
, predict the next line using imports from the current file:
from .util import *
from .library import (_Enum, _Enum_Type)
from .util import safe_call as safe_call
from .library import backend
from .util import safe_call as safe_call
from .library import backend
from .util import safe_call as safe_call
from .library import backend
from .util import safe_call as safe_call
from .library import backend
from .util import safe_call as safe_call
from .library import backend
from .util import safe_call as safe_call
from .library import backend
from .util import safe_call as safe_call
from .library import backend
from .util import safe_call as safe_call
from .library import backend
from .util import safe_call as safe_call
from .library import backend
import ctypes as ct
import ctypes as ct
import ctypes as ct
import ctypes as ct
import ctypes as ct
import ctypes as ct
import ctypes as ct
import ctypes as ct
import ctypes as ct
and context including class names, function names, and sometimes code from other files:
# Path: arrayfire/library.py
# class _Enum(object):
# __metaclass__ = _MetaEnum
#
# class _Enum_Type(object):
# def __init__(self, v):
# self.value = v
. Output only the next line. | CPU = _Enum_Type(1<<1) |
Predict the next line after this snippet: <|code_start|>def _get_indices(key):
inds = _Index4()
if isinstance(key, tuple):
n_idx = len(key)
for n in range(n_idx):
inds[n] = Index(key[n])
else:
inds[0] = Index(key)
return inds
def _get_assign_dims(key, idims):
dims = [1]*4
for n in range(len(idims)):
dims[n] = idims[n]
if _is_number(key):
dims[0] = 1
return dims
elif isinstance(key, slice):
dims[0] = _slice_to_length(key, idims[0])
return dims
elif isinstance(key, ParallelRange):
dims[0] = _slice_to_length(key.S, idims[0])
return dims
elif isinstance(key, BaseArray):
# If the array is boolean take only the number of nonzeros
if(key.dtype() is Dtype.b8):
<|code_end|>
using the current file's imports:
import inspect
import os
import numpy as np
from .library import *
from .util import *
from .util import _is_number
from .bcast import _bcast_var
from .base import *
from .index import *
from .index import _Index4
from .algorithm import (sum, count)
from .arith import cast
and any relevant context from other files:
# Path: arrayfire/algorithm.py
# def sum(a, dim=None, nan_val=None):
# """
# Calculate the sum of all the elements along a specified dimension.
#
# Parameters
# ----------
# a : af.Array
# Multi dimensional arrayfire array.
# dim: optional: int. default: None
# Dimension along which the sum is required.
# nan_val: optional: scalar. default: None
# The value that replaces NaN in the array
#
# Returns
# -------
# out: af.Array or scalar number
# The sum of all elements in `a` along dimension `dim`.
# If `dim` is `None`, sum of the entire Array is returned.
# """
# if (nan_val is not None):
# if dim is not None:
# return _nan_parallel_dim(a, dim, backend.get().af_sum_nan, nan_val)
# else:
# return _nan_reduce_all(a, backend.get().af_sum_nan_all, nan_val)
# else:
# if dim is not None:
# return _parallel_dim(a, dim, backend.get().af_sum)
# else:
# return _reduce_all(a, backend.get().af_sum_all)
#
# def count(a, dim=None):
# """
# Count the number of non zero elements in an array along a specified dimension.
#
# Parameters
# ----------
# a : af.Array
# Multi dimensional arrayfire array.
# dim: optional: int. default: None
# Dimension along which the the non zero elements are to be counted.
#
# Returns
# -------
# out: af.Array or scalar number
# The count of non zero elements in `a` along `dim`.
# If `dim` is `None`, the total number of non zero elements in `a`.
# """
# if dim is not None:
# return _parallel_dim(a, dim, backend.get().af_count)
# else:
# return _reduce_all(a, backend.get().af_count_all)
#
# Path: arrayfire/arith.py
# def cast(a, dtype):
# """
# Cast an array to a specified type
#
# Parameters
# ----------
# a : af.Array
# Multi dimensional arrayfire array.
# dtype: af.Dtype
# Must be one of the following:
# - Dtype.f32 for float
# - Dtype.f64 for double
# - Dtype.b8 for bool
# - Dtype.u8 for unsigned char
# - Dtype.s32 for signed 32 bit integer
# - Dtype.u32 for unsigned 32 bit integer
# - Dtype.s64 for signed 64 bit integer
# - Dtype.u64 for unsigned 64 bit integer
# - Dtype.c32 for 32 bit complex number
# - Dtype.c64 for 64 bit complex number
# Returns
# --------
# out : af.Array
# array containing the values from `a` after converting to `dtype`.
# """
# out=Array()
# safe_call(backend.get().af_cast(c_pointer(out.arr), a.arr, dtype.value))
# return out
. Output only the next line. | dims[0] = int(sum(key)) |
Predict the next line after this snippet: <|code_start|>
def logical_or(self, other):
"""
Return self || other.
"""
out = Array()
safe_call(backend.get().af_or(c_pointer(out.arr), self.arr, other.arr)) #TODO: bcast var?
return out
def __nonzero__(self):
return self != 0
# TODO:
# def __abs__(self):
# return self
def __getitem__(self, key):
"""
Return self[key]
Note
----
Ellipsis not supported as key
"""
try:
out = Array()
n_dims = self.numdims()
if (isinstance(key, Array) and key.type() == Dtype.b8.value):
n_dims = 1
<|code_end|>
using the current file's imports:
import inspect
import os
import numpy as np
from .library import *
from .util import *
from .util import _is_number
from .bcast import _bcast_var
from .base import *
from .index import *
from .index import _Index4
from .algorithm import (sum, count)
from .arith import cast
and any relevant context from other files:
# Path: arrayfire/algorithm.py
# def sum(a, dim=None, nan_val=None):
# """
# Calculate the sum of all the elements along a specified dimension.
#
# Parameters
# ----------
# a : af.Array
# Multi dimensional arrayfire array.
# dim: optional: int. default: None
# Dimension along which the sum is required.
# nan_val: optional: scalar. default: None
# The value that replaces NaN in the array
#
# Returns
# -------
# out: af.Array or scalar number
# The sum of all elements in `a` along dimension `dim`.
# If `dim` is `None`, sum of the entire Array is returned.
# """
# if (nan_val is not None):
# if dim is not None:
# return _nan_parallel_dim(a, dim, backend.get().af_sum_nan, nan_val)
# else:
# return _nan_reduce_all(a, backend.get().af_sum_nan_all, nan_val)
# else:
# if dim is not None:
# return _parallel_dim(a, dim, backend.get().af_sum)
# else:
# return _reduce_all(a, backend.get().af_sum_all)
#
# def count(a, dim=None):
# """
# Count the number of non zero elements in an array along a specified dimension.
#
# Parameters
# ----------
# a : af.Array
# Multi dimensional arrayfire array.
# dim: optional: int. default: None
# Dimension along which the the non zero elements are to be counted.
#
# Returns
# -------
# out: af.Array or scalar number
# The count of non zero elements in `a` along `dim`.
# If `dim` is `None`, the total number of non zero elements in `a`.
# """
# if dim is not None:
# return _parallel_dim(a, dim, backend.get().af_count)
# else:
# return _reduce_all(a, backend.get().af_count_all)
#
# Path: arrayfire/arith.py
# def cast(a, dtype):
# """
# Cast an array to a specified type
#
# Parameters
# ----------
# a : af.Array
# Multi dimensional arrayfire array.
# dtype: af.Dtype
# Must be one of the following:
# - Dtype.f32 for float
# - Dtype.f64 for double
# - Dtype.b8 for bool
# - Dtype.u8 for unsigned char
# - Dtype.s32 for signed 32 bit integer
# - Dtype.u32 for unsigned 32 bit integer
# - Dtype.s64 for signed 64 bit integer
# - Dtype.u64 for unsigned 64 bit integer
# - Dtype.c32 for 32 bit complex number
# - Dtype.c64 for 64 bit complex number
# Returns
# --------
# out : af.Array
# array containing the values from `a` after converting to `dtype`.
# """
# out=Array()
# safe_call(backend.get().af_cast(c_pointer(out.arr), a.arr, dtype.value))
# return out
. Output only the next line. | if (count(key) == 0): |
Here is a snippet: <|code_start|> type_char != _type_char):
raise TypeError("Can not create array of requested type from input data type")
if(offset is None and strides is None):
self.arr = _create_array(buf, numdims, idims, to_dtype[_type_char], is_device)
else:
self.arr = _create_strided_array(buf, numdims, idims,
to_dtype[_type_char],
is_device, offset, strides)
else:
if type_char is None:
type_char = 'f'
numdims = len(dims) if dims else 0
idims = [1] * 4
for n in range(numdims):
idims[n] = dims[n]
self.arr = _create_empty_array(numdims, idims, to_dtype[type_char])
def as_type(self, ty):
"""
Cast current array to a specified data type
Parameters
----------
ty : Return data type
"""
<|code_end|>
. Write the next line using the current file imports:
import inspect
import os
import numpy as np
from .library import *
from .util import *
from .util import _is_number
from .bcast import _bcast_var
from .base import *
from .index import *
from .index import _Index4
from .algorithm import (sum, count)
from .arith import cast
and context from other files:
# Path: arrayfire/algorithm.py
# def sum(a, dim=None, nan_val=None):
# """
# Calculate the sum of all the elements along a specified dimension.
#
# Parameters
# ----------
# a : af.Array
# Multi dimensional arrayfire array.
# dim: optional: int. default: None
# Dimension along which the sum is required.
# nan_val: optional: scalar. default: None
# The value that replaces NaN in the array
#
# Returns
# -------
# out: af.Array or scalar number
# The sum of all elements in `a` along dimension `dim`.
# If `dim` is `None`, sum of the entire Array is returned.
# """
# if (nan_val is not None):
# if dim is not None:
# return _nan_parallel_dim(a, dim, backend.get().af_sum_nan, nan_val)
# else:
# return _nan_reduce_all(a, backend.get().af_sum_nan_all, nan_val)
# else:
# if dim is not None:
# return _parallel_dim(a, dim, backend.get().af_sum)
# else:
# return _reduce_all(a, backend.get().af_sum_all)
#
# def count(a, dim=None):
# """
# Count the number of non zero elements in an array along a specified dimension.
#
# Parameters
# ----------
# a : af.Array
# Multi dimensional arrayfire array.
# dim: optional: int. default: None
# Dimension along which the the non zero elements are to be counted.
#
# Returns
# -------
# out: af.Array or scalar number
# The count of non zero elements in `a` along `dim`.
# If `dim` is `None`, the total number of non zero elements in `a`.
# """
# if dim is not None:
# return _parallel_dim(a, dim, backend.get().af_count)
# else:
# return _reduce_all(a, backend.get().af_count_all)
#
# Path: arrayfire/arith.py
# def cast(a, dtype):
# """
# Cast an array to a specified type
#
# Parameters
# ----------
# a : af.Array
# Multi dimensional arrayfire array.
# dtype: af.Dtype
# Must be one of the following:
# - Dtype.f32 for float
# - Dtype.f64 for double
# - Dtype.b8 for bool
# - Dtype.u8 for unsigned char
# - Dtype.s32 for signed 32 bit integer
# - Dtype.u32 for unsigned 32 bit integer
# - Dtype.s64 for signed 64 bit integer
# - Dtype.u64 for unsigned 64 bit integer
# - Dtype.c32 for 32 bit complex number
# - Dtype.c64 for 64 bit complex number
# Returns
# --------
# out : af.Array
# array containing the values from `a` after converting to `dtype`.
# """
# out=Array()
# safe_call(backend.get().af_cast(c_pointer(out.arr), a.arr, dtype.value))
# return out
, which may include functions, classes, or code. Output only the next line. | return cast(self, ty) |
Given snippet: <|code_start|> 'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.inheritance_diagram']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'ArrayFire'
copyright = '2020, ArrayFire'
author = 'Stefan Yurkevitch, Pradeep Garigipati, Umar Arshad'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
from __af_version__ import full_version
and context:
# Path: __af_version__.py
which might include code, classes, or functions. Output only the next line. | version = full_version |
Based on the snippet: <|code_start|># Copyright 2015 Internap.
#
# 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 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 specific language governing permissions and
# limitations under the License.
def not_implemented(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
raise NotImplementedError("'{}' is not implemented".format(func.func_name))
return func_wrapper
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from contextlib import contextmanager
from functools import wraps
from netman.core.objects.backward_compatible_switch_operations import BackwardCompatibleSwitchOperations
and context (classes, functions, sometimes code) from other files:
# Path: netman/core/objects/backward_compatible_switch_operations.py
# class BackwardCompatibleSwitchOperations(object):
# """
# Depecrated methods
# """
# def remove_access_vlan(self, interface_id):
# warnings.warn("Deprecated, use unset_interface_access_vlan(interface_id) instead", DeprecationWarning)
# return self.unset_interface_access_vlan(interface_id)
#
# def configure_native_vlan(self, interface_id, vlan):
# warnings.warn("Deprecated, use set_interface_native_vlan(interface_id, vlan) instead", DeprecationWarning)
# return self.set_interface_native_vlan(interface_id, vlan)
#
# def remove_native_vlan(self, interface_id):
# warnings.warn("Deprecated, use unset_interface_native_vlan(interface_id) instead", DeprecationWarning)
# return self.unset_interface_native_vlan(interface_id)
#
# def remove_vlan_access_group(self, vlan_number, direction):
# warnings.warn("Deprecated, use unset_vlan_access_group(vlan_number, direction) instead", DeprecationWarning)
# return self.unset_vlan_access_group(vlan_number, direction)
#
# def remove_vlan_vrf(self, vlan_number):
# warnings.warn("Deprecated, use unset_vlan_vrf(vlan_number) instead", DeprecationWarning)
# return self.unset_vlan_vrf(vlan_number)
#
# def remove_interface_description(self, interface_id):
# warnings.warn("Deprecated, use unset_interface_description(interface_id) instead", DeprecationWarning)
# return self.unset_interface_description(interface_id)
#
# def remove_bond_description(self, number):
# warnings.warn("Deprecated, use unset_bond_description(number) instead", DeprecationWarning)
# return self.unset_bond_description(number)
#
# def configure_bond_native_vlan(self, number, vlan):
# warnings.warn("Deprecated, use set_bond_native_vlan(number, vlan) instead", DeprecationWarning)
# return self.set_bond_native_vlan(number, vlan)
#
# def remove_bond_native_vlan(self, number):
# warnings.warn("Deprecated, use unset_bond_native_vlan(number) instead", DeprecationWarning)
# return self.unset_bond_native_vlan(number)
#
# def enable_lldp(self, interface_id, enabled):
# warnings.warn("Deprecated, use set_interface_lldp_state(interface_id, enabled) instead", DeprecationWarning)
# return self.set_interface_lldp_state(interface_id, enabled)
#
# def shutdown_interface(self, interface_id):
# warnings.warn("Deprecated, use set_interface_state(interface_id, state) instead", DeprecationWarning)
# return self.set_interface_state(interface_id, OFF)
#
# def openup_interface(self, interface_id):
# warnings.warn("Deprecated, use set_interface_state(interface_id, state) instead", DeprecationWarning)
# return self.set_interface_state(interface_id, ON)
. Output only the next line. | class SwitchOperations(BackwardCompatibleSwitchOperations): |
Continue the code 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 "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.
__all__ = ['to_api', 'to_core']
class V2(Serializer):
since_version = 2
def to_api(self, bond):
return dict(
number=bond.number,
link_speed=bond.link_speed,
members=bond.members,
**base_interface.to_api(bond)
)
def to_core(self, api_bond):
params = dict(vars(base_interface.to_core(api_bond)))
params.update(sub_dict(api_bond, 'number', 'link_speed', 'members'))
<|code_end|>
. Use current file imports:
from netman.api.objects import base_interface, interface, Serializer, \
Serializers
from netman.api.objects import sub_dict
from netman.core.objects.bond import Bond
from netman.core.objects.interface import Interface
and context (classes, functions, or code) from other files:
# Path: netman/core/objects/bond.py
# class Bond(BaseInterface):
# def __init__(self, number=None, link_speed=None, members=None, **interface):
# super(Bond, self).__init__(**interface)
# self.number = number
# self.link_speed = link_speed
# self.members = members or []
#
# @property
# def interface(self):
# warnings.warn('Deprecated: Use directly the members of Bond instead.', DeprecationWarning)
# return Interface(
# shutdown=self.shutdown,
# port_mode=self.port_mode,
# access_vlan=self.access_vlan,
# trunk_native_vlan=self.trunk_native_vlan,
# trunk_vlans=self.trunk_vlans,
# )
. Output only the next line. | return Bond(**params) |
Predict the next line after this snippet: <|code_start|> def __len__(self):
return len(self.dict)
def __delitem__(self, key):
try:
del self.dict[key]
self.refresh_items.remove(key)
except KeyError:
pass
def values(self):
return self.dict.values()
class VlanCache(Cache):
object_type = Vlan
object_key = 'number'
class InterfaceCache(Cache):
object_type = Interface
object_key = 'name'
class VlanInterfaceCache(Cache):
object_type = str
object_key = 'number'
class BondCache(Cache):
<|code_end|>
using the current file's imports:
import copy
from collections import OrderedDict
from netman.core.objects.bond import Bond
from netman.core.objects.interface import Interface
from netman.core.objects.interface_states import OFF, ON
from netman.core.objects.port_modes import ACCESS, TRUNK
from netman.core.objects.switch_base import SwitchBase
from netman.core.objects.vlan import Vlan
from netman.core.objects.vrrp_group import VrrpGroup
and any relevant context from other files:
# Path: netman/core/objects/bond.py
# class Bond(BaseInterface):
# def __init__(self, number=None, link_speed=None, members=None, **interface):
# super(Bond, self).__init__(**interface)
# self.number = number
# self.link_speed = link_speed
# self.members = members or []
#
# @property
# def interface(self):
# warnings.warn('Deprecated: Use directly the members of Bond instead.', DeprecationWarning)
# return Interface(
# shutdown=self.shutdown,
# port_mode=self.port_mode,
# access_vlan=self.access_vlan,
# trunk_native_vlan=self.trunk_native_vlan,
# trunk_vlans=self.trunk_vlans,
# )
#
# Path: netman/core/objects/port_modes.py
# ACCESS = "ACCESS"
#
# TRUNK = "TRUNK"
#
# Path: netman/core/objects/switch_base.py
# class SwitchBase(SwitchOperations):
# def __init__(self, switch_descriptor):
# self.switch_descriptor = switch_descriptor
# self.logger = logging.getLogger("{module}.{hostname}".format(module=self.__module__, hostname=self.switch_descriptor.hostname))
# self.connected = False
# self.in_transaction = False
#
# def connect(self):
# self._connect()
# self.connected = True
#
# def disconnect(self):
# self._disconnect()
# self.connected = False
#
# def start_transaction(self):
# self._start_transaction()
# self.in_transaction = True
#
# def end_transaction(self):
# self._end_transaction()
# self.in_transaction = False
#
# def _connect(self):
# """
# Adpapters should implement this rather than connect
# """
# raise NotImplementedError()
#
# def _disconnect(self):
# """
# Adpapters should implement this rather than disconnect
# """
# raise NotImplementedError()
#
# def _start_transaction(self):
# """
# Adpapters should implement this rather than connect
# """
# raise NotImplementedError()
#
# def _end_transaction(self):
# """
# Adpapters should implement this rather than disconnect
# """
# raise NotImplementedError()
#
# @contextmanager
# def transaction(self):
# self.start_transaction()
# try:
# yield self
# self.commit_transaction()
# except Exception as e:
# if self.logger:
# self.logger.exception(e)
# self.rollback_transaction()
# raise
# finally:
# self.end_transaction()
. Output only the next line. | object_type = Bond |
Given snippet: <|code_start|> del self.vlans_cache[number]
def set_vlan_access_group(self, vlan_number, direction, name):
self.real_switch.set_vlan_access_group(vlan_number, direction, name)
self.vlans_cache[vlan_number].access_groups[direction] = name
def unset_vlan_access_group(self, vlan_number, direction):
self.real_switch.unset_vlan_access_group(vlan_number, direction)
self.vlans_cache[vlan_number].access_groups[direction] = None
def add_ip_to_vlan(self, vlan_number, ip_network):
self.real_switch.add_ip_to_vlan(vlan_number, ip_network)
self.vlans_cache[vlan_number].ips.append(ip_network)
def remove_ip_from_vlan(self, vlan_number, ip_network):
self.real_switch.remove_ip_from_vlan(vlan_number, ip_network)
self.vlans_cache[vlan_number].ips = [
net for net in self.vlans_cache[vlan_number].ips
if str(net) != str(ip_network)]
def set_vlan_vrf(self, vlan_number, vrf_name):
self.real_switch.set_vlan_vrf(vlan_number, vrf_name)
self.vlans_cache[vlan_number].vrf_forwarding = vrf_name
def unset_vlan_vrf(self, vlan_number):
self.real_switch.unset_vlan_vrf(vlan_number)
self.vlans_cache[vlan_number].vrf_forwarding = None
def set_access_mode(self, interface_id):
self.real_switch.set_access_mode(interface_id)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
from collections import OrderedDict
from netman.core.objects.bond import Bond
from netman.core.objects.interface import Interface
from netman.core.objects.interface_states import OFF, ON
from netman.core.objects.port_modes import ACCESS, TRUNK
from netman.core.objects.switch_base import SwitchBase
from netman.core.objects.vlan import Vlan
from netman.core.objects.vrrp_group import VrrpGroup
and context:
# Path: netman/core/objects/bond.py
# class Bond(BaseInterface):
# def __init__(self, number=None, link_speed=None, members=None, **interface):
# super(Bond, self).__init__(**interface)
# self.number = number
# self.link_speed = link_speed
# self.members = members or []
#
# @property
# def interface(self):
# warnings.warn('Deprecated: Use directly the members of Bond instead.', DeprecationWarning)
# return Interface(
# shutdown=self.shutdown,
# port_mode=self.port_mode,
# access_vlan=self.access_vlan,
# trunk_native_vlan=self.trunk_native_vlan,
# trunk_vlans=self.trunk_vlans,
# )
#
# Path: netman/core/objects/port_modes.py
# ACCESS = "ACCESS"
#
# TRUNK = "TRUNK"
#
# Path: netman/core/objects/switch_base.py
# class SwitchBase(SwitchOperations):
# def __init__(self, switch_descriptor):
# self.switch_descriptor = switch_descriptor
# self.logger = logging.getLogger("{module}.{hostname}".format(module=self.__module__, hostname=self.switch_descriptor.hostname))
# self.connected = False
# self.in_transaction = False
#
# def connect(self):
# self._connect()
# self.connected = True
#
# def disconnect(self):
# self._disconnect()
# self.connected = False
#
# def start_transaction(self):
# self._start_transaction()
# self.in_transaction = True
#
# def end_transaction(self):
# self._end_transaction()
# self.in_transaction = False
#
# def _connect(self):
# """
# Adpapters should implement this rather than connect
# """
# raise NotImplementedError()
#
# def _disconnect(self):
# """
# Adpapters should implement this rather than disconnect
# """
# raise NotImplementedError()
#
# def _start_transaction(self):
# """
# Adpapters should implement this rather than connect
# """
# raise NotImplementedError()
#
# def _end_transaction(self):
# """
# Adpapters should implement this rather than disconnect
# """
# raise NotImplementedError()
#
# @contextmanager
# def transaction(self):
# self.start_transaction()
# try:
# yield self
# self.commit_transaction()
# except Exception as e:
# if self.logger:
# self.logger.exception(e)
# self.rollback_transaction()
# raise
# finally:
# self.end_transaction()
which might include code, classes, or functions. Output only the next line. | self.interfaces_cache[interface_id].port_mode = ACCESS |
Given the code snippet: <|code_start|> def unset_vlan_access_group(self, vlan_number, direction):
self.real_switch.unset_vlan_access_group(vlan_number, direction)
self.vlans_cache[vlan_number].access_groups[direction] = None
def add_ip_to_vlan(self, vlan_number, ip_network):
self.real_switch.add_ip_to_vlan(vlan_number, ip_network)
self.vlans_cache[vlan_number].ips.append(ip_network)
def remove_ip_from_vlan(self, vlan_number, ip_network):
self.real_switch.remove_ip_from_vlan(vlan_number, ip_network)
self.vlans_cache[vlan_number].ips = [
net for net in self.vlans_cache[vlan_number].ips
if str(net) != str(ip_network)]
def set_vlan_vrf(self, vlan_number, vrf_name):
self.real_switch.set_vlan_vrf(vlan_number, vrf_name)
self.vlans_cache[vlan_number].vrf_forwarding = vrf_name
def unset_vlan_vrf(self, vlan_number):
self.real_switch.unset_vlan_vrf(vlan_number)
self.vlans_cache[vlan_number].vrf_forwarding = None
def set_access_mode(self, interface_id):
self.real_switch.set_access_mode(interface_id)
self.interfaces_cache[interface_id].port_mode = ACCESS
self.interfaces_cache[interface_id].trunk_native_vlan = None
self.interfaces_cache[interface_id].trunk_vlans = []
def set_trunk_mode(self, interface_id):
self.real_switch.set_trunk_mode(interface_id)
<|code_end|>
, generate the next line using the imports in this file:
import copy
from collections import OrderedDict
from netman.core.objects.bond import Bond
from netman.core.objects.interface import Interface
from netman.core.objects.interface_states import OFF, ON
from netman.core.objects.port_modes import ACCESS, TRUNK
from netman.core.objects.switch_base import SwitchBase
from netman.core.objects.vlan import Vlan
from netman.core.objects.vrrp_group import VrrpGroup
and context (functions, classes, or occasionally code) from other files:
# Path: netman/core/objects/bond.py
# class Bond(BaseInterface):
# def __init__(self, number=None, link_speed=None, members=None, **interface):
# super(Bond, self).__init__(**interface)
# self.number = number
# self.link_speed = link_speed
# self.members = members or []
#
# @property
# def interface(self):
# warnings.warn('Deprecated: Use directly the members of Bond instead.', DeprecationWarning)
# return Interface(
# shutdown=self.shutdown,
# port_mode=self.port_mode,
# access_vlan=self.access_vlan,
# trunk_native_vlan=self.trunk_native_vlan,
# trunk_vlans=self.trunk_vlans,
# )
#
# Path: netman/core/objects/port_modes.py
# ACCESS = "ACCESS"
#
# TRUNK = "TRUNK"
#
# Path: netman/core/objects/switch_base.py
# class SwitchBase(SwitchOperations):
# def __init__(self, switch_descriptor):
# self.switch_descriptor = switch_descriptor
# self.logger = logging.getLogger("{module}.{hostname}".format(module=self.__module__, hostname=self.switch_descriptor.hostname))
# self.connected = False
# self.in_transaction = False
#
# def connect(self):
# self._connect()
# self.connected = True
#
# def disconnect(self):
# self._disconnect()
# self.connected = False
#
# def start_transaction(self):
# self._start_transaction()
# self.in_transaction = True
#
# def end_transaction(self):
# self._end_transaction()
# self.in_transaction = False
#
# def _connect(self):
# """
# Adpapters should implement this rather than connect
# """
# raise NotImplementedError()
#
# def _disconnect(self):
# """
# Adpapters should implement this rather than disconnect
# """
# raise NotImplementedError()
#
# def _start_transaction(self):
# """
# Adpapters should implement this rather than connect
# """
# raise NotImplementedError()
#
# def _end_transaction(self):
# """
# Adpapters should implement this rather than disconnect
# """
# raise NotImplementedError()
#
# @contextmanager
# def transaction(self):
# self.start_transaction()
# try:
# yield self
# self.commit_transaction()
# except Exception as e:
# if self.logger:
# self.logger.exception(e)
# self.rollback_transaction()
# raise
# finally:
# self.end_transaction()
. Output only the next line. | self.interfaces_cache[interface_id].port_mode = TRUNK |
Based on the snippet: <|code_start|> try:
del self.dict[key]
self.refresh_items.remove(key)
except KeyError:
pass
def values(self):
return self.dict.values()
class VlanCache(Cache):
object_type = Vlan
object_key = 'number'
class InterfaceCache(Cache):
object_type = Interface
object_key = 'name'
class VlanInterfaceCache(Cache):
object_type = str
object_key = 'number'
class BondCache(Cache):
object_type = Bond
object_key = 'number'
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
from collections import OrderedDict
from netman.core.objects.bond import Bond
from netman.core.objects.interface import Interface
from netman.core.objects.interface_states import OFF, ON
from netman.core.objects.port_modes import ACCESS, TRUNK
from netman.core.objects.switch_base import SwitchBase
from netman.core.objects.vlan import Vlan
from netman.core.objects.vrrp_group import VrrpGroup
and context (classes, functions, sometimes code) from other files:
# Path: netman/core/objects/bond.py
# class Bond(BaseInterface):
# def __init__(self, number=None, link_speed=None, members=None, **interface):
# super(Bond, self).__init__(**interface)
# self.number = number
# self.link_speed = link_speed
# self.members = members or []
#
# @property
# def interface(self):
# warnings.warn('Deprecated: Use directly the members of Bond instead.', DeprecationWarning)
# return Interface(
# shutdown=self.shutdown,
# port_mode=self.port_mode,
# access_vlan=self.access_vlan,
# trunk_native_vlan=self.trunk_native_vlan,
# trunk_vlans=self.trunk_vlans,
# )
#
# Path: netman/core/objects/port_modes.py
# ACCESS = "ACCESS"
#
# TRUNK = "TRUNK"
#
# Path: netman/core/objects/switch_base.py
# class SwitchBase(SwitchOperations):
# def __init__(self, switch_descriptor):
# self.switch_descriptor = switch_descriptor
# self.logger = logging.getLogger("{module}.{hostname}".format(module=self.__module__, hostname=self.switch_descriptor.hostname))
# self.connected = False
# self.in_transaction = False
#
# def connect(self):
# self._connect()
# self.connected = True
#
# def disconnect(self):
# self._disconnect()
# self.connected = False
#
# def start_transaction(self):
# self._start_transaction()
# self.in_transaction = True
#
# def end_transaction(self):
# self._end_transaction()
# self.in_transaction = False
#
# def _connect(self):
# """
# Adpapters should implement this rather than connect
# """
# raise NotImplementedError()
#
# def _disconnect(self):
# """
# Adpapters should implement this rather than disconnect
# """
# raise NotImplementedError()
#
# def _start_transaction(self):
# """
# Adpapters should implement this rather than connect
# """
# raise NotImplementedError()
#
# def _end_transaction(self):
# """
# Adpapters should implement this rather than disconnect
# """
# raise NotImplementedError()
#
# @contextmanager
# def transaction(self):
# self.start_transaction()
# try:
# yield self
# self.commit_transaction()
# except Exception as e:
# if self.logger:
# self.logger.exception(e)
# self.rollback_transaction()
# raise
# finally:
# self.end_transaction()
. Output only the next line. | class CachedSwitch(SwitchBase): |
Based on the snippet: <|code_start|>
class AddInterfaceToBondTest(ComplianceTestCase):
_dev_sample = "juniper"
def setUp(self):
super(AddInterfaceToBondTest, self).setUp()
self.client.add_bond(42)
def tearDown(self):
self.janitor.remove_bond(42)
super(AddInterfaceToBondTest, self).tearDown()
def test_sets_the_interface_bond_master(self):
self.client.add_interface_to_bond(self.test_port, 42)
interface = self.client.get_interface(self.test_port)
assert_that(interface.bond_master, is_(42))
self.janitor.remove_interface_from_bond(self.test_port)
def test_sets_the_interface_port_mode_to_bond_members(self):
self.client.add_interface_to_bond(self.test_port, 42)
interface = self.client.get_interface(self.test_port)
<|code_end|>
, predict the immediate next line with the help of imports:
from hamcrest import is_, assert_that, empty, none
from netman.core.objects.exceptions import UnknownInterface
from netman.core.objects.port_modes import BOND_MEMBER
from tests.adapters.compliance_test_case import ComplianceTestCase
and context (classes, functions, sometimes code) from other files:
# Path: netman/core/objects/port_modes.py
# BOND_MEMBER = "BOND_MEMBER"
. Output only the next line. | assert_that(interface.port_mode, is_(BOND_MEMBER)) |
Given the following code snippet before the placeholder: <|code_start|> super(ResetInterfaceTest, self).setUp()
self.interface_before = self.client.get_interface(self.test_port)
def tearDown(self):
self.janitor.remove_vlan(90)
self.janitor.remove_bond(42)
super(ResetInterfaceTest, self).tearDown()
def test_reverts_trunk_vlans(self):
self.try_to.add_vlan(90)
self.try_to.set_trunk_mode(self.test_port)
self.try_to.add_trunk_vlan(self.test_port, 90)
self.client.reset_interface(self.test_port)
assert_that(self.client.get_interface(self.test_port).trunk_vlans, is_(self.interface_before.trunk_vlans))
def test_reverts_trunk_native_vlan(self):
self.try_to.add_vlan(90)
self.try_to.set_trunk_mode(self.test_port)
self.try_to.set_interface_native_vlan(self.test_port, 90)
self.client.reset_interface(self.test_port)
assert_that(self.client.get_interface(self.test_port).trunk_native_vlan,
is_(self.interface_before.trunk_native_vlan))
def test_reverts_port_mode(self):
<|code_end|>
, predict the next line using imports from the current file:
from hamcrest import assert_that, is_
from netman.core.objects.exceptions import UnknownInterface
from netman.core.objects.interface_states import ON, OFF
from netman.core.objects.port_modes import ACCESS
from tests.adapters.compliance_test_case import ComplianceTestCase
and context including class names, function names, and sometimes code from other files:
# Path: netman/core/objects/port_modes.py
# ACCESS = "ACCESS"
. Output only the next line. | if self.interface_before.port_mode == ACCESS: |
Given the following code snippet before the placeholder: <|code_start|> self.client.set_access_mode(self.test_port)
self.client.remove_vlan(2999)
@skip_on_switches("juniper_mx", "arista_http")
def test_passing_from_trunk_mode_to_access_gets_rid_of_stuff_in_trunk_mode(self):
self.client.add_vlan(1100)
self.client.add_vlan(1200)
self.client.add_vlan(1300)
self.client.add_vlan(1400)
self.client.set_trunk_mode(self.test_port)
self.client.set_interface_native_vlan(self.test_port, vlan=1200)
self.client.add_trunk_vlan(self.test_port, vlan=1100)
self.client.add_trunk_vlan(self.test_port, vlan=1300)
self.client.add_trunk_vlan(self.test_port, vlan=1400)
interfaces = self.client.get_interfaces()
test_if = next(i for i in interfaces if i.name == self.test_port)
assert_that(test_if.port_mode, equal_to(TRUNK))
assert_that(test_if.trunk_native_vlan, equal_to(1200))
assert_that(test_if.access_vlan, equal_to(None))
assert_that(test_if.trunk_vlans, equal_to([1100, 1300, 1400]))
self.client.set_access_mode(self.test_port)
interfaces = self.client.get_interfaces()
test_if = next(i for i in interfaces if i.name == self.test_port)
<|code_end|>
, predict the next line using imports from the current file:
from hamcrest import equal_to, assert_that, has_length, is_, none
from netaddr import IPNetwork, IPAddress
from netman.core.objects.access_groups import IN, OUT
from netman.core.objects.exceptions import UnknownVlan, UnknownInterface, \
UnknownResource
from netman.core.objects.interface_states import OFF, ON
from netman.core.objects.port_modes import ACCESS, TRUNK
from tests.adapters.configured_test_case import ConfiguredTestCase, skip_on_switches
and context including class names, function names, and sometimes code from other files:
# Path: netman/core/objects/port_modes.py
# ACCESS = "ACCESS"
#
# TRUNK = "TRUNK"
. Output only the next line. | assert_that(test_if.port_mode, equal_to(ACCESS)) |
Based on the snippet: <|code_start|> @skip_on_switches("juniper_mx", "arista_http")
def test_native_trunk(self):
self.client.add_vlan(2999, name="my-test-vlan")
self.client.set_trunk_mode(self.test_port)
self.client.set_interface_native_vlan(self.test_port, vlan=2999)
self.client.unset_interface_native_vlan(self.test_port)
self.client.set_access_mode(self.test_port)
self.client.remove_vlan(2999)
@skip_on_switches("juniper_mx", "arista_http")
def test_passing_from_trunk_mode_to_access_gets_rid_of_stuff_in_trunk_mode(self):
self.client.add_vlan(1100)
self.client.add_vlan(1200)
self.client.add_vlan(1300)
self.client.add_vlan(1400)
self.client.set_trunk_mode(self.test_port)
self.client.set_interface_native_vlan(self.test_port, vlan=1200)
self.client.add_trunk_vlan(self.test_port, vlan=1100)
self.client.add_trunk_vlan(self.test_port, vlan=1300)
self.client.add_trunk_vlan(self.test_port, vlan=1400)
interfaces = self.client.get_interfaces()
test_if = next(i for i in interfaces if i.name == self.test_port)
<|code_end|>
, predict the immediate next line with the help of imports:
from hamcrest import equal_to, assert_that, has_length, is_, none
from netaddr import IPNetwork, IPAddress
from netman.core.objects.access_groups import IN, OUT
from netman.core.objects.exceptions import UnknownVlan, UnknownInterface, \
UnknownResource
from netman.core.objects.interface_states import OFF, ON
from netman.core.objects.port_modes import ACCESS, TRUNK
from tests.adapters.configured_test_case import ConfiguredTestCase, skip_on_switches
and context (classes, functions, sometimes code) from other files:
# Path: netman/core/objects/port_modes.py
# ACCESS = "ACCESS"
#
# TRUNK = "TRUNK"
. Output only the next line. | assert_that(test_if.port_mode, equal_to(TRUNK)) |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2015 Internap.
#
# 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 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 specific language governing permissions and
# limitations under the License.
class BrocadeTest(unittest.TestCase):
def setUp(self):
self.switch = Brocade(SwitchDescriptor(model='brocade', hostname="my.hostname"), None)
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import mock
from flexmock import flexmock, flexmock_teardown
from hamcrest import assert_that, has_length, equal_to, is_, none, empty
from netaddr import IPNetwork
from netaddr.ip import IPAddress
from netman.adapters.switches import brocade_factory_ssh, brocade_factory_telnet
from netman.adapters.switches.brocade import Brocade, parse_if_ranges
from netman.adapters.switches.util import SubShell
from netman.core.objects.access_groups import IN, OUT
from netman.core.objects.exceptions import IPNotAvailable, UnknownVlan, UnknownIP, UnknownAccessGroup, BadVlanNumber, \
BadVlanName, UnknownInterface, TrunkVlanNotSet, UnknownVrf, VlanVrfNotSet, VrrpAlreadyExistsForVlan, BadVrrpPriorityNumber, BadVrrpGroupNumber, \
BadVrrpTimers, BadVrrpTracking, NoIpOnVlanForVrrp, VrrpDoesNotExistForVlan, UnknownDhcpRelayServer, DhcpRelayServerAlreadyExists, \
VlanAlreadyExist, InvalidAccessGroupName, IPAlreadySet
from netman.core.objects.interface_states import OFF, ON
from netman.core.objects.port_modes import ACCESS, TRUNK
from netman.core.objects.switch_descriptor import SwitchDescriptor
and context including class names, function names, and sometimes code from other files:
# Path: netman/adapters/switches/util.py
# class SubShell(object):
# debug = False
#
# def __init__(self, ssh, enter, exit_cmd, validate=None):
# self.ssh = ssh
# self.enter = enter
# self.exit = exit_cmd
# self.validate = validate or (lambda x: None)
#
# def __enter__(self):
# if isinstance(self.enter, list):
# [self.validate(self.ssh.do(cmd)) for cmd in self.enter]
# else:
# self.validate(self.ssh.do(self.enter))
# return self.ssh
#
# def __exit__(self, eType, eValue, eTrace):
# if self.debug and eType is not None:
# logging.error("Subshell exception {}: {}\n{}"
# .format(eType.__name__, eValue, "".join(traceback.format_tb(eTrace))))
#
# self.ssh.do(self.exit)
#
# Path: netman/core/objects/port_modes.py
# ACCESS = "ACCESS"
#
# TRUNK = "TRUNK"
#
# Path: netman/core/objects/switch_descriptor.py
# class SwitchDescriptor(Model):
# def __init__(self, model, hostname, username=None, password=None, port=None, netman_server=None):
# self.model = model
# self.hostname = hostname
# self.username = username
# self.password = password
# self.port = port
# self.netman_server = netman_server
. Output only the next line. | SubShell.debug = True |
Predict the next line after this snippet: <|code_start|> self.shell_mock.should_receive("do").with_args("show running-config vlan").once().ordered().and_return([
"spanning-tree",
"!",
"vlan 1 name DEFAULT-VLAN",
" no untagged ethe 1/3",
"!",
"vlan 100",
" tagged ethe 1/2 ethe 1/4 to 1/6",
"!",
"vlan 200",
" tagged ethe 1/2",
"!",
"vlan 300",
" tagged ethe 1/2",
"!",
"vlan 1999",
" untagged ethe 1/1",
"!",
"vlan 2999",
" untagged ethe 1/2",
"!",
"!"
])
result = self.switch.get_interfaces()
if1, if2, if3, if4, if5, if6 = result
assert_that(if1.name, equal_to("ethernet 1/1"))
assert_that(if1.shutdown, equal_to(False))
<|code_end|>
using the current file's imports:
import unittest
import mock
from flexmock import flexmock, flexmock_teardown
from hamcrest import assert_that, has_length, equal_to, is_, none, empty
from netaddr import IPNetwork
from netaddr.ip import IPAddress
from netman.adapters.switches import brocade_factory_ssh, brocade_factory_telnet
from netman.adapters.switches.brocade import Brocade, parse_if_ranges
from netman.adapters.switches.util import SubShell
from netman.core.objects.access_groups import IN, OUT
from netman.core.objects.exceptions import IPNotAvailable, UnknownVlan, UnknownIP, UnknownAccessGroup, BadVlanNumber, \
BadVlanName, UnknownInterface, TrunkVlanNotSet, UnknownVrf, VlanVrfNotSet, VrrpAlreadyExistsForVlan, BadVrrpPriorityNumber, BadVrrpGroupNumber, \
BadVrrpTimers, BadVrrpTracking, NoIpOnVlanForVrrp, VrrpDoesNotExistForVlan, UnknownDhcpRelayServer, DhcpRelayServerAlreadyExists, \
VlanAlreadyExist, InvalidAccessGroupName, IPAlreadySet
from netman.core.objects.interface_states import OFF, ON
from netman.core.objects.port_modes import ACCESS, TRUNK
from netman.core.objects.switch_descriptor import SwitchDescriptor
and any relevant context from other files:
# Path: netman/adapters/switches/util.py
# class SubShell(object):
# debug = False
#
# def __init__(self, ssh, enter, exit_cmd, validate=None):
# self.ssh = ssh
# self.enter = enter
# self.exit = exit_cmd
# self.validate = validate or (lambda x: None)
#
# def __enter__(self):
# if isinstance(self.enter, list):
# [self.validate(self.ssh.do(cmd)) for cmd in self.enter]
# else:
# self.validate(self.ssh.do(self.enter))
# return self.ssh
#
# def __exit__(self, eType, eValue, eTrace):
# if self.debug and eType is not None:
# logging.error("Subshell exception {}: {}\n{}"
# .format(eType.__name__, eValue, "".join(traceback.format_tb(eTrace))))
#
# self.ssh.do(self.exit)
#
# Path: netman/core/objects/port_modes.py
# ACCESS = "ACCESS"
#
# TRUNK = "TRUNK"
#
# Path: netman/core/objects/switch_descriptor.py
# class SwitchDescriptor(Model):
# def __init__(self, model, hostname, username=None, password=None, port=None, netman_server=None):
# self.model = model
# self.hostname = hostname
# self.username = username
# self.password = password
# self.port = port
# self.netman_server = netman_server
. Output only the next line. | assert_that(if1.port_mode, equal_to(ACCESS)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.