Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|> def f(a, b, c, *args):
raise NotImplementedError()
sig = FunctionSignature(f)
with self.assertRaises(UnknownArguments):
sig.get_normalized_args((1, 2, 3, 4), dict(d=5))
def test__kwargs(self):
def f(a, b, c=2):
pass
def f_args(a, b, c=2, *args):
pass
def f_kwargs(a, b, c=2, **kwargs):
pass
def f_args_kwargs(a, b, c=2, *args, **kwargs):
pass
lambda_args_kwargs = lambda a, b, c=2, *args, **kwargs: None
sig = [('a', False),
('b', False),
('c', True, 2)]
self._test_function_signature(f, sig)
self._test_function_signature(f_args, sig, has_varargs=True)
self._test_function_signature(f_kwargs, sig, has_varkwargs=True)
self._test_function_signature(f_args_kwargs, sig, has_varargs=True, has_varkwargs=True)
self._test_function_signature(lambda_args_kwargs, sig, has_varargs=True, has_varkwargs=True)
def test__normalizing_kwargs_with_numbers(self):
# this is supported in python, but interferes with the arg-normalizing logic
sig = FunctionSignature(lambda *args, **kwargs: None)
<|code_end|>
, predict the next line using imports from the current file:
import time
from .test_utils import TestCase
from infi.pyutils.function_signature import FunctionSignature
from infi.pyutils.exceptions import SignatureException, InvalidKeywordArgument, UnknownArguments, MissingArguments
and context including class names, function names, and sometimes code from other files:
# Path: infi/pyutils/function_signature.py
# class FunctionSignature(object):
# def __init__(self, func):
# super(FunctionSignature, self).__init__()
# self.func = func
# self.func_name = func.__name__
# self._build_arguments()
# def is_bound_method(self):
# return is_bound_method(self.func)
# def is_class_method(self):
# return is_class_method(self.func)
# def _iter_args_and_defaults(self, args, defaults):
# defaults = [] if defaults is None else defaults
# filled_defaults = itertools.chain(itertools.repeat(_NO_DEFAULT, len(args) - len(defaults)), defaults)
# return izip(args, filled_defaults)
#
# def _build_arguments(self):
# self._args = []
# try:
# args, varargs_name, kwargs_name, defaults = inspect.getargspec(self.func)
# except TypeError:
# args = []
# varargs_name = 'args'
# kwargs_name = 'kwargs'
# defaults = []
# for arg_name, default in self._iter_args_and_defaults(args, defaults):
# self._args.append(Argument(arg_name, default))
# self._varargs_name = varargs_name
# self._kwargs_name = kwargs_name
# def get_args(self):
# return itertools.islice(self._args, 1 if self.is_bound_method() else 0, None)
# def get_num_args(self):
# returned = len(self._args)
# if self.is_bound_method():
# returned = max(0, returned - 1)
# return returned
# def get_self_arg_name(self):
# if self.is_bound_method() and len(self._args) > 0:
# return self._args[0].name
# return None
# def get_arg_names(self):
# return (arg.name for arg in self.get_args())
# def get_required_arg_names(self):
# return set(arg.name for arg in self.get_args() if not arg.has_default())
# def has_variable_args(self):
# return self._varargs_name is not None
# def has_variable_kwargs(self):
# return self._kwargs_name is not None
# def get_normalized_args(self, args, kwargs):
# returned = {}
# self._update_normalized_positional_args(returned, args)
# self._update_normalized_kwargs(returned, kwargs)
# self._check_missing_arguments(returned)
# self._check_unknown_arguments(returned)
# return returned
# def _update_normalized_positional_args(self, returned, args):
# argument_names = list(self.get_arg_names())
# argument_names.extend(range(len(args) - self.get_num_args()))
# for arg_name, given_arg in zip(argument_names, args):
# returned[arg_name] = given_arg
#
# def _update_normalized_kwargs(self, returned, kwargs):
# for arg_name, arg in iteritems(kwargs):
# if not isinstance(arg_name, basestring):
# raise InvalidKeywordArgument("Invalid keyword argument %r" % (arg_name,))
# if arg_name in returned:
# raise SignatureException("%s is given more than once to %s" % (arg_name, self.func_name))
# returned[arg_name] = arg
#
# def _check_missing_arguments(self, args_dict):
# required_arguments = self.get_required_arg_names()
# missing_arguments = required_arguments - set(args_dict)
# if missing_arguments:
# raise MissingArguments("The following arguments were not specified: %s" % ",".join(map(repr, missing_arguments)))
# def _check_unknown_arguments(self, args_dict):
# positional_arg_count = len([arg_name for arg_name in args_dict if isinstance(arg_name, Number)])
# num_args = self.get_num_args()
# if positional_arg_count and not self.has_variable_args():
# raise UnknownArguments("%s receives %s positional arguments (%s specified)" % (self.func_name, num_args, num_args + positional_arg_count))
# unknown = set(arg for arg in args_dict if not isinstance(arg, Number)) - set(self.get_arg_names())
# if unknown and not self.has_variable_kwargs():
# raise UnknownArguments("%s received unknown argument(s): %s" % (self.func_name, ",".join(unknown)))
#
# Path: infi/pyutils/exceptions.py
# class SignatureException(ReflectionException):
# pass
#
# class InvalidKeywordArgument(ReflectionException):
# pass
#
# class UnknownArguments(SignatureException):
# pass
#
# class MissingArguments(SignatureException):
# pass
. Output only the next line. | with self.assertRaises(InvalidKeywordArgument): |
Predict the next line after this snippet: <|code_start|> def _assert_argument_names(self, sig, names):
self.assertEquals([arg.name for arg in sig._args], names)
def _test_function_signature(self,
func,
expected_signature,
has_varargs=False,
has_varkwargs=False
):
sig = FunctionSignature(func)
self.assertEquals(len(expected_signature), len(sig._args))
self.assertEquals(len(expected_signature), sig.get_num_args())
for expected_arg, arg in zip(expected_signature, sig._args):
if isinstance(expected_arg, tuple):
expected_arg = ExpectedArg(*expected_arg)
self.assertEquals(expected_arg.name,
arg.name)
self.assertEquals(expected_arg.has_default,
arg.has_default())
if expected_arg.has_default:
self.assertEquals(expected_arg.default, arg.default)
self.assertEquals(sig.has_variable_kwargs(), has_varkwargs)
self.assertEquals(sig.has_variable_args(), has_varargs)
self._test_missing_arguments(sig, expected_signature)
def _test_missing_arguments(self, signature, expected_signature):
expected_signature = [ExpectedArg(*x) for x in expected_signature]
kwargs = dict((x.name, 666) for x in expected_signature)
to_remove = [arg for arg in expected_signature]
kwargs.pop([e.name for e in expected_signature if not e.has_default][0])
<|code_end|>
using the current file's imports:
import time
from .test_utils import TestCase
from infi.pyutils.function_signature import FunctionSignature
from infi.pyutils.exceptions import SignatureException, InvalidKeywordArgument, UnknownArguments, MissingArguments
and any relevant context from other files:
# Path: infi/pyutils/function_signature.py
# class FunctionSignature(object):
# def __init__(self, func):
# super(FunctionSignature, self).__init__()
# self.func = func
# self.func_name = func.__name__
# self._build_arguments()
# def is_bound_method(self):
# return is_bound_method(self.func)
# def is_class_method(self):
# return is_class_method(self.func)
# def _iter_args_and_defaults(self, args, defaults):
# defaults = [] if defaults is None else defaults
# filled_defaults = itertools.chain(itertools.repeat(_NO_DEFAULT, len(args) - len(defaults)), defaults)
# return izip(args, filled_defaults)
#
# def _build_arguments(self):
# self._args = []
# try:
# args, varargs_name, kwargs_name, defaults = inspect.getargspec(self.func)
# except TypeError:
# args = []
# varargs_name = 'args'
# kwargs_name = 'kwargs'
# defaults = []
# for arg_name, default in self._iter_args_and_defaults(args, defaults):
# self._args.append(Argument(arg_name, default))
# self._varargs_name = varargs_name
# self._kwargs_name = kwargs_name
# def get_args(self):
# return itertools.islice(self._args, 1 if self.is_bound_method() else 0, None)
# def get_num_args(self):
# returned = len(self._args)
# if self.is_bound_method():
# returned = max(0, returned - 1)
# return returned
# def get_self_arg_name(self):
# if self.is_bound_method() and len(self._args) > 0:
# return self._args[0].name
# return None
# def get_arg_names(self):
# return (arg.name for arg in self.get_args())
# def get_required_arg_names(self):
# return set(arg.name for arg in self.get_args() if not arg.has_default())
# def has_variable_args(self):
# return self._varargs_name is not None
# def has_variable_kwargs(self):
# return self._kwargs_name is not None
# def get_normalized_args(self, args, kwargs):
# returned = {}
# self._update_normalized_positional_args(returned, args)
# self._update_normalized_kwargs(returned, kwargs)
# self._check_missing_arguments(returned)
# self._check_unknown_arguments(returned)
# return returned
# def _update_normalized_positional_args(self, returned, args):
# argument_names = list(self.get_arg_names())
# argument_names.extend(range(len(args) - self.get_num_args()))
# for arg_name, given_arg in zip(argument_names, args):
# returned[arg_name] = given_arg
#
# def _update_normalized_kwargs(self, returned, kwargs):
# for arg_name, arg in iteritems(kwargs):
# if not isinstance(arg_name, basestring):
# raise InvalidKeywordArgument("Invalid keyword argument %r" % (arg_name,))
# if arg_name in returned:
# raise SignatureException("%s is given more than once to %s" % (arg_name, self.func_name))
# returned[arg_name] = arg
#
# def _check_missing_arguments(self, args_dict):
# required_arguments = self.get_required_arg_names()
# missing_arguments = required_arguments - set(args_dict)
# if missing_arguments:
# raise MissingArguments("The following arguments were not specified: %s" % ",".join(map(repr, missing_arguments)))
# def _check_unknown_arguments(self, args_dict):
# positional_arg_count = len([arg_name for arg_name in args_dict if isinstance(arg_name, Number)])
# num_args = self.get_num_args()
# if positional_arg_count and not self.has_variable_args():
# raise UnknownArguments("%s receives %s positional arguments (%s specified)" % (self.func_name, num_args, num_args + positional_arg_count))
# unknown = set(arg for arg in args_dict if not isinstance(arg, Number)) - set(self.get_arg_names())
# if unknown and not self.has_variable_kwargs():
# raise UnknownArguments("%s received unknown argument(s): %s" % (self.func_name, ",".join(unknown)))
#
# Path: infi/pyutils/exceptions.py
# class SignatureException(ReflectionException):
# pass
#
# class InvalidKeywordArgument(ReflectionException):
# pass
#
# class UnknownArguments(SignatureException):
# pass
#
# class MissingArguments(SignatureException):
# pass
. Output only the next line. | with self.assertRaises(MissingArguments): |
Based on the snippet: <|code_start|> value = inst._cache[self.__name__]
except (KeyError, AttributeError):
value = self.fget(inst)
try:
cache = inst._cache
except AttributeError:
cache = inst._cache = {}
cache[self.__name__] = value
return value
_cached_method_id_allocator = itertools.count()
def _get_instancemethod_cache_entry(method_id, *args, **kwargs):
if len(args) + len(kwargs) == 0:
return method_id
try:
kwargs_keys = list(kwargs.keys())
kwargs_keys.sort()
key = (method_id,) + args + tuple([kwargs[key] for key in kwargs_keys])
_ = {key: None}
return key
except TypeError:
return None
def cached_method(func):
"""Decorator that caches a method's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
method_id = next(_cached_method_id_allocator)
<|code_end|>
, predict the immediate next line with the help of imports:
import itertools
import time
from .decorators import wraps
from .python_compat import iteritems
from logging import getLogger
from types import MethodType, FunctionType
from inspect import getmembers
and context (classes, functions, sometimes code) from other files:
# Path: infi/pyutils/decorators.py
# def wraps(wrapped):
# """ a convenience function on top of functools.wraps:
#
# - adds the original function to the wrapped function as __wrapped__ attribute."""
# def new_decorator(f):
# returned = functools.wraps(wrapped)(f)
# returned.__wrapped__ = wrapped
# return returned
# return new_decorator
#
# Path: infi/pyutils/python_compat.py
# _PYTHON_VERSION = platform.python_version()
# _IS_PYTHON_3 = _PYTHON_VERSION >= '3'
# _IS_BELOW_PYTHON_2_7 = _PYTHON_VERSION < '2.7'
# def get_underlying_function(f):
# def _get_underlying_classmethod_function(f):
# def create_bound_method(func, self):
# class TemporaryClass(object):
. Output only the next line. | @wraps(func) |
Using the snippet: <|code_start|> """Decorator that caches a method's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
decorated class must implement inst.init_cache() which creates inst._cache dictionary.
"""
method_id = next(_cached_method_id_allocator)
@wraps(func)
def callee(inst, *args, **kwargs):
key = _get_instancemethod_cache_entry(method_id, *args, **kwargs)
func_name = func.__name__
if key is None:
logger.debug("Passed arguments to {0} are mutable, so the returned value will not be cached".format(func_name))
return func(inst, *args, **kwargs)
try:
return inst._cache[func_name][key]
except (KeyError, AttributeError):
value = func(inst, *args, **kwargs)
if not hasattr(inst, "_cache"):
inst._cache = CacheData()
if inst._cache.get(func_name, None) is None:
#cache class creator returns a dict
inst._cache[func_name] = self.cache_class()
inst._cache[func_name][key] = value
return value
callee.__cached_method__ = True
callee.__method_id__ = method_id
return callee
def _get_function_cache_entry(args, kwargs):
<|code_end|>
, determine the next line of code. You have imports:
import itertools
import time
from .decorators import wraps
from .python_compat import iteritems
from logging import getLogger
from types import MethodType, FunctionType
from inspect import getmembers
and context (class names, function names, or code) available:
# Path: infi/pyutils/decorators.py
# def wraps(wrapped):
# """ a convenience function on top of functools.wraps:
#
# - adds the original function to the wrapped function as __wrapped__ attribute."""
# def new_decorator(f):
# returned = functools.wraps(wrapped)(f)
# returned.__wrapped__ = wrapped
# return returned
# return new_decorator
#
# Path: infi/pyutils/python_compat.py
# _PYTHON_VERSION = platform.python_version()
# _IS_PYTHON_3 = _PYTHON_VERSION >= '3'
# _IS_BELOW_PYTHON_2_7 = _PYTHON_VERSION < '2.7'
# def get_underlying_function(f):
# def _get_underlying_classmethod_function(f):
# def create_bound_method(func, self):
# class TemporaryClass(object):
. Output only the next line. | return (tuple(args), frozenset(iteritems(kwargs))) |
Given the code snippet: <|code_start|>
_PYTHON_VERSION = sys.version_info
if _PYTHON_VERSION >= (3,):
else:
if _PYTHON_VERSION >= (3,5):
def contextmanager(func):
<|code_end|>
, generate the next line using the imports in this file:
import sys
from .decorators import wraps
from contextlib import _GeneratorContextManager
from contextlib import GeneratorContextManager as _GeneratorContextManager
and context (functions, classes, or occasionally code) from other files:
# Path: infi/pyutils/decorators.py
# def wraps(wrapped):
# """ a convenience function on top of functools.wraps:
#
# - adds the original function to the wrapped function as __wrapped__ attribute."""
# def new_decorator(f):
# returned = functools.wraps(wrapped)(f)
# returned.__wrapped__ = wrapped
# return returned
# return new_decorator
. Output only the next line. | @wraps(func) |
Based on the snippet: <|code_start|>
def wraps(wrapped):
""" a convenience function on top of functools.wraps:
- adds the original function to the wrapped function as __wrapped__ attribute."""
def new_decorator(f):
returned = functools.wraps(wrapped)(f)
returned.__wrapped__ = wrapped
return returned
return new_decorator
def inspect_getargspec_patch(func):
"""calls inspect's getargspec with func.__wrapped__ if exists, else with func"""
return inspect._infi_patched_getargspec(_get_innner_func(func))
def ipython_getargspec_patch(func):
return _ipython_inspect_module._infi_patched_getargspec(_get_innner_func(func))
def _get_innner_func(f):
while True:
wrapped = getattr(f, "__wrapped__", None)
if wrapped is None:
return f
f = wrapped
<|code_end|>
, predict the immediate next line with the help of imports:
import functools
import inspect
from .patch import monkey_patch
from IPython.core import oinspect as _ipython_inspect_module
from IPython import OInspect as _ipython_inspect_module
and context (classes, functions, sometimes code) from other files:
# Path: infi/pyutils/patch.py
# def monkey_patch(module, name, replacement):
# original_name = _PATCHED_NAME_PREFIX + name
# if getattr(module, original_name, None) is None:
# setattr(module, original_name, getattr(module, name))
# setattr(module, name, replacement)
. Output only the next line. | monkey_patch(inspect, "getargspec", inspect_getargspec_patch) |
Predict the next line after this snippet: <|code_start|> >>> avg.as_version('2.0') == 'Average'
True
"""
def __init__(self, key, list_or_dict=None, default_version=ALL, **kwargs):
super(Value, self).__init__(default_version)
if isinstance(key, Value):
key = str(key)
self._key = str(key)
if list_or_dict is None:
list_or_dict = []
if isinstance(list_or_dict, dict):
self._construct_from_dict(list_or_dict)
else:
if 'aliases' in kwargs:
# For backwards compatibility with old non versioned enums
list_or_dict = kwargs.get('aliases')
self._construct_from_list(list_or_dict)
def _construct_from_list(self, values):
converted_values = [self._key]
for value in values:
if isinstance(value, Value):
converted_values.extend(value.get_values())
else:
converted_values.append(value)
self._construct_from_dict({ALL:converted_values})
self.bind_to_version(ALL)
def _construct_from_dict(self, values):
<|code_end|>
using the current file's imports:
from packaging.version import Version, parse
from .python_compat import OrderedDict, itervalues
and any relevant context from other files:
# Path: infi/pyutils/python_compat.py
# _PYTHON_VERSION = platform.python_version()
# _IS_PYTHON_3 = _PYTHON_VERSION >= '3'
# _IS_BELOW_PYTHON_2_7 = _PYTHON_VERSION < '2.7'
# def get_underlying_function(f):
# def _get_underlying_classmethod_function(f):
# def create_bound_method(func, self):
# class TemporaryClass(object):
. Output only the next line. | self._values = OrderedDict((_convert(k), values[k]) for k in reversed(sorted(values.keys()))) |
Here is a snippet: <|code_start|> An Enum class for python.
>>> x = Enum(VersionedValue("True",{'1.0': ["TRUE"],
'2.0': ["True","yes"]}),
VersionedValue("False",{'1.0': ["FALSE"],
'2.0': ["False","No"]}))
>>> x.true
TRUE
>>> "TRUE" in x
True
>>> x.false
FALSE
>>> x.false == "NOT"
True
>>> "NOT" in x
True
>>> "FALSE" in x
True
"""
def __init__(self, *values, **kwargs):
default_version = kwargs.get('default_version', ALL)
super(Enum, self).__init__(default_version)
self._values = OrderedDict()
for value in values:
if not isinstance(value, Value):
value = Value(value)
self._values[str(value)] = value.as_version(default_version)
def bind_to_version(self, version):
super(Enum, self).bind_to_version(version)
<|code_end|>
. Write the next line using the current file imports:
from packaging.version import Version, parse
from .python_compat import OrderedDict, itervalues
and context from other files:
# Path: infi/pyutils/python_compat.py
# _PYTHON_VERSION = platform.python_version()
# _IS_PYTHON_3 = _PYTHON_VERSION >= '3'
# _IS_BELOW_PYTHON_2_7 = _PYTHON_VERSION < '2.7'
# def get_underlying_function(f):
# def _get_underlying_classmethod_function(f):
# def create_bound_method(func, self):
# class TemporaryClass(object):
, which may include functions, classes, or code. Output only the next line. | for value in itervalues(self._values): |
Given the following code snippet before the placeholder: <|code_start|>
class RecursiveGetattrTest(TestCase):
def setUp(self):
super(RecursiveGetattrTest, self).setUp()
self.obj = Object()
self.obj.a = Object()
self.obj.a.b = Object()
self.obj.a.b.value = self.value = Object()
def test__recursive_getattr_success(self):
<|code_end|>
, predict the next line using imports from the current file:
from .test_utils import TestCase
from infi.pyutils import recursive_getattr
and context including class names, function names, and sometimes code from other files:
# Path: infi/pyutils/misc.py
# def recursive_getattr(obj, attr, default=_NOTHING):
# for subattr in attr.split("."):
# obj = getattr(obj, subattr, _NOTHING)
# if obj is _NOTHING:
# if default is not _NOTHING:
# return default
# raise AttributeError(attr)
# return obj
. Output only the next line. | self.assertIs(recursive_getattr(self.obj, 'a.b.value'), |
Next line prediction: <|code_start|>
class MethodMapTest(TestCase):
def test__method_map(self):
class MyObj(object):
<|code_end|>
. Use current file imports:
(import platform
from .test_utils import TestCase
from infi.pyutils.method_map import MethodMap)
and context including class names, function names, or small code snippets from other files:
# Path: infi/pyutils/method_map.py
# class MethodMap(object):
# def __init__(self, decorator=Identity):
# super(MethodMap, self).__init__()
# self._map = {}
# self._decorate = decorator
# def registering(self, key):
# return functools.partial(self.register, key)
# def register(self, key, value):
# self._map[key] = self._decorate(value)
# return value
# def __get__(self, instance, owner):
# return Binder(self._map, instance)
. Output only the next line. | METHODS = MethodMap() |
Continue the code snippet: <|code_start|>
class Predicate(Functor):
def __init__(self, func=None):
super(Predicate, self).__init__()
self._func = func
def __call__(self, *args, **kwargs):
return self._func(*args, **kwargs)
def __repr__(self):
return "<Predicate {0!r}>".format(self._func or "?")
<|code_end|>
. Use current file imports:
import operator
import functools
from .functors.functor import Functor
from .functors.always import Always
from .python_compat import iteritems
and context (classes, functions, or code) from other files:
# Path: infi/pyutils/functors/functor.py
# class Functor(object):
# def __call__(self, *args, **kwargs):
# raise NotImplementedError()
#
# Path: infi/pyutils/functors/always.py
# class Always(Functor):
# def __init__(self, value):
# super(Always, self).__init__()
# self._value = value
# def __call__(self, *args, **kwargs):
# return self._value
# def __repr__(self):
# return "<Always {0!r}>".format(self._value)
#
# Path: infi/pyutils/python_compat.py
# _PYTHON_VERSION = platform.python_version()
# _IS_PYTHON_3 = _PYTHON_VERSION >= '3'
# _IS_BELOW_PYTHON_2_7 = _PYTHON_VERSION < '2.7'
# def get_underlying_function(f):
# def _get_underlying_classmethod_function(f):
# def create_bound_method(func, self):
# class TemporaryClass(object):
. Output only the next line. | AlwaysTrue = Predicate(Always(True)) |
Based on the snippet: <|code_start|> def __init__(self, pred):
super(Not, self).__init__()
self._pred = pred
def __call__(self, *args, **kwargs):
return not self._pred(*args, **kwargs)
def __repr__(self):
return "<not {0!r}>".format(self._pred)
class Identity(Predicate):
def __init__(self, obj):
super(Identity, self).__init__(functools.partial(operator.is_, obj))
self._obj = obj
def __repr__(self):
return "<is {0!r}>".format(self._obj)
class Equality(Predicate):
def __init__(self, obj):
super(Equality, self).__init__(functools.partial(operator.eq, obj))
self._obj = obj
def __repr__(self):
return "< == {0!r}>".format(self._obj)
class _MISSING(object):
pass
class ObjectAttributes(Predicate):
def __init__(self, **attributes):
super(ObjectAttributes, self).__init__()
self._attributes = attributes
def __call__(self, obj):
<|code_end|>
, predict the immediate next line with the help of imports:
import operator
import functools
from .functors.functor import Functor
from .functors.always import Always
from .python_compat import iteritems
and context (classes, functions, sometimes code) from other files:
# Path: infi/pyutils/functors/functor.py
# class Functor(object):
# def __call__(self, *args, **kwargs):
# raise NotImplementedError()
#
# Path: infi/pyutils/functors/always.py
# class Always(Functor):
# def __init__(self, value):
# super(Always, self).__init__()
# self._value = value
# def __call__(self, *args, **kwargs):
# return self._value
# def __repr__(self):
# return "<Always {0!r}>".format(self._value)
#
# Path: infi/pyutils/python_compat.py
# _PYTHON_VERSION = platform.python_version()
# _IS_PYTHON_3 = _PYTHON_VERSION >= '3'
# _IS_BELOW_PYTHON_2_7 = _PYTHON_VERSION < '2.7'
# def get_underlying_function(f):
# def _get_underlying_classmethod_function(f):
# def create_bound_method(func, self):
# class TemporaryClass(object):
. Output only the next line. | return all(getattr(obj, attr, _MISSING) == value for attr, value in iteritems(self._attributes)) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
Django TailorDev Biblio
Test forms
"""
from __future__ import unicode_literals
def test_text_to_list():
"""Test text_to_list utils"""
inputs = [
"foo,bar,lol",
"foo , bar, lol",
"foo\nbar\nlol",
"foo,\nbar,\nlol",
"foo, \nbar,lol",
"foo,,bar,\nlol",
]
expected = ["bar", "foo", "lol"]
for input in inputs:
<|code_end|>
. Use current file imports:
(from django.test import TestCase
from ..forms import text_to_list, EntryBatchImportForm)
and context including class names, function names, or small code snippets from other files:
# Path: td_biblio/forms.py
# def text_to_list(raw):
# """Transform a raw text list to a python sorted object list
# Supported separators: coma, space and carriage return
# """
# return sorted(
# list(
# set(
# id.strip()
# for r in map(methodcaller("split", ","), raw.split())
# for id in r
# if len(id)
# )
# )
# )
#
# class EntryBatchImportForm(forms.Form):
#
# pmids = forms.CharField(
# label=_("PMID"),
# widget=forms.Textarea(attrs={"placeholder": "ex: 26588162, 19569182"}),
# help_text=_(
# "Paste a list of PubMed Identifiers " "(comma separated or one per line)"
# ),
# required=False,
# )
#
# dois = forms.CharField(
# label=_("DOI"),
# widget=forms.Textarea(
# attrs={"placeholder": "ex: 10.1093/nar/gks419, 10.1093/nar/gkp323"}
# ),
# help_text=_(
# "Paste a list of Digital Object Identifiers "
# "(comma separated or one per line)"
# ),
# required=False,
# )
#
# def clean_pmids(self):
# """Transform raw data in a PMID list"""
# pmids = text_to_list(self.cleaned_data["pmids"])
# for pmid in pmids:
# pmid_validator(pmid)
# return pmids
#
# def clean_dois(self):
# """Transform raw data in a DOI list"""
# dois = text_to_list(self.cleaned_data["dois"])
# for doi in dois:
# doi_validator(doi)
# return dois
#
# def clean(self):
# super(EntryBatchImportForm, self).clean()
#
# dois = self.cleaned_data.get("dois", [])
# pmids = self.cleaned_data.get("pmids", [])
#
# if not len(dois) and not len(pmids):
# raise forms.ValidationError(
# _("You need to submit at least one valid DOI or PMID")
# )
. Output only the next line. | result = text_to_list(input) |
Given the code snippet: <|code_start|> "foo,,bar,\nlol",
]
expected = ["bar", "foo", "lol"]
for input in inputs:
result = text_to_list(input)
result.sort()
assert result == expected
class EntryBatchImportFormTests(TestCase):
"""
Tests for the EntryBatchImportForm
"""
def test_clean_pmids(self):
"""Test PMIDs cleaning method"""
inputs = [
{"pmids": "26588162\n19569182"},
{"pmids": "19569182\n26588162"},
{"pmids": "19569182,\n26588162"},
{"pmids": "19569182,26588162"},
{"pmids": "19569182,,26588162"},
{"pmids": "19569182\n\n26588162"},
]
expected = ["19569182", "26588162"]
for input in inputs:
<|code_end|>
, generate the next line using the imports in this file:
from django.test import TestCase
from ..forms import text_to_list, EntryBatchImportForm
and context (functions, classes, or occasionally code) from other files:
# Path: td_biblio/forms.py
# def text_to_list(raw):
# """Transform a raw text list to a python sorted object list
# Supported separators: coma, space and carriage return
# """
# return sorted(
# list(
# set(
# id.strip()
# for r in map(methodcaller("split", ","), raw.split())
# for id in r
# if len(id)
# )
# )
# )
#
# class EntryBatchImportForm(forms.Form):
#
# pmids = forms.CharField(
# label=_("PMID"),
# widget=forms.Textarea(attrs={"placeholder": "ex: 26588162, 19569182"}),
# help_text=_(
# "Paste a list of PubMed Identifiers " "(comma separated or one per line)"
# ),
# required=False,
# )
#
# dois = forms.CharField(
# label=_("DOI"),
# widget=forms.Textarea(
# attrs={"placeholder": "ex: 10.1093/nar/gks419, 10.1093/nar/gkp323"}
# ),
# help_text=_(
# "Paste a list of Digital Object Identifiers "
# "(comma separated or one per line)"
# ),
# required=False,
# )
#
# def clean_pmids(self):
# """Transform raw data in a PMID list"""
# pmids = text_to_list(self.cleaned_data["pmids"])
# for pmid in pmids:
# pmid_validator(pmid)
# return pmids
#
# def clean_dois(self):
# """Transform raw data in a DOI list"""
# dois = text_to_list(self.cleaned_data["dois"])
# for doi in dois:
# doi_validator(doi)
# return dois
#
# def clean(self):
# super(EntryBatchImportForm, self).clean()
#
# dois = self.cleaned_data.get("dois", [])
# pmids = self.cleaned_data.get("pmids", [])
#
# if not len(dois) and not len(pmids):
# raise forms.ValidationError(
# _("You need to submit at least one valid DOI or PMID")
# )
. Output only the next line. | form = EntryBatchImportForm(input) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
class Command(BaseCommand):
help = "Import entries from a BibTex file"
def _get_logger(self):
logger = logging.getLogger("td_biblio")
return logger
def add_arguments(self, parser):
parser.add_argument("bibtex", help="The path to the BibTeX file to import")
def handle(self, *args, **options):
logger = self._get_logger()
bibtex = options.get("bibtex", None)
if bibtex is None:
raise CommandError("A BibTeX file path is required")
logger.info("Importing '{}' BibTeX file...".format(bibtex))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from django.core.management.base import BaseCommand, CommandError
from td_biblio.utils.loaders import BibTeXLoader
and context:
# Path: td_biblio/utils/loaders.py
# class BibTeXLoader(BaseLoader):
# """BibTeXLoader
#
# This loader is designed to import a bibtex file items.
#
# Usage:
#
# >>> from td_biblio.utils.loaders import BibTeXLoader
# >>> loader = BibTeXLoader()
# >>> loader.load_records(bibtex_filename='foo.bib')
# >>> loader.save_records()
# """
#
# def to_record(self, input):
# """Convert a bibtex item to a valid record"""
#
# # Simple fields
# record = input.copy()
#
# # Journal
# record["journal"] = input["journal"]
#
# # Publication date
# pub_date = {"day": 1, "month": 1, "year": 1900}
# input_date = dict((k, v) for (k, v) in input.items() if k in pub_date.keys())
# pub_date.update(input_date)
# # Check if month is numerical or not
# try:
# int(pub_date["month"])
# except ValueError:
# pub_date["month"] = strptime(pub_date["month"], "%b").tm_mon
# # Convert date fields to integers
# pub_date = dict((k, int(v)) for k, v in pub_date.items())
# record["publication_date"] = datetime.date(**pub_date)
#
# record["is_partial_publication_date"] = not all(
# [True if k in input else False for k in pub_date.keys()]
# )
#
# # Authors
# record["authors"] = []
# for author in input["author"]:
# splited = author.split(", ")
# record["authors"].append(
# {"first_name": " ".join(splited[1:]), "last_name": splited[0]}
# )
# return record
#
# def load_records(self, bibtex_filename=None):
# """Load all bibtex items as valid records"""
#
# with open(bibtex_filename) as bibtex_file:
# # Parse BibTex file
# parser = BibTexParser()
# parser.customization = td_biblio_customization
# bp = bibtexparser.load(bibtex_file, parser=parser)
# self.records = [self.to_record(r) for r in bp.get_entry_list()]
which might include code, classes, or functions. Output only the next line. | loader = BibTeXLoader() |
Given snippet: <|code_start|> )
def clean_pmids(self):
"""Transform raw data in a PMID list"""
pmids = text_to_list(self.cleaned_data["pmids"])
for pmid in pmids:
pmid_validator(pmid)
return pmids
def clean_dois(self):
"""Transform raw data in a DOI list"""
dois = text_to_list(self.cleaned_data["dois"])
for doi in dois:
doi_validator(doi)
return dois
def clean(self):
super(EntryBatchImportForm, self).clean()
dois = self.cleaned_data.get("dois", [])
pmids = self.cleaned_data.get("pmids", [])
if not len(dois) and not len(pmids):
raise forms.ValidationError(
_("You need to submit at least one valid DOI or PMID")
)
class AuthorDuplicatesForm(forms.Form):
def get_authors_choices():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from operator import methodcaller
from django import forms
from django.core.validators import RegexValidator
from django.utils.translation import ugettext_lazy as _
from td_biblio.models import Author
and context:
# Path: td_biblio/models.py
# class Author(AbstractHuman):
# """Entry author"""
#
# class Meta:
# ordering = ("last_name", "first_name")
# verbose_name = _("Author")
# verbose_name_plural = _("Authors")
which might include code, classes, or functions. Output only the next line. | return Author.objects.values_list("id", "last_name") |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
try:
except ImportError:
@pytest.mark.django_db
class PublicationDateFilterTests(TestCase):
"""Tests for the publication_date filter"""
def setUp(self):
"""Setup a publication database"""
# Standard entries
for i in range(4):
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import pytest
from django.core.urlresolvers import reverse
from django.urls import reverse
from django.test import TestCase
from ..factories import EntryFactory
and context including class names, function names, and sometimes code from other files:
# Path: td_biblio/factories.py
# class EntryFactory(DjangoModelFactory):
#
# type = factory.fuzzy.FuzzyChoice(ENTRY_TYPES_RAW_CHOICES)
# title = factory.Sequence(lambda n: "Entry title %s" % n)
# journal = factory.SubFactory(JournalFactory)
# publication_date = factory.fuzzy.FuzzyDate(datetime.date(1942, 1, 1))
# volume = factory.fuzzy.FuzzyInteger(1, 10)
# number = factory.fuzzy.FuzzyInteger(1, 50)
# pages = FuzzyPages(1, 2000)
#
# class Meta:
# model = models.Entry
. Output only the next line. | EntryFactory(is_partial_publication_date=False) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
TailorDev Bibliography
Test factories.
"""
@pytest.mark.django_db
class FuzzyPagesTestCase(TestCase):
def test_simple_call(self):
"""Test the Fuzzy pages attribute implicit call"""
entry = EntryFactory()
self.assertNotEqual(len(entry.pages), 0)
def test_only_max_page(self):
"""Test the Fuzzy pages attribute explicit call"""
<|code_end|>
using the current file's imports:
import pytest
from django.test import TestCase
from ..factories import FuzzyPages, EntryFactory
and any relevant context from other files:
# Path: td_biblio/factories.py
# class FuzzyPages(BaseFuzzyAttribute):
# """Random pages numbers separated by double-hyphens"""
#
# def __init__(self, low, high=None, **kwargs):
# if high is None:
# high = low
# low = 1
#
# self.low = low
# self.high = high
#
# super(FuzzyPages, self).__init__(**kwargs)
#
# def fuzz(self):
# start = random.randint(self.low, self.high)
# end = random.randint(start, self.high)
# return "%d--%d" % (start, end)
#
# class EntryFactory(DjangoModelFactory):
#
# type = factory.fuzzy.FuzzyChoice(ENTRY_TYPES_RAW_CHOICES)
# title = factory.Sequence(lambda n: "Entry title %s" % n)
# journal = factory.SubFactory(JournalFactory)
# publication_date = factory.fuzzy.FuzzyDate(datetime.date(1942, 1, 1))
# volume = factory.fuzzy.FuzzyInteger(1, 10)
# number = factory.fuzzy.FuzzyInteger(1, 50)
# pages = FuzzyPages(1, 2000)
#
# class Meta:
# model = models.Entry
. Output only the next line. | entry = EntryFactory(pages=FuzzyPages(1, 10)) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
"""
TailorDev Bibliography
Test factories.
"""
@pytest.mark.django_db
class FuzzyPagesTestCase(TestCase):
def test_simple_call(self):
"""Test the Fuzzy pages attribute implicit call"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from django.test import TestCase
from ..factories import FuzzyPages, EntryFactory
and context:
# Path: td_biblio/factories.py
# class FuzzyPages(BaseFuzzyAttribute):
# """Random pages numbers separated by double-hyphens"""
#
# def __init__(self, low, high=None, **kwargs):
# if high is None:
# high = low
# low = 1
#
# self.low = low
# self.high = high
#
# super(FuzzyPages, self).__init__(**kwargs)
#
# def fuzz(self):
# start = random.randint(self.low, self.high)
# end = random.randint(start, self.high)
# return "%d--%d" % (start, end)
#
# class EntryFactory(DjangoModelFactory):
#
# type = factory.fuzzy.FuzzyChoice(ENTRY_TYPES_RAW_CHOICES)
# title = factory.Sequence(lambda n: "Entry title %s" % n)
# journal = factory.SubFactory(JournalFactory)
# publication_date = factory.fuzzy.FuzzyDate(datetime.date(1942, 1, 1))
# volume = factory.fuzzy.FuzzyInteger(1, 10)
# number = factory.fuzzy.FuzzyInteger(1, 50)
# pages = FuzzyPages(1, 2000)
#
# class Meta:
# model = models.Entry
which might include code, classes, or functions. Output only the next line. | entry = EntryFactory() |
Next line prediction: <|code_start|> self.verticalLayout.setSpacing(1)
self.verticalLayout.setObjectName("verticalLayout")
self.topListEntryLayout = QtWidgets.QHBoxLayout()
self.topListEntryLayout.setSpacing(1)
self.topListEntryLayout.setObjectName("topListEntryLayout")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.topListEntryLayout.addItem(spacerItem)
self.entryAddButton = QtWidgets.QPushButton(listEntryDialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.entryAddButton.sizePolicy().hasHeightForWidth())
self.entryAddButton.setSizePolicy(sizePolicy)
self.entryAddButton.setMinimumSize(QtCore.QSize(25, 25))
self.entryAddButton.setMaximumSize(QtCore.QSize(25, 25))
self.entryAddButton.setAutoDefault(False)
self.entryAddButton.setObjectName("entryAddButton")
self.topListEntryLayout.addWidget(self.entryAddButton)
self.entryDelButton = QtWidgets.QPushButton(listEntryDialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.entryDelButton.sizePolicy().hasHeightForWidth())
self.entryDelButton.setSizePolicy(sizePolicy)
self.entryDelButton.setMinimumSize(QtCore.QSize(25, 25))
self.entryDelButton.setMaximumSize(QtCore.QSize(25, 25))
self.entryDelButton.setAutoDefault(False)
self.entryDelButton.setObjectName("entryDelButton")
self.topListEntryLayout.addWidget(self.entryDelButton)
self.verticalLayout.addLayout(self.topListEntryLayout)
<|code_end|>
. Use current file imports:
(from PyQt5 import QtCore, QtGui, QtWidgets
from lazylyst.CustomWidgets import MixListWidget)
and context including class names, function names, or small code snippets from other files:
# Path: lazylyst/CustomWidgets.py
# class MixListWidget(QtWidgets.QListWidget):
# # Return signal if key was pressed while in focus
# keyPressedSignal=QtCore.pyqtSignal()
# leaveSignal=QtCore.pyqtSignal()
#
# def __init__(self, parent=None):
# super(MixListWidget, self).__init__(parent)
#
# # Update this widgets last pressed key, and return a signal
# def keyPressEvent(self, ev):
# self.key=ev.key()
# if self.key not in [Qt.Key_Insert,Qt.Key_Delete]:
# return
# self.keyPressedSignal.emit()
#
# # Deselect all items if in a blank space
# def mousePressEvent(self, ev):
# if self.itemAt(ev.pos()) is None:
# self.clearSelection()
# QtWidgets.QListWidget.mousePressEvent(self, ev)
#
# # Swapping a double click with the backspace button...
# # ...wanted to transmit double click as a key
# def mouseDoubleClickEvent(self,ev):
# # Only allow left-double clicks
# if ev.button()!=1:
# return
# self.key=Qt.Key_Backspace
# self.keyPressedSignal.emit()
#
# # Ensure that key presses are sent to the widget which the mouse is hovering over
# def enterEvent(self,ev):
# super(MixListWidget, self).enterEvent(ev)
# self.setFocus()
#
# # If ever the list if left by the mouse, emit (used to trigger ordering of passive functions)
# def leaveEvent(self,ev):
# self.leaveSignal.emit()
#
# # Return the lists entries in the order which it appears
# def visualListOrder(self):
# txt=np.array([self.item(i).text() for i in range(self.count())])
# args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())])
# return list(txt[np.argsort(args)])
. Output only the next line. | self.entryListWidget = MixListWidget(listEntryDialog) |
Continue the code snippet: <|code_start|> font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.actIntervalLabel.setFont(font)
self.actIntervalLabel.setAlignment(QtCore.Qt.AlignCenter)
self.actIntervalLabel.setObjectName("actIntervalLabel")
self.actShortInputLayout.addWidget(self.actIntervalLabel, 4, 3, 1, 1)
self.actActiveRadio = QtWidgets.QRadioButton(actionDialog)
self.actActiveRadio.setObjectName("actActiveRadio")
self.actShortInputLayout.addWidget(self.actActiveRadio, 0, 3, 1, 1)
self.actNameLineEdit = QtWidgets.QLineEdit(actionDialog)
self.actNameLineEdit.setObjectName("actNameLineEdit")
self.actShortInputLayout.addWidget(self.actNameLineEdit, 2, 2, 1, 1)
self.passiveBeforeCheck = QtWidgets.QCheckBox(actionDialog)
self.passiveBeforeCheck.setObjectName("passiveBeforeCheck")
self.actShortInputLayout.addWidget(self.passiveBeforeCheck, 6, 4, 1, 1)
self.actPathLabel = QtWidgets.QLabel(actionDialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.actPathLabel.sizePolicy().hasHeightForWidth())
self.actPathLabel.setSizePolicy(sizePolicy)
self.actPathLabel.setMaximumSize(QtCore.QSize(16777215, 16777215))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.actPathLabel.setFont(font)
self.actPathLabel.setAlignment(QtCore.Qt.AlignCenter)
self.actPathLabel.setObjectName("actPathLabel")
self.actShortInputLayout.addWidget(self.actPathLabel, 4, 1, 1, 1)
<|code_end|>
. Use current file imports:
from PyQt5 import QtCore, QtGui, QtWidgets
from lazylyst.CustomWidgets import HoverLineEdit, KeyBindLineEdit, KeyListWidget
and context (classes, functions, or code) from other files:
# Path: lazylyst/CustomWidgets.py
# class HoverLineEdit(QtWidgets.QLineEdit):
# hoverOut = QtCore.pyqtSignal()
#
# def __init__(self, parent=None):
# super(HoverLineEdit, self).__init__(parent)
# self.changeState=False
# self.textChanged.connect(self.updateChangeState)
#
# def leaveEvent(self, ev):
# # Only emit if the text was changed
# if self.changeState:
# self.hoverOut.emit()
# self.changeState=False
#
# def updateChangeState(self,ev):
# self.changeState=True
#
# class KeyBindLineEdit(QtWidgets.QLineEdit):
# keyPressed=QtCore.pyqtSignal(str)
#
# def __init__(self, parent=None):
# super(KeyBindLineEdit, self).__init__(parent)
# self.MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META)
#
# # If any usual key bind was pressed, return the human recognizable string
# def keyPressEvent(self, ev):
# keyname = keyPressToString(ev)
# if keyname==None:
# return
# self.keyPressed.emit(keyname)
#
# class KeyListWidget(QtWidgets.QListWidget):
# # Return signal if key was pressed while in focus
# keyPressedSignal = QtCore.pyqtSignal()
#
# def __init__(self, parent=None):
# super(KeyListWidget, self).__init__(parent)
#
# # Update this widgets last pressed key, and return a signal
# def keyPressEvent(self, ev):
# self.key=ev.key()
# if self.key not in [Qt.Key_Delete]:
# return
# self.keyPressedSignal.emit()
#
# # Deselect all items if in a blank space
# def mousePressEvent(self, ev):
# if self.itemAt(ev.pos()) is None:
# self.clearSelection()
# QtWidgets.QListWidget.mousePressEvent(self, ev)
#
# # Ensure that key presses are sent to the widget which the mouse is hovering over
# def enterEvent(self,ev):
# super(KeyListWidget, self).enterEvent(ev)
# self.setFocus()
#
# # Return a lists entries in the order which is appears
# def visualListOrder(self):
# txt=np.array([self.item(i).text() for i in range(self.count())])
# args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())])
# return list(txt[np.argsort(args)])
. Output only the next line. | self.actTagLineEdit = HoverLineEdit(actionDialog) |
Given the following code snippet before the placeholder: <|code_start|># Form implementation generated from reading ui file 'ActionSetup.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
class Ui_actionDialog(object):
def setupUi(self, actionDialog):
actionDialog.setObjectName("actionDialog")
actionDialog.resize(626, 626)
self.verticalLayout = QtWidgets.QVBoxLayout(actionDialog)
self.verticalLayout.setObjectName("verticalLayout")
self.actShortInputLayout = QtWidgets.QGridLayout()
self.actShortInputLayout.setSpacing(1)
self.actShortInputLayout.setObjectName("actShortInputLayout")
self.actOptionalsLabel = QtWidgets.QLabel(actionDialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.actOptionalsLabel.sizePolicy().hasHeightForWidth())
self.actOptionalsLabel.setSizePolicy(sizePolicy)
self.actOptionalsLabel.setMaximumSize(QtCore.QSize(16777215, 16777215))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.actOptionalsLabel.setFont(font)
self.actOptionalsLabel.setAlignment(QtCore.Qt.AlignCenter)
self.actOptionalsLabel.setObjectName("actOptionalsLabel")
self.actShortInputLayout.addWidget(self.actOptionalsLabel, 6, 1, 1, 1)
<|code_end|>
, predict the next line using imports from the current file:
from PyQt5 import QtCore, QtGui, QtWidgets
from lazylyst.CustomWidgets import HoverLineEdit, KeyBindLineEdit, KeyListWidget
and context including class names, function names, and sometimes code from other files:
# Path: lazylyst/CustomWidgets.py
# class HoverLineEdit(QtWidgets.QLineEdit):
# hoverOut = QtCore.pyqtSignal()
#
# def __init__(self, parent=None):
# super(HoverLineEdit, self).__init__(parent)
# self.changeState=False
# self.textChanged.connect(self.updateChangeState)
#
# def leaveEvent(self, ev):
# # Only emit if the text was changed
# if self.changeState:
# self.hoverOut.emit()
# self.changeState=False
#
# def updateChangeState(self,ev):
# self.changeState=True
#
# class KeyBindLineEdit(QtWidgets.QLineEdit):
# keyPressed=QtCore.pyqtSignal(str)
#
# def __init__(self, parent=None):
# super(KeyBindLineEdit, self).__init__(parent)
# self.MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META)
#
# # If any usual key bind was pressed, return the human recognizable string
# def keyPressEvent(self, ev):
# keyname = keyPressToString(ev)
# if keyname==None:
# return
# self.keyPressed.emit(keyname)
#
# class KeyListWidget(QtWidgets.QListWidget):
# # Return signal if key was pressed while in focus
# keyPressedSignal = QtCore.pyqtSignal()
#
# def __init__(self, parent=None):
# super(KeyListWidget, self).__init__(parent)
#
# # Update this widgets last pressed key, and return a signal
# def keyPressEvent(self, ev):
# self.key=ev.key()
# if self.key not in [Qt.Key_Delete]:
# return
# self.keyPressedSignal.emit()
#
# # Deselect all items if in a blank space
# def mousePressEvent(self, ev):
# if self.itemAt(ev.pos()) is None:
# self.clearSelection()
# QtWidgets.QListWidget.mousePressEvent(self, ev)
#
# # Ensure that key presses are sent to the widget which the mouse is hovering over
# def enterEvent(self,ev):
# super(KeyListWidget, self).enterEvent(ev)
# self.setFocus()
#
# # Return a lists entries in the order which is appears
# def visualListOrder(self):
# txt=np.array([self.item(i).text() for i in range(self.count())])
# args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())])
# return list(txt[np.argsort(args)])
. Output only the next line. | self.actTriggerLineEdit = KeyBindLineEdit(actionDialog) |
Next line prediction: <|code_start|> self.actPathLineEdit.setObjectName("actPathLineEdit")
self.actShortInputLayout.addWidget(self.actPathLineEdit, 4, 2, 1, 1)
self.actTriggerLabel = QtWidgets.QLabel(actionDialog)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.actTriggerLabel.setFont(font)
self.actTriggerLabel.setAlignment(QtCore.Qt.AlignCenter)
self.actTriggerLabel.setObjectName("actTriggerLabel")
self.actShortInputLayout.addWidget(self.actTriggerLabel, 2, 3, 1, 1)
self.actIntervalLineEdit = QtWidgets.QLineEdit(actionDialog)
self.actIntervalLineEdit.setObjectName("actIntervalLineEdit")
self.actShortInputLayout.addWidget(self.actIntervalLineEdit, 4, 4, 1, 1)
self.actActiveCheckLayout = QtWidgets.QHBoxLayout()
self.actActiveCheckLayout.setObjectName("actActiveCheckLayout")
self.activeTimerCheck = QtWidgets.QCheckBox(actionDialog)
self.activeTimerCheck.setObjectName("activeTimerCheck")
self.actActiveCheckLayout.addWidget(self.activeTimerCheck)
self.activeThreadedCheck = QtWidgets.QCheckBox(actionDialog)
self.activeThreadedCheck.setObjectName("activeThreadedCheck")
self.actActiveCheckLayout.addWidget(self.activeThreadedCheck)
self.actShortInputLayout.addLayout(self.actActiveCheckLayout, 0, 4, 1, 1)
self.actShortInputLayout.setColumnStretch(1, 1)
self.actShortInputLayout.setColumnStretch(2, 7)
self.actShortInputLayout.setColumnStretch(3, 1)
self.actShortInputLayout.setColumnStretch(4, 1)
self.verticalLayout.addLayout(self.actShortInputLayout)
self.actReturnLayout = QtWidgets.QGridLayout()
self.actReturnLayout.setSpacing(1)
self.actReturnLayout.setObjectName("actReturnLayout")
<|code_end|>
. Use current file imports:
(from PyQt5 import QtCore, QtGui, QtWidgets
from lazylyst.CustomWidgets import HoverLineEdit, KeyBindLineEdit, KeyListWidget)
and context including class names, function names, or small code snippets from other files:
# Path: lazylyst/CustomWidgets.py
# class HoverLineEdit(QtWidgets.QLineEdit):
# hoverOut = QtCore.pyqtSignal()
#
# def __init__(self, parent=None):
# super(HoverLineEdit, self).__init__(parent)
# self.changeState=False
# self.textChanged.connect(self.updateChangeState)
#
# def leaveEvent(self, ev):
# # Only emit if the text was changed
# if self.changeState:
# self.hoverOut.emit()
# self.changeState=False
#
# def updateChangeState(self,ev):
# self.changeState=True
#
# class KeyBindLineEdit(QtWidgets.QLineEdit):
# keyPressed=QtCore.pyqtSignal(str)
#
# def __init__(self, parent=None):
# super(KeyBindLineEdit, self).__init__(parent)
# self.MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META)
#
# # If any usual key bind was pressed, return the human recognizable string
# def keyPressEvent(self, ev):
# keyname = keyPressToString(ev)
# if keyname==None:
# return
# self.keyPressed.emit(keyname)
#
# class KeyListWidget(QtWidgets.QListWidget):
# # Return signal if key was pressed while in focus
# keyPressedSignal = QtCore.pyqtSignal()
#
# def __init__(self, parent=None):
# super(KeyListWidget, self).__init__(parent)
#
# # Update this widgets last pressed key, and return a signal
# def keyPressEvent(self, ev):
# self.key=ev.key()
# if self.key not in [Qt.Key_Delete]:
# return
# self.keyPressedSignal.emit()
#
# # Deselect all items if in a blank space
# def mousePressEvent(self, ev):
# if self.itemAt(ev.pos()) is None:
# self.clearSelection()
# QtWidgets.QListWidget.mousePressEvent(self, ev)
#
# # Ensure that key presses are sent to the widget which the mouse is hovering over
# def enterEvent(self,ev):
# super(KeyListWidget, self).enterEvent(ev)
# self.setFocus()
#
# # Return a lists entries in the order which is appears
# def visualListOrder(self):
# txt=np.array([self.item(i).text() for i in range(self.count())])
# args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())])
# return list(txt[np.argsort(args)])
. Output only the next line. | self.actSelectInputList = KeyListWidget(actionDialog) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MapProj.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
class Ui_mapProjDialog(object):
def setupUi(self, mapProjDialog):
mapProjDialog.setObjectName("mapProjDialog")
mapProjDialog.resize(260, 131)
self.verticalLayout = QtWidgets.QVBoxLayout(mapProjDialog)
self.verticalLayout.setSpacing(1)
self.verticalLayout.setObjectName("verticalLayout")
self.upperProjLayout = QtWidgets.QGridLayout()
self.upperProjLayout.setSpacing(1)
self.upperProjLayout.setObjectName("upperProjLayout")
self.simpleProjComboBox = QtWidgets.QComboBox(mapProjDialog)
self.simpleProjComboBox.setObjectName("simpleProjComboBox")
self.upperProjLayout.addWidget(self.simpleProjComboBox, 0, 1, 1, 1)
self.simpleProjRadio = QtWidgets.QRadioButton(mapProjDialog)
self.simpleProjRadio.setObjectName("simpleProjRadio")
self.upperProjLayout.addWidget(self.simpleProjRadio, 0, 0, 1, 1)
self.customProjRadio = QtWidgets.QRadioButton(mapProjDialog)
self.customProjRadio.setObjectName("customProjRadio")
self.upperProjLayout.addWidget(self.customProjRadio, 1, 0, 1, 1)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from PyQt5 import QtCore, QtGui, QtWidgets
from lazylyst.CustomWidgets import HoverLineEdit
and context:
# Path: lazylyst/CustomWidgets.py
# class HoverLineEdit(QtWidgets.QLineEdit):
# hoverOut = QtCore.pyqtSignal()
#
# def __init__(self, parent=None):
# super(HoverLineEdit, self).__init__(parent)
# self.changeState=False
# self.textChanged.connect(self.updateChangeState)
#
# def leaveEvent(self, ev):
# # Only emit if the text was changed
# if self.changeState:
# self.hoverOut.emit()
# self.changeState=False
#
# def updateChangeState(self,ev):
# self.changeState=True
which might include code, classes, or functions. Output only the next line. | self.epsgLineEdit = HoverLineEdit(mapProjDialog) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Configuration.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
class Ui_ConfDialog(object):
def setupUi(self, ConfDialog):
ConfDialog.setObjectName("ConfDialog")
ConfDialog.resize(695, 449)
self.horizontalLayout = QtWidgets.QHBoxLayout(ConfDialog)
self.horizontalLayout.setObjectName("horizontalLayout")
self.confPrefLayout = QtWidgets.QVBoxLayout()
self.confPrefLayout.setSpacing(1)
self.confPrefLayout.setObjectName("confPrefLayout")
self.confPrefLabel = QtWidgets.QLabel(ConfDialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.confPrefLabel.sizePolicy().hasHeightForWidth())
self.confPrefLabel.setSizePolicy(sizePolicy)
self.confPrefLabel.setMinimumSize(QtCore.QSize(0, 25))
self.confPrefLabel.setMaximumSize(QtCore.QSize(16777215, 25))
self.confPrefLabel.setLayoutDirection(QtCore.Qt.LeftToRight)
self.confPrefLabel.setAlignment(QtCore.Qt.AlignCenter)
self.confPrefLabel.setObjectName("confPrefLabel")
self.confPrefLayout.addWidget(self.confPrefLabel)
<|code_end|>
with the help of current file imports:
from PyQt5 import QtCore, QtGui, QtWidgets
from lazylyst.CustomWidgets import MixListWidget
and context from other files:
# Path: lazylyst/CustomWidgets.py
# class MixListWidget(QtWidgets.QListWidget):
# # Return signal if key was pressed while in focus
# keyPressedSignal=QtCore.pyqtSignal()
# leaveSignal=QtCore.pyqtSignal()
#
# def __init__(self, parent=None):
# super(MixListWidget, self).__init__(parent)
#
# # Update this widgets last pressed key, and return a signal
# def keyPressEvent(self, ev):
# self.key=ev.key()
# if self.key not in [Qt.Key_Insert,Qt.Key_Delete]:
# return
# self.keyPressedSignal.emit()
#
# # Deselect all items if in a blank space
# def mousePressEvent(self, ev):
# if self.itemAt(ev.pos()) is None:
# self.clearSelection()
# QtWidgets.QListWidget.mousePressEvent(self, ev)
#
# # Swapping a double click with the backspace button...
# # ...wanted to transmit double click as a key
# def mouseDoubleClickEvent(self,ev):
# # Only allow left-double clicks
# if ev.button()!=1:
# return
# self.key=Qt.Key_Backspace
# self.keyPressedSignal.emit()
#
# # Ensure that key presses are sent to the widget which the mouse is hovering over
# def enterEvent(self,ev):
# super(MixListWidget, self).enterEvent(ev)
# self.setFocus()
#
# # If ever the list if left by the mouse, emit (used to trigger ordering of passive functions)
# def leaveEvent(self,ev):
# self.leaveSignal.emit()
#
# # Return the lists entries in the order which it appears
# def visualListOrder(self):
# txt=np.array([self.item(i).text() for i in range(self.count())])
# args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())])
# return list(txt[np.argsort(args)])
, which may contain function names, class names, or code. Output only the next line. | self.confPrefList = MixListWidget(ConfDialog) |
Next line prediction: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class UserViewSet(viewsets.ViewSet):
permission_classes = [AllowAny, ]
"""
A simple ViewSet that for listing or retrieving users.
user_list = UserViewSet.as_view({
'get': 'list',
'post': 'create'
})
user_detail = UserViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
"""
def list(self, request):
"""
Lists all users in the system
---
"""
<|code_end|>
. Use current file imports:
(from ..models import User
from ..serializers import UserSerializer
from ..views import send_response
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from django.http import HttpResponse)
and context including class names, function names, or small code snippets from other files:
# Path: cognitive/app/models.py
# class User(models.Model):
# username = models.CharField(max_length=50)
# full_name = models.CharField(max_length=50)
# email = models.CharField(max_length=100)
# password = models.CharField(max_length=100)
# token = models.CharField(max_length=100, blank=True, null=True)
# max_experiments = models.IntegerField(default=50)
#
# def __str__(self):
# return self.username
#
# @classmethod
# def authenticate(cls, username_or_email, password):
# try:
# user = User.objects.get(username=username_or_email)
# except:
# try:
# user = User.objects.get(email=username_or_email)
# except:
# return None
# if not user.confirm_password(password):
# return None
# return user
#
# @classmethod
# def validate(cls, username, email, password):
# err_msg = ""
# if not username:
# err_msg = "Empty username field"
# raise ValidationError(err_msg)
# if not password:
# err_msg = "Empty password field"
# raise ValidationError(err_msg)
# if not email:
# err_msg = "Empty email field"
# raise ValidationError(err_msg)
# validate_email(email)
# if User.objects.filter(username=username).count() > 0:
# err_msg = "Username already exists"
# raise ValidationError(err_msg)
# if User.objects.filter(email=email).count() > 0:
# err_msg = "Email already exists"
# raise ValidationError(err_msg)
# return True
#
# def confirm_password(self, password):
# # TODO: password must be encrypted
# if self.password == password:
# return True
# else:
# return False
#
# # TODO: password encryption
#
# @classmethod
# def generate_token(cls):
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# return ''.join(random.choice(chars) for _ in range(size))
# return id_generator()
#
# def has_correct_token(self, token):
# return self.token == token
#
# Path: cognitive/app/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = User
# # fields = ['id','username','full_name']
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | user = User.objects.all() |
Continue the code snippet: <|code_start|># 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 UserViewSet(viewsets.ViewSet):
permission_classes = [AllowAny, ]
"""
A simple ViewSet that for listing or retrieving users.
user_list = UserViewSet.as_view({
'get': 'list',
'post': 'create'
})
user_detail = UserViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
"""
def list(self, request):
"""
Lists all users in the system
---
"""
user = User.objects.all()
<|code_end|>
. Use current file imports:
from ..models import User
from ..serializers import UserSerializer
from ..views import send_response
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from django.http import HttpResponse
and context (classes, functions, or code) from other files:
# Path: cognitive/app/models.py
# class User(models.Model):
# username = models.CharField(max_length=50)
# full_name = models.CharField(max_length=50)
# email = models.CharField(max_length=100)
# password = models.CharField(max_length=100)
# token = models.CharField(max_length=100, blank=True, null=True)
# max_experiments = models.IntegerField(default=50)
#
# def __str__(self):
# return self.username
#
# @classmethod
# def authenticate(cls, username_or_email, password):
# try:
# user = User.objects.get(username=username_or_email)
# except:
# try:
# user = User.objects.get(email=username_or_email)
# except:
# return None
# if not user.confirm_password(password):
# return None
# return user
#
# @classmethod
# def validate(cls, username, email, password):
# err_msg = ""
# if not username:
# err_msg = "Empty username field"
# raise ValidationError(err_msg)
# if not password:
# err_msg = "Empty password field"
# raise ValidationError(err_msg)
# if not email:
# err_msg = "Empty email field"
# raise ValidationError(err_msg)
# validate_email(email)
# if User.objects.filter(username=username).count() > 0:
# err_msg = "Username already exists"
# raise ValidationError(err_msg)
# if User.objects.filter(email=email).count() > 0:
# err_msg = "Email already exists"
# raise ValidationError(err_msg)
# return True
#
# def confirm_password(self, password):
# # TODO: password must be encrypted
# if self.password == password:
# return True
# else:
# return False
#
# # TODO: password encryption
#
# @classmethod
# def generate_token(cls):
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# return ''.join(random.choice(chars) for _ in range(size))
# return id_generator()
#
# def has_correct_token(self, token):
# return self.token == token
#
# Path: cognitive/app/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = User
# # fields = ['id','username','full_name']
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | serializer = UserSerializer(user, many=True) |
Given the code snippet: <|code_start|># License for the specific language governing permissions and limitations
# under the License.
class UserViewSet(viewsets.ViewSet):
permission_classes = [AllowAny, ]
"""
A simple ViewSet that for listing or retrieving users.
user_list = UserViewSet.as_view({
'get': 'list',
'post': 'create'
})
user_detail = UserViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
"""
def list(self, request):
"""
Lists all users in the system
---
"""
user = User.objects.all()
serializer = UserSerializer(user, many=True)
<|code_end|>
, generate the next line using the imports in this file:
from ..models import User
from ..serializers import UserSerializer
from ..views import send_response
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from django.http import HttpResponse
and context (functions, classes, or occasionally code) from other files:
# Path: cognitive/app/models.py
# class User(models.Model):
# username = models.CharField(max_length=50)
# full_name = models.CharField(max_length=50)
# email = models.CharField(max_length=100)
# password = models.CharField(max_length=100)
# token = models.CharField(max_length=100, blank=True, null=True)
# max_experiments = models.IntegerField(default=50)
#
# def __str__(self):
# return self.username
#
# @classmethod
# def authenticate(cls, username_or_email, password):
# try:
# user = User.objects.get(username=username_or_email)
# except:
# try:
# user = User.objects.get(email=username_or_email)
# except:
# return None
# if not user.confirm_password(password):
# return None
# return user
#
# @classmethod
# def validate(cls, username, email, password):
# err_msg = ""
# if not username:
# err_msg = "Empty username field"
# raise ValidationError(err_msg)
# if not password:
# err_msg = "Empty password field"
# raise ValidationError(err_msg)
# if not email:
# err_msg = "Empty email field"
# raise ValidationError(err_msg)
# validate_email(email)
# if User.objects.filter(username=username).count() > 0:
# err_msg = "Username already exists"
# raise ValidationError(err_msg)
# if User.objects.filter(email=email).count() > 0:
# err_msg = "Email already exists"
# raise ValidationError(err_msg)
# return True
#
# def confirm_password(self, password):
# # TODO: password must be encrypted
# if self.password == password:
# return True
# else:
# return False
#
# # TODO: password encryption
#
# @classmethod
# def generate_token(cls):
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# return ''.join(random.choice(chars) for _ in range(size))
# return id_generator()
#
# def has_correct_token(self, token):
# return self.token == token
#
# Path: cognitive/app/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = User
# # fields = ['id','username','full_name']
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | return send_response(request.method, serializer) |
Using 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.
PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
FILE_UPLOAD_DIR = os.path.join(PROJECT_PATH, 'cognitive/app/uploads/')
def handle_uploaded_file(f):
file_dir = os.path.join(FILE_UPLOAD_DIR, str(f))
with open(file_dir, 'w+') as dest:
for chunk in f.chunks():
dest.write(chunk)
class DataViewSet(viewsets.ViewSet):
# This API endpoint needs to be modified for enabling directly
# upload any kind of data without requiring hard work on frontend
def list(self, request):
"""
Lists all experiments for a particular user
---
"""
<|code_end|>
, determine the next line of code. You have imports:
import os.path
from datetime import datetime
from ..models import Data, User
from ..serializers import DataSerializer
from ..views import send_response
from rest_framework import viewsets
and context (class names, function names, or code) available:
# Path: cognitive/app/models.py
# class Data(models.Model):
# user = models.ForeignKey(User)
# type = models.CharField(blank=False, null=False, max_length=50)
# file_path = models.CharField(blank=True, null=True, max_length=50)
# columns = models.CharField(blank=True, null=True, max_length=1024)
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ('-created_time',)
#
# class User(models.Model):
# username = models.CharField(max_length=50)
# full_name = models.CharField(max_length=50)
# email = models.CharField(max_length=100)
# password = models.CharField(max_length=100)
# token = models.CharField(max_length=100, blank=True, null=True)
# max_experiments = models.IntegerField(default=50)
#
# def __str__(self):
# return self.username
#
# @classmethod
# def authenticate(cls, username_or_email, password):
# try:
# user = User.objects.get(username=username_or_email)
# except:
# try:
# user = User.objects.get(email=username_or_email)
# except:
# return None
# if not user.confirm_password(password):
# return None
# return user
#
# @classmethod
# def validate(cls, username, email, password):
# err_msg = ""
# if not username:
# err_msg = "Empty username field"
# raise ValidationError(err_msg)
# if not password:
# err_msg = "Empty password field"
# raise ValidationError(err_msg)
# if not email:
# err_msg = "Empty email field"
# raise ValidationError(err_msg)
# validate_email(email)
# if User.objects.filter(username=username).count() > 0:
# err_msg = "Username already exists"
# raise ValidationError(err_msg)
# if User.objects.filter(email=email).count() > 0:
# err_msg = "Email already exists"
# raise ValidationError(err_msg)
# return True
#
# def confirm_password(self, password):
# # TODO: password must be encrypted
# if self.password == password:
# return True
# else:
# return False
#
# # TODO: password encryption
#
# @classmethod
# def generate_token(cls):
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# return ''.join(random.choice(chars) for _ in range(size))
# return id_generator()
#
# def has_correct_token(self, token):
# return self.token == token
#
# Path: cognitive/app/serializers.py
# class DataSerializer(serializers.ModelSerializer):
# class Meta:
# model = Data
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | data = Data.objects.all() |
Given snippet: <|code_start|> # This API endpoint needs to be modified for enabling directly
# upload any kind of data without requiring hard work on frontend
def list(self, request):
"""
Lists all experiments for a particular user
---
"""
data = Data.objects.all()
serializer = DataSerializer(data, many=True)
return send_response(request.method, serializer)
def retrieve(self, request, pk=None):
"""
Retrieve an experiment for a particular user
---
"""
data = Data.objects.get(pk=pk)
serializer = DataSerializer(data)
return send_response(request.method, serializer)
def create(self, request):
upload_file = request.FILES['file']
first_line = upload_file.readline().rstrip('\r\n')
handle_uploaded_file(upload_file)
data = request.data
data_model = Data(
type="csv",
file_path=str(upload_file),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os.path
from datetime import datetime
from ..models import Data, User
from ..serializers import DataSerializer
from ..views import send_response
from rest_framework import viewsets
and context:
# Path: cognitive/app/models.py
# class Data(models.Model):
# user = models.ForeignKey(User)
# type = models.CharField(blank=False, null=False, max_length=50)
# file_path = models.CharField(blank=True, null=True, max_length=50)
# columns = models.CharField(blank=True, null=True, max_length=1024)
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ('-created_time',)
#
# class User(models.Model):
# username = models.CharField(max_length=50)
# full_name = models.CharField(max_length=50)
# email = models.CharField(max_length=100)
# password = models.CharField(max_length=100)
# token = models.CharField(max_length=100, blank=True, null=True)
# max_experiments = models.IntegerField(default=50)
#
# def __str__(self):
# return self.username
#
# @classmethod
# def authenticate(cls, username_or_email, password):
# try:
# user = User.objects.get(username=username_or_email)
# except:
# try:
# user = User.objects.get(email=username_or_email)
# except:
# return None
# if not user.confirm_password(password):
# return None
# return user
#
# @classmethod
# def validate(cls, username, email, password):
# err_msg = ""
# if not username:
# err_msg = "Empty username field"
# raise ValidationError(err_msg)
# if not password:
# err_msg = "Empty password field"
# raise ValidationError(err_msg)
# if not email:
# err_msg = "Empty email field"
# raise ValidationError(err_msg)
# validate_email(email)
# if User.objects.filter(username=username).count() > 0:
# err_msg = "Username already exists"
# raise ValidationError(err_msg)
# if User.objects.filter(email=email).count() > 0:
# err_msg = "Email already exists"
# raise ValidationError(err_msg)
# return True
#
# def confirm_password(self, password):
# # TODO: password must be encrypted
# if self.password == password:
# return True
# else:
# return False
#
# # TODO: password encryption
#
# @classmethod
# def generate_token(cls):
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# return ''.join(random.choice(chars) for _ in range(size))
# return id_generator()
#
# def has_correct_token(self, token):
# return self.token == token
#
# Path: cognitive/app/serializers.py
# class DataSerializer(serializers.ModelSerializer):
# class Meta:
# model = Data
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
which might include code, classes, or functions. Output only the next line. | user=User.objects.get(pk=int(data["user_id"])), |
Given the following code snippet before the placeholder: <|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.
PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
FILE_UPLOAD_DIR = os.path.join(PROJECT_PATH, 'cognitive/app/uploads/')
def handle_uploaded_file(f):
file_dir = os.path.join(FILE_UPLOAD_DIR, str(f))
with open(file_dir, 'w+') as dest:
for chunk in f.chunks():
dest.write(chunk)
class DataViewSet(viewsets.ViewSet):
# This API endpoint needs to be modified for enabling directly
# upload any kind of data without requiring hard work on frontend
def list(self, request):
"""
Lists all experiments for a particular user
---
"""
data = Data.objects.all()
<|code_end|>
, predict the next line using imports from the current file:
import os.path
from datetime import datetime
from ..models import Data, User
from ..serializers import DataSerializer
from ..views import send_response
from rest_framework import viewsets
and context including class names, function names, and sometimes code from other files:
# Path: cognitive/app/models.py
# class Data(models.Model):
# user = models.ForeignKey(User)
# type = models.CharField(blank=False, null=False, max_length=50)
# file_path = models.CharField(blank=True, null=True, max_length=50)
# columns = models.CharField(blank=True, null=True, max_length=1024)
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ('-created_time',)
#
# class User(models.Model):
# username = models.CharField(max_length=50)
# full_name = models.CharField(max_length=50)
# email = models.CharField(max_length=100)
# password = models.CharField(max_length=100)
# token = models.CharField(max_length=100, blank=True, null=True)
# max_experiments = models.IntegerField(default=50)
#
# def __str__(self):
# return self.username
#
# @classmethod
# def authenticate(cls, username_or_email, password):
# try:
# user = User.objects.get(username=username_or_email)
# except:
# try:
# user = User.objects.get(email=username_or_email)
# except:
# return None
# if not user.confirm_password(password):
# return None
# return user
#
# @classmethod
# def validate(cls, username, email, password):
# err_msg = ""
# if not username:
# err_msg = "Empty username field"
# raise ValidationError(err_msg)
# if not password:
# err_msg = "Empty password field"
# raise ValidationError(err_msg)
# if not email:
# err_msg = "Empty email field"
# raise ValidationError(err_msg)
# validate_email(email)
# if User.objects.filter(username=username).count() > 0:
# err_msg = "Username already exists"
# raise ValidationError(err_msg)
# if User.objects.filter(email=email).count() > 0:
# err_msg = "Email already exists"
# raise ValidationError(err_msg)
# return True
#
# def confirm_password(self, password):
# # TODO: password must be encrypted
# if self.password == password:
# return True
# else:
# return False
#
# # TODO: password encryption
#
# @classmethod
# def generate_token(cls):
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# return ''.join(random.choice(chars) for _ in range(size))
# return id_generator()
#
# def has_correct_token(self, token):
# return self.token == token
#
# Path: cognitive/app/serializers.py
# class DataSerializer(serializers.ModelSerializer):
# class Meta:
# model = Data
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | serializer = DataSerializer(data, many=True) |
Given snippet: <|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.
PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
FILE_UPLOAD_DIR = os.path.join(PROJECT_PATH, 'cognitive/app/uploads/')
def handle_uploaded_file(f):
file_dir = os.path.join(FILE_UPLOAD_DIR, str(f))
with open(file_dir, 'w+') as dest:
for chunk in f.chunks():
dest.write(chunk)
class DataViewSet(viewsets.ViewSet):
# This API endpoint needs to be modified for enabling directly
# upload any kind of data without requiring hard work on frontend
def list(self, request):
"""
Lists all experiments for a particular user
---
"""
data = Data.objects.all()
serializer = DataSerializer(data, many=True)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os.path
from datetime import datetime
from ..models import Data, User
from ..serializers import DataSerializer
from ..views import send_response
from rest_framework import viewsets
and context:
# Path: cognitive/app/models.py
# class Data(models.Model):
# user = models.ForeignKey(User)
# type = models.CharField(blank=False, null=False, max_length=50)
# file_path = models.CharField(blank=True, null=True, max_length=50)
# columns = models.CharField(blank=True, null=True, max_length=1024)
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ('-created_time',)
#
# class User(models.Model):
# username = models.CharField(max_length=50)
# full_name = models.CharField(max_length=50)
# email = models.CharField(max_length=100)
# password = models.CharField(max_length=100)
# token = models.CharField(max_length=100, blank=True, null=True)
# max_experiments = models.IntegerField(default=50)
#
# def __str__(self):
# return self.username
#
# @classmethod
# def authenticate(cls, username_or_email, password):
# try:
# user = User.objects.get(username=username_or_email)
# except:
# try:
# user = User.objects.get(email=username_or_email)
# except:
# return None
# if not user.confirm_password(password):
# return None
# return user
#
# @classmethod
# def validate(cls, username, email, password):
# err_msg = ""
# if not username:
# err_msg = "Empty username field"
# raise ValidationError(err_msg)
# if not password:
# err_msg = "Empty password field"
# raise ValidationError(err_msg)
# if not email:
# err_msg = "Empty email field"
# raise ValidationError(err_msg)
# validate_email(email)
# if User.objects.filter(username=username).count() > 0:
# err_msg = "Username already exists"
# raise ValidationError(err_msg)
# if User.objects.filter(email=email).count() > 0:
# err_msg = "Email already exists"
# raise ValidationError(err_msg)
# return True
#
# def confirm_password(self, password):
# # TODO: password must be encrypted
# if self.password == password:
# return True
# else:
# return False
#
# # TODO: password encryption
#
# @classmethod
# def generate_token(cls):
# def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
# return ''.join(random.choice(chars) for _ in range(size))
# return id_generator()
#
# def has_correct_token(self, token):
# return self.token == token
#
# Path: cognitive/app/serializers.py
# class DataSerializer(serializers.ModelSerializer):
# class Meta:
# model = Data
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
which might include code, classes, or functions. Output only the next line. | return send_response(request.method, serializer) |
Based on the snippet: <|code_start|># 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.
# TODO: [refactor] this import statement should specify needed file instead of '*'
CACHE = {}
class myThread(threading.Thread):
def __init__(self, thread_id, name, experiment, component_id, max_results, cache_results):
threading.Thread.__init__(self)
self.threadID = thread_id
self.name = name
self.experiment = experiment
self.comp_id = component_id
self.result = {}
self.max_results = max_results
self.cache_results = cache_results
def run(self):
print "Run called for thread name", self.name, "End component", self.comp_id
<|code_end|>
, predict the immediate next line with the help of imports:
from ..models import Experiment, Component
from toposort import toposort_flatten
from ..ml_models import Classifier
from rest_framework import viewsets
from django.http import HttpResponse
from collections import Counter
from pandas import *
import threading
import json
and context (classes, functions, sometimes code) from other files:
# Path: cognitive/app/models.py
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# class Component(models.Model):
# COMPONENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
#
# experiment = models.ForeignKey(Experiment)
# status = models.CharField(max_length=50, choices=COMPONENT_STATUS, default='Stop')
# operation_type = models.OneToOneField(DataOperationType, blank=True, null=True)
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# data_location = models.CharField(max_length=50, blank=True, null=True)
# preferred_data_location = models.CharField(max_length=50, blank=True, null=True)
# # component_id = models.IntegerField(blank=True, null=True)
#
# Path: cognitive/app/ml_models.py
# class Classifier:
# def __init__(self, input_data, classifier_type, train_data_percentage, input_features, target_feature):
# self.input_data = input_data
# self.train_data_percentage = train_data_percentage
# self.target_feature = target_feature
# self.input_features = input_features
# self.parallel_jobs = 1
# if classifier_type == 'Linear_SVM':
# self.clf = SVC(kernel='linear', C=0.025)
# elif classifier_type == 'Nearest_Neighbours':
# self.clf = KNeighborsClassifier(3)
# elif classifier_type == 'Decision_Tree':
# self.clf = DecisionTreeClassifier(max_depth=5)
# elif classifier_type == 'Random_Forest':
# self.clf = RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1, n_jobs=self.parallel_jobs)
# elif classifier_type == 'Naive_Bayes':
# self.clf = GaussianNB()
#
# def learn(self):
# print "Input features ", list(self.input_features)
# print "Target feature ", self.target_feature
# features = self.input_data[self.input_features].values
# labels = self.input_data[self.target_feature].values
# test_data_percentage = 1 - self.train_data_percentage
# x_train, x_test, y_train, y_actual = cross_validation.train_test_split(
# features, labels, test_size=test_data_percentage, random_state=0)
# self.clf.fit(x_train, y_train)
# y_pred = self.clf.predict(x_test)
# accuracy = round(accuracy_score(y_actual, y_pred), 2)
# recall = round(recall_score(y_actual, y_pred), 2)
# precision = round(precision_score(y_actual, y_pred), 2)
# f1 = round(f1_score(y_actual, y_pred), 2)
# mat = confusion_matrix(y_actual, y_pred)
# true_positives = mat[1][1]
# false_positives = mat[0][1]
# true_negatives = mat[0][0]
# false_negatives = mat[1][0]
# result = {
# 'Accuracy Score': accuracy, 'Recall Score': recall,
# 'Precision Score': precision, 'F1 Score': f1,
# 'True Positives': true_positives,
# 'False Positives': false_positives,
# 'True Negatives': true_negatives,
# 'False Negatives': false_negatives
# }
#
# print result
# return result
. Output only the next line. | exp = Experiment.objects.get(pk=self.experiment) |
Next line prediction: <|code_start|>
for elem in tmp:
node = elem.split(":")
if len(node) > 1:
first_node = node[0]
second_node = node[1]
else:
first_node = node[0]
second_node = ''
if second_node in graph_data:
depend_nodes = graph_data[second_node]
depend_nodes.add(first_node)
else:
graph_data[second_node] = set()
graph_data[second_node].add(first_node)
topological_graph = toposort_flatten(graph_data)
print "Graph after topological sort", topological_graph
if self.experiment in CACHE:
input_data = CACHE[self.experiment]
else:
input_data = DataFrame
feature_names = None
feature_types = None
output_data = None
for data in topological_graph:
component_id = int(data)
<|code_end|>
. Use current file imports:
(from ..models import Experiment, Component
from toposort import toposort_flatten
from ..ml_models import Classifier
from rest_framework import viewsets
from django.http import HttpResponse
from collections import Counter
from pandas import *
import threading
import json)
and context including class names, function names, or small code snippets from other files:
# Path: cognitive/app/models.py
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# class Component(models.Model):
# COMPONENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
#
# experiment = models.ForeignKey(Experiment)
# status = models.CharField(max_length=50, choices=COMPONENT_STATUS, default='Stop')
# operation_type = models.OneToOneField(DataOperationType, blank=True, null=True)
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# data_location = models.CharField(max_length=50, blank=True, null=True)
# preferred_data_location = models.CharField(max_length=50, blank=True, null=True)
# # component_id = models.IntegerField(blank=True, null=True)
#
# Path: cognitive/app/ml_models.py
# class Classifier:
# def __init__(self, input_data, classifier_type, train_data_percentage, input_features, target_feature):
# self.input_data = input_data
# self.train_data_percentage = train_data_percentage
# self.target_feature = target_feature
# self.input_features = input_features
# self.parallel_jobs = 1
# if classifier_type == 'Linear_SVM':
# self.clf = SVC(kernel='linear', C=0.025)
# elif classifier_type == 'Nearest_Neighbours':
# self.clf = KNeighborsClassifier(3)
# elif classifier_type == 'Decision_Tree':
# self.clf = DecisionTreeClassifier(max_depth=5)
# elif classifier_type == 'Random_Forest':
# self.clf = RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1, n_jobs=self.parallel_jobs)
# elif classifier_type == 'Naive_Bayes':
# self.clf = GaussianNB()
#
# def learn(self):
# print "Input features ", list(self.input_features)
# print "Target feature ", self.target_feature
# features = self.input_data[self.input_features].values
# labels = self.input_data[self.target_feature].values
# test_data_percentage = 1 - self.train_data_percentage
# x_train, x_test, y_train, y_actual = cross_validation.train_test_split(
# features, labels, test_size=test_data_percentage, random_state=0)
# self.clf.fit(x_train, y_train)
# y_pred = self.clf.predict(x_test)
# accuracy = round(accuracy_score(y_actual, y_pred), 2)
# recall = round(recall_score(y_actual, y_pred), 2)
# precision = round(precision_score(y_actual, y_pred), 2)
# f1 = round(f1_score(y_actual, y_pred), 2)
# mat = confusion_matrix(y_actual, y_pred)
# true_positives = mat[1][1]
# false_positives = mat[0][1]
# true_negatives = mat[0][0]
# false_negatives = mat[1][0]
# result = {
# 'Accuracy Score': accuracy, 'Recall Score': recall,
# 'Precision Score': precision, 'F1 Score': f1,
# 'True Positives': true_positives,
# 'False Positives': false_positives,
# 'True Negatives': true_negatives,
# 'False Negatives': false_negatives
# }
#
# print result
# return result
. Output only the next line. | comp = Component.objects.get(pk=component_id) |
Predict the next line for this snippet: <|code_start|> comp = Component.objects.get(pk=component_id)
print "Component_id", component_id, " ", comp.operation_type
op = comp.operation_type
if op.function_type == 'Create':
if op.function_arg == 'Table':
if op.function_subtype == 'Input':
filename = op.function_subtype_arg
input_data = read_csv(filename)
feature_names = input_data.columns
# TODO: [refactor] elif?
if op.function_arg == 'Row':
if op.function_subtype == 'Row':
row_values = json.loads(op.function_subtype_arg)
input_data.loc[len(input_data) + 1] = row_values
if op.function_arg == 'Model':
if op.function_subtype == 'Train-Test':
params = json.loads(op.function_subtype_arg)
train_data_percentage = int(params["train_data_percentage"])
target_column = int(params["target_column"])
model_type = op.function_arg_id
print model_type, train_data_percentage, target_column
target_feature = feature_names[target_column]
try:
actual_target_column = input_data.columns.get_loc(target_feature)
input_feature_columns = range(len(input_data.columns))
input_feature_columns.remove(actual_target_column)
input_features = input_data.columns[input_feature_columns]
<|code_end|>
with the help of current file imports:
from ..models import Experiment, Component
from toposort import toposort_flatten
from ..ml_models import Classifier
from rest_framework import viewsets
from django.http import HttpResponse
from collections import Counter
from pandas import *
import threading
import json
and context from other files:
# Path: cognitive/app/models.py
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# class Component(models.Model):
# COMPONENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
#
# experiment = models.ForeignKey(Experiment)
# status = models.CharField(max_length=50, choices=COMPONENT_STATUS, default='Stop')
# operation_type = models.OneToOneField(DataOperationType, blank=True, null=True)
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# data_location = models.CharField(max_length=50, blank=True, null=True)
# preferred_data_location = models.CharField(max_length=50, blank=True, null=True)
# # component_id = models.IntegerField(blank=True, null=True)
#
# Path: cognitive/app/ml_models.py
# class Classifier:
# def __init__(self, input_data, classifier_type, train_data_percentage, input_features, target_feature):
# self.input_data = input_data
# self.train_data_percentage = train_data_percentage
# self.target_feature = target_feature
# self.input_features = input_features
# self.parallel_jobs = 1
# if classifier_type == 'Linear_SVM':
# self.clf = SVC(kernel='linear', C=0.025)
# elif classifier_type == 'Nearest_Neighbours':
# self.clf = KNeighborsClassifier(3)
# elif classifier_type == 'Decision_Tree':
# self.clf = DecisionTreeClassifier(max_depth=5)
# elif classifier_type == 'Random_Forest':
# self.clf = RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1, n_jobs=self.parallel_jobs)
# elif classifier_type == 'Naive_Bayes':
# self.clf = GaussianNB()
#
# def learn(self):
# print "Input features ", list(self.input_features)
# print "Target feature ", self.target_feature
# features = self.input_data[self.input_features].values
# labels = self.input_data[self.target_feature].values
# test_data_percentage = 1 - self.train_data_percentage
# x_train, x_test, y_train, y_actual = cross_validation.train_test_split(
# features, labels, test_size=test_data_percentage, random_state=0)
# self.clf.fit(x_train, y_train)
# y_pred = self.clf.predict(x_test)
# accuracy = round(accuracy_score(y_actual, y_pred), 2)
# recall = round(recall_score(y_actual, y_pred), 2)
# precision = round(precision_score(y_actual, y_pred), 2)
# f1 = round(f1_score(y_actual, y_pred), 2)
# mat = confusion_matrix(y_actual, y_pred)
# true_positives = mat[1][1]
# false_positives = mat[0][1]
# true_negatives = mat[0][0]
# false_negatives = mat[1][0]
# result = {
# 'Accuracy Score': accuracy, 'Recall Score': recall,
# 'Precision Score': precision, 'F1 Score': f1,
# 'True Positives': true_positives,
# 'False Positives': false_positives,
# 'True Negatives': true_negatives,
# 'False Negatives': false_negatives
# }
#
# print result
# return result
, which may contain function names, class names, or code. Output only the next line. | classifier = Classifier( |
Predict the next line for this snippet: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law 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.
# TODO: [refactor] this import statement should specify some file instead of '*'
CACHE = {}
class storm_client (threading.Thread):
def __init__(self, thread_id, name, experiment, component_id, max_results, cache_results):
threading.Thread.__init__(self)
self.threadID = thread_id
self.name = name
self.experiment = experiment
self.comp_id = component_id
self.result = {}
self.max_results = max_results
self.cache_results = cache_results
print "Submitting topology to storm. End component", self.comp_id
<|code_end|>
with the help of current file imports:
from ..models import Experiment, Component
from toposort import toposort_flatten
from rest_framework import viewsets
from django.http import HttpResponse
from django.conf import settings
from django.core import serializers
from collections import defaultdict
from pandas import *
import redis
import threading
import json
and context from other files:
# Path: cognitive/app/models.py
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# class Component(models.Model):
# COMPONENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
#
# experiment = models.ForeignKey(Experiment)
# status = models.CharField(max_length=50, choices=COMPONENT_STATUS, default='Stop')
# operation_type = models.OneToOneField(DataOperationType, blank=True, null=True)
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# data_location = models.CharField(max_length=50, blank=True, null=True)
# preferred_data_location = models.CharField(max_length=50, blank=True, null=True)
# # component_id = models.IntegerField(blank=True, null=True)
, which may contain function names, class names, or code. Output only the next line. | exp = Experiment.objects.get(pk=self.experiment) |
Based on the snippet: <|code_start|> self.threadID = thread_id
self.name = name
self.experiment = experiment
self.comp_id = component_id
self.result = {}
self.max_results = max_results
self.cache_results = cache_results
print "Submitting topology to storm. End component", self.comp_id
exp = Experiment.objects.get(pk=self.experiment)
graph = exp.workflow.graph_data
graph_data = {}
print graph
tmp = graph.split(',')
for elem in tmp:
first_node = elem.split(":")[0]
second_node = elem.split(":")[1]
if second_node in graph_data:
depend_nodes = graph_data[second_node]
depend_nodes.add(first_node)
else:
graph_data[second_node] = set()
graph_data[second_node].add(first_node)
topological_graph = toposort_flatten(graph_data)
print "Graph after topological sort", topological_graph
message = {
'exp_id': self.experiment, 'result': self.comp_id,
'graph': topological_graph, 'components': defaultdict()}
for data in topological_graph:
component_id = int(data)
<|code_end|>
, predict the immediate next line with the help of imports:
from ..models import Experiment, Component
from toposort import toposort_flatten
from rest_framework import viewsets
from django.http import HttpResponse
from django.conf import settings
from django.core import serializers
from collections import defaultdict
from pandas import *
import redis
import threading
import json
and context (classes, functions, sometimes code) from other files:
# Path: cognitive/app/models.py
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# class Component(models.Model):
# COMPONENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
#
# experiment = models.ForeignKey(Experiment)
# status = models.CharField(max_length=50, choices=COMPONENT_STATUS, default='Stop')
# operation_type = models.OneToOneField(DataOperationType, blank=True, null=True)
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# data_location = models.CharField(max_length=50, blank=True, null=True)
# preferred_data_location = models.CharField(max_length=50, blank=True, null=True)
# # component_id = models.IntegerField(blank=True, null=True)
. Output only the next line. | comp = Component.objects.get(pk=component_id) |
Based on the snippet: <|code_start|># Copyright 2015 Cisco Inc.
#
# 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 WorkFlowViewSet(viewsets.ViewSet):
def list(self, request):
"""
List all workflows for an experiment
---
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from ..models import Workflow, Experiment
from ..serializers import WorkflowSerializer
from ..views import send_response
from rest_framework import viewsets
from rest_framework.renderers import JSONRenderer
import json
and context (classes, functions, sometimes code) from other files:
# Path: cognitive/app/models.py
# class Workflow(models.Model):
# experiment = models.OneToOneField(Experiment)
# graph_data = models.CharField(max_length=100)
#
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# Path: cognitive/app/serializers.py
# class WorkflowSerializer(serializers.ModelSerializer):
# class Meta:
# model = Workflow
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | exp = Workflow.objects.all() |
Given snippet: <|code_start|>
class WorkFlowViewSet(viewsets.ViewSet):
def list(self, request):
"""
List all workflows for an experiment
---
"""
exp = Workflow.objects.all()
serializer = WorkflowSerializer(exp, many=True)
return send_response(request.method, serializer)
def retrieve(self, request, pk=None):
"""
Retrieve a workflow for an experiment
---
"""
workflow = Workflow.objects.get(pk=pk)
serializer = WorkflowSerializer(workflow)
return send_response(request.method, serializer)
def create(self, request):
"""
Create a workflow for an experiment
---
request_serializer: WorkflowSerializer
"""
data = json.loads(JSONRenderer().render(request.data))
exp_id = int(data["experiment"])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..models import Workflow, Experiment
from ..serializers import WorkflowSerializer
from ..views import send_response
from rest_framework import viewsets
from rest_framework.renderers import JSONRenderer
import json
and context:
# Path: cognitive/app/models.py
# class Workflow(models.Model):
# experiment = models.OneToOneField(Experiment)
# graph_data = models.CharField(max_length=100)
#
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# Path: cognitive/app/serializers.py
# class WorkflowSerializer(serializers.ModelSerializer):
# class Meta:
# model = Workflow
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
which might include code, classes, or functions. Output only the next line. | exp = Experiment.objects.get(pk=exp_id) |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2015 Cisco Inc.
#
# 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 WorkFlowViewSet(viewsets.ViewSet):
def list(self, request):
"""
List all workflows for an experiment
---
"""
exp = Workflow.objects.all()
<|code_end|>
, predict the next line using imports from the current file:
from ..models import Workflow, Experiment
from ..serializers import WorkflowSerializer
from ..views import send_response
from rest_framework import viewsets
from rest_framework.renderers import JSONRenderer
import json
and context including class names, function names, and sometimes code from other files:
# Path: cognitive/app/models.py
# class Workflow(models.Model):
# experiment = models.OneToOneField(Experiment)
# graph_data = models.CharField(max_length=100)
#
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# Path: cognitive/app/serializers.py
# class WorkflowSerializer(serializers.ModelSerializer):
# class Meta:
# model = Workflow
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | serializer = WorkflowSerializer(exp, many=True) |
Given the code snippet: <|code_start|># Copyright 2015 Cisco Inc.
#
# 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 WorkFlowViewSet(viewsets.ViewSet):
def list(self, request):
"""
List all workflows for an experiment
---
"""
exp = Workflow.objects.all()
serializer = WorkflowSerializer(exp, many=True)
<|code_end|>
, generate the next line using the imports in this file:
from ..models import Workflow, Experiment
from ..serializers import WorkflowSerializer
from ..views import send_response
from rest_framework import viewsets
from rest_framework.renderers import JSONRenderer
import json
and context (functions, classes, or occasionally code) from other files:
# Path: cognitive/app/models.py
# class Workflow(models.Model):
# experiment = models.OneToOneField(Experiment)
# graph_data = models.CharField(max_length=100)
#
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# Path: cognitive/app/serializers.py
# class WorkflowSerializer(serializers.ModelSerializer):
# class Meta:
# model = Workflow
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | return send_response(request.method, serializer) |
Predict the next line after this snippet: <|code_start|># Copyright 2015 Cisco Inc.
#
# 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 ExperimentViewSet(viewsets.ViewSet):
def list(self, request):
"""
Lists all experiments for a particular user
---
"""
<|code_end|>
using the current file's imports:
from ..models import Experiment
from ..serializers import ExperimentSerializer
from ..views import send_response
from rest_framework import viewsets
and any relevant context from other files:
# Path: cognitive/app/models.py
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# Path: cognitive/app/serializers.py
# class ExperimentSerializer(serializers.ModelSerializer):
# class Meta:
# model = Experiment
# # fields = ('created_time', 'modified_time',
# # 'execution_start_time', 'execution_end_time', 'component_start_id')
# # read_only_fields = ('created_time', 'modified_time',
# # 'execution_start_time', 'execution_end_time', 'component_start_id')
# # write_only_fields = ('created_time', 'modified_time',
# # 'execution_start_time', 'execution_end_time', 'component_start_id')
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | exp = Experiment.objects.all() |
Given snippet: <|code_start|># Copyright 2015 Cisco Inc.
#
# 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 ExperimentViewSet(viewsets.ViewSet):
def list(self, request):
"""
Lists all experiments for a particular user
---
"""
exp = Experiment.objects.all()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..models import Experiment
from ..serializers import ExperimentSerializer
from ..views import send_response
from rest_framework import viewsets
and context:
# Path: cognitive/app/models.py
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# Path: cognitive/app/serializers.py
# class ExperimentSerializer(serializers.ModelSerializer):
# class Meta:
# model = Experiment
# # fields = ('created_time', 'modified_time',
# # 'execution_start_time', 'execution_end_time', 'component_start_id')
# # read_only_fields = ('created_time', 'modified_time',
# # 'execution_start_time', 'execution_end_time', 'component_start_id')
# # write_only_fields = ('created_time', 'modified_time',
# # 'execution_start_time', 'execution_end_time', 'component_start_id')
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
which might include code, classes, or functions. Output only the next line. | serializer = ExperimentSerializer(exp, many=True) |
Using the snippet: <|code_start|># Copyright 2015 Cisco Inc.
#
# 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 ExperimentViewSet(viewsets.ViewSet):
def list(self, request):
"""
Lists all experiments for a particular user
---
"""
exp = Experiment.objects.all()
serializer = ExperimentSerializer(exp, many=True)
<|code_end|>
, determine the next line of code. You have imports:
from ..models import Experiment
from ..serializers import ExperimentSerializer
from ..views import send_response
from rest_framework import viewsets
and context (class names, function names, or code) available:
# Path: cognitive/app/models.py
# class Experiment(models.Model):
# EXPERIMENT_STATUS = (
# ('Stop', ' Saved as stop'),
# ('InComplete', 'More information required'),
# ('InExecution', 'Execution started'),
# ('Error', ' Error when executed'),
# ('Completed', 'Executed Successfully'),
# )
# user = models.ForeignKey(User)
# name = models.CharField(max_length=50)
# status = models.CharField(max_length=50, choices=EXPERIMENT_STATUS, default='Stop')
# created_time = models.DateTimeField(auto_now=True)
# modified_time = models.DateTimeField(auto_now=True)
# execution_start_time = models.DateTimeField(blank=True, null=True)
# execution_end_time = models.DateTimeField(blank=True, null=True)
# component_start_id = models.IntegerField(blank=True, null=True)
#
# class Meta:
# ordering = ['-modified_time']
#
# Path: cognitive/app/serializers.py
# class ExperimentSerializer(serializers.ModelSerializer):
# class Meta:
# model = Experiment
# # fields = ('created_time', 'modified_time',
# # 'execution_start_time', 'execution_end_time', 'component_start_id')
# # read_only_fields = ('created_time', 'modified_time',
# # 'execution_start_time', 'execution_end_time', 'component_start_id')
# # write_only_fields = ('created_time', 'modified_time',
# # 'execution_start_time', 'execution_end_time', 'component_start_id')
#
# Path: cognitive/app/views.py
# def send_response(method, serializer):
# if method == 'GET':
# return Response(serializer.data)
# elif method == 'POST':
# if serializer.is_valid():
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'PUT':
# if serializer.is_valid():
# return Response(serializer.data)
# else:
# return Response(
# serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# elif method == 'DELETE':
# return Response(status=status.HTTP_204_NO_CONTENT)
. Output only the next line. | return send_response(request.method, serializer) |
Here is a snippet: <|code_start|>
def nonfatal(func, *args):
try:
func(*args)
except Fatal as e:
<|code_end|>
. Write the next line using the current file imports:
import socket
import subprocess as ssubprocess
from sshuttle.helpers import log, debug1, Fatal, family_to_string, get_env
and context from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# class Fatal(Exception):
# pass
#
# def family_to_string(family):
# if family == socket.AF_INET6:
# return "AF_INET6"
# elif family == socket.AF_INET:
# return "AF_INET"
# else:
# return str(family)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
, which may include functions, classes, or code. Output only the next line. | log('error: %s' % e) |
Predict the next line for this snippet: <|code_start|> try:
func(*args)
except Fatal as e:
log('error: %s' % e)
def ipt_chain_exists(family, table, name):
if family == socket.AF_INET6:
cmd = 'ip6tables'
elif family == socket.AF_INET:
cmd = 'iptables'
else:
raise Exception('Unsupported family "%s"' % family_to_string(family))
argv = [cmd, '-w', '-t', table, '-nL']
try:
output = ssubprocess.check_output(argv, env=get_env())
for line in output.decode('ASCII').split('\n'):
if line.startswith('Chain %s ' % name):
return True
except ssubprocess.CalledProcessError as e:
raise Fatal('%r returned %d' % (argv, e.returncode))
def ipt(family, table, *args):
if family == socket.AF_INET6:
argv = ['ip6tables', '-w', '-t', table] + list(args)
elif family == socket.AF_INET:
argv = ['iptables', '-w', '-t', table] + list(args)
else:
raise Exception('Unsupported family "%s"' % family_to_string(family))
<|code_end|>
with the help of current file imports:
import socket
import subprocess as ssubprocess
from sshuttle.helpers import log, debug1, Fatal, family_to_string, get_env
and context from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# class Fatal(Exception):
# pass
#
# def family_to_string(family):
# if family == socket.AF_INET6:
# return "AF_INET6"
# elif family == socket.AF_INET:
# return "AF_INET"
# else:
# return str(family)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
, which may contain function names, class names, or code. Output only the next line. | debug1('%s' % ' '.join(argv)) |
Predict the next line after this snippet: <|code_start|>
def nonfatal(func, *args):
try:
func(*args)
<|code_end|>
using the current file's imports:
import socket
import subprocess as ssubprocess
from sshuttle.helpers import log, debug1, Fatal, family_to_string, get_env
and any relevant context from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# class Fatal(Exception):
# pass
#
# def family_to_string(family):
# if family == socket.AF_INET6:
# return "AF_INET6"
# elif family == socket.AF_INET:
# return "AF_INET"
# else:
# return str(family)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
. Output only the next line. | except Fatal as e: |
Using the snippet: <|code_start|>
def nonfatal(func, *args):
try:
func(*args)
except Fatal as e:
log('error: %s' % e)
def ipt_chain_exists(family, table, name):
if family == socket.AF_INET6:
cmd = 'ip6tables'
elif family == socket.AF_INET:
cmd = 'iptables'
else:
<|code_end|>
, determine the next line of code. You have imports:
import socket
import subprocess as ssubprocess
from sshuttle.helpers import log, debug1, Fatal, family_to_string, get_env
and context (class names, function names, or code) available:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# class Fatal(Exception):
# pass
#
# def family_to_string(family):
# if family == socket.AF_INET6:
# return "AF_INET6"
# elif family == socket.AF_INET:
# return "AF_INET"
# else:
# return str(family)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
. Output only the next line. | raise Exception('Unsupported family "%s"' % family_to_string(family)) |
Given snippet: <|code_start|>
def nonfatal(func, *args):
try:
func(*args)
except Fatal as e:
log('error: %s' % e)
def ipt_chain_exists(family, table, name):
if family == socket.AF_INET6:
cmd = 'ip6tables'
elif family == socket.AF_INET:
cmd = 'iptables'
else:
raise Exception('Unsupported family "%s"' % family_to_string(family))
argv = [cmd, '-w', '-t', table, '-nL']
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import socket
import subprocess as ssubprocess
from sshuttle.helpers import log, debug1, Fatal, family_to_string, get_env
and context:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# class Fatal(Exception):
# pass
#
# def family_to_string(family):
# if family == socket.AF_INET6:
# return "AF_INET6"
# elif family == socket.AF_INET:
# return "AF_INET"
# else:
# return str(family)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
which might include code, classes, or functions. Output only the next line. | output = ssubprocess.check_output(argv, env=get_env()) |
Based on the snippet: <|code_start|> return 0 # still connecting
self.wsock.setblocking(False)
try:
return _nb_clean(os.write, self.wsock.fileno(), buf)
except OSError:
_, e = sys.exc_info()[:2]
if e.errno == errno.EPIPE:
debug1('%r: uwrite: got EPIPE' % self)
self.nowrite()
return 0
else:
# unexpected error... stream is dead
self.seterr('uwrite: %s' % e)
return 0
def write(self, buf):
assert(buf)
return self.uwrite(buf)
def uread(self):
if self.connect_to:
return None # still connecting
if self.shut_read:
return
self.rsock.setblocking(False)
try:
return _nb_clean(os.read, self.rsock.fileno(), 65536)
except OSError:
_, e = sys.exc_info()[:2]
self.seterr('uread: %s' % e)
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import struct
import socket
import errno
import select
import os
import fcntl
from sshuttle.helpers import b, log, debug1, debug2, debug3, Fatal
and context (classes, functions, sometimes code) from other files:
# Path: sshuttle/helpers.py
# def b(s):
# return s.encode("ASCII")
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# class Fatal(Exception):
# pass
. Output only the next line. | return b('') # unexpected error... we'll call it EOF |
Continue the code snippet: <|code_start|> return
rb = self.uread()
if rb:
self.buf.append(rb)
if rb == b(''): # empty string means EOF; None means temporarily empty
self.noread()
def copy_to(self, outwrap):
if self.buf and self.buf[0]:
wrote = outwrap.write(self.buf[0])
self.buf[0] = self.buf[0][wrote:]
while self.buf and not self.buf[0]:
self.buf.pop(0)
if not self.buf and self.shut_read:
outwrap.nowrite()
class Handler:
def __init__(self, socks=None, callback=None):
self.ok = True
self.socks = socks or []
if callback:
self.callback = callback
def pre_select(self, r, w, x):
for i in self.socks:
_add(r, i)
def callback(self, sock):
<|code_end|>
. Use current file imports:
import sys
import struct
import socket
import errno
import select
import os
import fcntl
from sshuttle.helpers import b, log, debug1, debug2, debug3, Fatal
and context (classes, functions, or code) from other files:
# Path: sshuttle/helpers.py
# def b(s):
# return s.encode("ASCII")
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# class Fatal(Exception):
# pass
. Output only the next line. | log('--no callback defined-- %r' % self) |
Predict the next line for this snippet: <|code_start|> if e.args[0] == errno.EINVAL:
pass
elif e.args[0] not in (errno.ENOTCONN, errno.ENOTSOCK):
raise
except AttributeError:
pass
return 'unknown'
_swcount = 0
class SockWrapper:
def __init__(self, rsock, wsock, connect_to=None, peername=None):
global _swcount
_swcount += 1
debug3('creating new SockWrapper (%d now exist)' % _swcount)
self.exc = None
self.rsock = rsock
self.wsock = wsock
self.shut_read = self.shut_write = False
self.buf = []
self.connect_to = connect_to
self.peername = peername or _try_peername(self.rsock)
self.try_connect()
def __del__(self):
global _swcount
_swcount -= 1
<|code_end|>
with the help of current file imports:
import sys
import struct
import socket
import errno
import select
import os
import fcntl
from sshuttle.helpers import b, log, debug1, debug2, debug3, Fatal
and context from other files:
# Path: sshuttle/helpers.py
# def b(s):
# return s.encode("ASCII")
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# class Fatal(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | debug1('%r: deleting (%d remain)' % (self, _swcount)) |
Given snippet: <|code_start|> # automatically, so this code won't run.
realerr = self.rsock.getsockopt(socket.SOL_SOCKET,
socket.SO_ERROR)
e = socket.error(realerr, os.strerror(realerr))
debug3('%r: fixed connect result: %s' % (self, e))
if e.args[0] in [errno.EINPROGRESS, errno.EALREADY]:
pass # not connected yet
elif e.args[0] == 0:
# connected successfully (weird Linux bug?)
# Sometimes Linux seems to return EINVAL when it isn't
# invalid. This *may* be caused by a race condition
# between connect() and getsockopt(SO_ERROR) (ie. it
# finishes connecting in between the two, so there is no
# longer an error). However, I'm not sure of that.
#
# I did get at least one report that the problem went away
# when we added this, however.
self.connect_to = None
elif e.args[0] == errno.EISCONN:
# connected successfully (BSD)
self.connect_to = None
elif e.args[0] in NET_ERRS + [errno.EACCES, errno.EPERM]:
# a "normal" kind of error
self.connect_to = None
self.seterr(e)
else:
raise # error we've never heard of?! barf completely.
def noread(self):
if not self.shut_read:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import struct
import socket
import errno
import select
import os
import fcntl
from sshuttle.helpers import b, log, debug1, debug2, debug3, Fatal
and context:
# Path: sshuttle/helpers.py
# def b(s):
# return s.encode("ASCII")
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# class Fatal(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | debug2('%r: done reading' % self) |
Here is a snippet: <|code_start|> errno.EHOSTUNREACH, errno.ENETUNREACH,
errno.EHOSTDOWN, errno.ENETDOWN,
errno.ENETUNREACH, errno.ECONNABORTED,
errno.ECONNRESET]
def _add(socks, elem):
if elem not in socks:
socks.append(elem)
def _fds(socks):
out = []
for i in socks:
try:
out.append(i.fileno())
except AttributeError:
out.append(i)
out.sort()
return out
def _nb_clean(func, *args):
try:
return func(*args)
except OSError:
_, e = sys.exc_info()[:2]
if e.errno not in (errno.EWOULDBLOCK, errno.EAGAIN):
raise
else:
<|code_end|>
. Write the next line using the current file imports:
import sys
import struct
import socket
import errno
import select
import os
import fcntl
from sshuttle.helpers import b, log, debug1, debug2, debug3, Fatal
and context from other files:
# Path: sshuttle/helpers.py
# def b(s):
# return s.encode("ASCII")
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# class Fatal(Exception):
# pass
, which may include functions, classes, or code. Output only the next line. | debug3('%s: err was: %s' % (func.__name__, e)) |
Given snippet: <|code_start|> try:
os.set_blocking(self.wfile.fileno(), False)
except AttributeError:
# python < 3.5
flags = fcntl.fcntl(self.wfile.fileno(), fcntl.F_GETFL)
flags |= os.O_NONBLOCK
flags = fcntl.fcntl(self.wfile.fileno(), fcntl.F_SETFL, flags)
if self.outbuf and self.outbuf[0]:
wrote = _nb_clean(os.write, self.wfile.fileno(), self.outbuf[0])
debug2('mux wrote: %r/%d' % (wrote, len(self.outbuf[0])))
if wrote:
self.outbuf[0] = self.outbuf[0][wrote:]
while self.outbuf and not self.outbuf[0]:
self.outbuf[0:1] = []
def fill(self):
try:
os.set_blocking(self.rfile.fileno(), False)
except AttributeError:
# python < 3.5
flags = fcntl.fcntl(self.rfile.fileno(), fcntl.F_GETFL)
flags |= os.O_NONBLOCK
flags = fcntl.fcntl(self.rfile.fileno(), fcntl.F_SETFL, flags)
try:
# If LATENCY_BUFFER_SIZE is inappropriately large, we will
# get a MemoryError here. Read no more than 1MiB.
read = _nb_clean(os.read, self.rfile.fileno(),
min(1048576, LATENCY_BUFFER_SIZE))
except OSError:
_, e = sys.exc_info()[:2]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import struct
import socket
import errno
import select
import os
import fcntl
from sshuttle.helpers import b, log, debug1, debug2, debug3, Fatal
and context:
# Path: sshuttle/helpers.py
# def b(s):
# return s.encode("ASCII")
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# class Fatal(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | raise Fatal('other end: %r' % e) |
Given snippet: <|code_start|> return hostwatch.hw_main(opt.subnets, opt.auto_hosts)
else:
# parse_subnetports() is used to create a list of includes
# and excludes. It is called once for each parameter and
# returns a list of one or more items for each subnet (it
# can return more than one item when a hostname in the
# parameter resolves to multiple IP addresses. Here, we
# flatten these lists.
includes = [item for sublist in opt.subnets+opt.subnets_file
for item in sublist]
excludes = [item for sublist in opt.exclude for item in sublist]
if not includes and not opt.auto_nets:
parser.error('at least one subnet, subnet file, '
'or -N expected')
remotename = opt.remote
if remotename == '' or remotename == '-':
remotename = None
nslist = [family_ip_tuple(ns) for ns in opt.ns_hosts]
if opt.seed_hosts:
sh = re.split(r'[\s,]+', (opt.seed_hosts or "").strip())
elif opt.auto_hosts:
sh = []
else:
sh = None
if opt.listen:
ipport_v6 = None
ipport_v4 = None
lst = opt.listen.split(",")
for ip in lst:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import socket
import platform
import sshuttle.helpers as helpers
import sshuttle.client as client
import sshuttle.firewall as firewall
import sshuttle.hostwatch as hostwatch
import sshuttle.ssyslog as ssyslog
import sshuttle.ssnet as ssnet
import sshuttle.ssnet as ssnet
from sshuttle.options import parser, parse_ipport
from sshuttle.helpers import family_ip_tuple, log, Fatal
from sshuttle.sudoers import sudoers
and context:
# Path: sshuttle/options.py
# def parse_subnetport_file(s):
# def parse_subnetport(s):
# def parse_ipport(s):
# def parse_list(lst):
# def __init__(self, option_strings, dest, nargs=None, **kwargs):
# def __call__(self, parser, namespace, values, option_string=None):
# def convert_arg_line_to_args(self, arg_line):
# class Concat(Action):
# class MyArgumentParser(ArgumentParser):
#
# Path: sshuttle/helpers.py
# def family_ip_tuple(ip):
# if ':' in ip:
# return (socket.AF_INET6, ip)
# else:
# return (socket.AF_INET, ip)
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# class Fatal(Exception):
# pass
#
# Path: sshuttle/sudoers.py
# def sudoers(user_name=None, no_modify=None, file_name=None):
# user_name = user_name or getpass.getuser()
# content = build_config(user_name)
#
# if no_modify:
# sys.stdout.write(content)
# exit(0)
# else:
# sys.stdout.write(warning_msg)
# save_config(content, file_name)
which might include code, classes, or functions. Output only the next line. | family, ip, port = parse_ipport(ip) |
Given the code snippet: <|code_start|> if opt.wrap:
ssnet.MAX_CHANNEL = opt.wrap
if opt.latency_buffer_size:
ssnet.LATENCY_BUFFER_SIZE = opt.latency_buffer_size
helpers.verbose = opt.verbose
try:
if opt.firewall:
if opt.subnets or opt.subnets_file:
parser.error('exactly zero arguments expected')
return firewall.main(opt.method, opt.syslog)
elif opt.hostwatch:
return hostwatch.hw_main(opt.subnets, opt.auto_hosts)
else:
# parse_subnetports() is used to create a list of includes
# and excludes. It is called once for each parameter and
# returns a list of one or more items for each subnet (it
# can return more than one item when a hostname in the
# parameter resolves to multiple IP addresses. Here, we
# flatten these lists.
includes = [item for sublist in opt.subnets+opt.subnets_file
for item in sublist]
excludes = [item for sublist in opt.exclude for item in sublist]
if not includes and not opt.auto_nets:
parser.error('at least one subnet, subnet file, '
'or -N expected')
remotename = opt.remote
if remotename == '' or remotename == '-':
remotename = None
<|code_end|>
, generate the next line using the imports in this file:
import re
import socket
import platform
import sshuttle.helpers as helpers
import sshuttle.client as client
import sshuttle.firewall as firewall
import sshuttle.hostwatch as hostwatch
import sshuttle.ssyslog as ssyslog
import sshuttle.ssnet as ssnet
import sshuttle.ssnet as ssnet
from sshuttle.options import parser, parse_ipport
from sshuttle.helpers import family_ip_tuple, log, Fatal
from sshuttle.sudoers import sudoers
and context (functions, classes, or occasionally code) from other files:
# Path: sshuttle/options.py
# def parse_subnetport_file(s):
# def parse_subnetport(s):
# def parse_ipport(s):
# def parse_list(lst):
# def __init__(self, option_strings, dest, nargs=None, **kwargs):
# def __call__(self, parser, namespace, values, option_string=None):
# def convert_arg_line_to_args(self, arg_line):
# class Concat(Action):
# class MyArgumentParser(ArgumentParser):
#
# Path: sshuttle/helpers.py
# def family_ip_tuple(ip):
# if ':' in ip:
# return (socket.AF_INET6, ip)
# else:
# return (socket.AF_INET, ip)
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# class Fatal(Exception):
# pass
#
# Path: sshuttle/sudoers.py
# def sudoers(user_name=None, no_modify=None, file_name=None):
# user_name = user_name or getpass.getuser()
# content = build_config(user_name)
#
# if no_modify:
# sys.stdout.write(content)
# exit(0)
# else:
# sys.stdout.write(warning_msg)
# save_config(content, file_name)
. Output only the next line. | nslist = [family_ip_tuple(ns) for ns in opt.ns_hosts] |
Predict the next line after this snippet: <|code_start|>
def main():
opt = parser.parse_args()
if opt.sudoers or opt.sudoers_no_modify:
if platform.platform().startswith('OpenBSD'):
<|code_end|>
using the current file's imports:
import re
import socket
import platform
import sshuttle.helpers as helpers
import sshuttle.client as client
import sshuttle.firewall as firewall
import sshuttle.hostwatch as hostwatch
import sshuttle.ssyslog as ssyslog
import sshuttle.ssnet as ssnet
import sshuttle.ssnet as ssnet
from sshuttle.options import parser, parse_ipport
from sshuttle.helpers import family_ip_tuple, log, Fatal
from sshuttle.sudoers import sudoers
and any relevant context from other files:
# Path: sshuttle/options.py
# def parse_subnetport_file(s):
# def parse_subnetport(s):
# def parse_ipport(s):
# def parse_list(lst):
# def __init__(self, option_strings, dest, nargs=None, **kwargs):
# def __call__(self, parser, namespace, values, option_string=None):
# def convert_arg_line_to_args(self, arg_line):
# class Concat(Action):
# class MyArgumentParser(ArgumentParser):
#
# Path: sshuttle/helpers.py
# def family_ip_tuple(ip):
# if ':' in ip:
# return (socket.AF_INET6, ip)
# else:
# return (socket.AF_INET, ip)
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# class Fatal(Exception):
# pass
#
# Path: sshuttle/sudoers.py
# def sudoers(user_name=None, no_modify=None, file_name=None):
# user_name = user_name or getpass.getuser()
# content = build_config(user_name)
#
# if no_modify:
# sys.stdout.write(content)
# exit(0)
# else:
# sys.stdout.write(warning_msg)
# save_config(content, file_name)
. Output only the next line. | log('Automatic sudoers does not work on BSD') |
Based on the snippet: <|code_start|> ssyslog.close_stdin()
ssyslog.stdout_to_syslog()
ssyslog.stderr_to_syslog()
return_code = client.main(ipport_v6, ipport_v4,
opt.ssh_cmd,
remotename,
opt.python,
opt.latency_control,
opt.latency_buffer_size,
opt.dns,
nslist,
opt.method,
sh,
opt.auto_hosts,
opt.auto_nets,
includes,
excludes,
opt.daemon,
opt.to_ns,
opt.pidfile,
opt.user,
opt.sudo_pythonpath,
opt.tmark)
if return_code == 0:
log('Normal exit code, exiting...')
else:
log('Abnormal exit code %d detected, failing...' % return_code)
return return_code
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import socket
import platform
import sshuttle.helpers as helpers
import sshuttle.client as client
import sshuttle.firewall as firewall
import sshuttle.hostwatch as hostwatch
import sshuttle.ssyslog as ssyslog
import sshuttle.ssnet as ssnet
import sshuttle.ssnet as ssnet
from sshuttle.options import parser, parse_ipport
from sshuttle.helpers import family_ip_tuple, log, Fatal
from sshuttle.sudoers import sudoers
and context (classes, functions, sometimes code) from other files:
# Path: sshuttle/options.py
# def parse_subnetport_file(s):
# def parse_subnetport(s):
# def parse_ipport(s):
# def parse_list(lst):
# def __init__(self, option_strings, dest, nargs=None, **kwargs):
# def __call__(self, parser, namespace, values, option_string=None):
# def convert_arg_line_to_args(self, arg_line):
# class Concat(Action):
# class MyArgumentParser(ArgumentParser):
#
# Path: sshuttle/helpers.py
# def family_ip_tuple(ip):
# if ':' in ip:
# return (socket.AF_INET6, ip)
# else:
# return (socket.AF_INET, ip)
#
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# class Fatal(Exception):
# pass
#
# Path: sshuttle/sudoers.py
# def sudoers(user_name=None, no_modify=None, file_name=None):
# user_name = user_name or getpass.getuser()
# content = build_config(user_name)
#
# if no_modify:
# sys.stdout.write(content)
# exit(0)
# else:
# sys.stdout.write(warning_msg)
# save_config(content, file_name)
. Output only the next line. | except Fatal as e: |
Based on the snippet: <|code_start|> "# command as root.\n"
def build_config(user_name):
content = warning_msg
content += template % {
'ca': command_alias,
'dist_packages': path_to_dist_packages,
'py': sys.executable,
'path': path_to_sshuttle,
'user_name': user_name,
}
return content
def save_config(content, file_name):
process = Popen([
'/usr/bin/sudo',
spawn.find_executable('sudoers-add'),
file_name,
], stdout=PIPE, stdin=PIPE)
process.stdin.write(content.encode())
streamdata = process.communicate()[0]
sys.stdout.write(streamdata.decode("ASCII"))
returncode = process.returncode
if returncode:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import getpass
from uuid import uuid4
from subprocess import Popen, PIPE
from sshuttle.helpers import log, debug1
from distutils import spawn
and context (classes, functions, sometimes code) from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
. Output only the next line. | log('Failed updating sudoers file.') |
Next line prediction: <|code_start|>
def build_config(user_name):
content = warning_msg
content += template % {
'ca': command_alias,
'dist_packages': path_to_dist_packages,
'py': sys.executable,
'path': path_to_sshuttle,
'user_name': user_name,
}
return content
def save_config(content, file_name):
process = Popen([
'/usr/bin/sudo',
spawn.find_executable('sudoers-add'),
file_name,
], stdout=PIPE, stdin=PIPE)
process.stdin.write(content.encode())
streamdata = process.communicate()[0]
sys.stdout.write(streamdata.decode("ASCII"))
returncode = process.returncode
if returncode:
log('Failed updating sudoers file.')
<|code_end|>
. Use current file imports:
(import os
import sys
import getpass
from uuid import uuid4
from subprocess import Popen, PIPE
from sshuttle.helpers import log, debug1
from distutils import spawn)
and context including class names, function names, or small code snippets from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
. Output only the next line. | debug1(streamdata) |
Given snippet: <|code_start|>"""When sshuttle is run via a systemd service file, we can communicate
to systemd about the status of the sshuttle process. In particular, we
can send READY status to tell systemd that sshuttle has completed
startup and send STOPPING to indicate that sshuttle is beginning
shutdown.
For details, see:
https://www.freedesktop.org/software/systemd/man/sd_notify.html
"""
def _notify(message):
"""Send a notification message to systemd."""
addr = os.environ.get("NOTIFY_SOCKET", None)
if not addr or len(addr) == 1 or addr[0] not in ('/', '@'):
return False
addr = '\0' + addr[1:] if addr[0] == '@' else addr
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
except (OSError, IOError) as e:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import socket
import os
from sshuttle.helpers import debug1
and context:
# Path: sshuttle/helpers.py
# def debug1(s):
# if verbose >= 1:
# log(s)
which might include code, classes, or functions. Output only the next line. | debug1("Error creating socket to notify systemd: %s" % e) |
Given the code snippet: <|code_start|>
if password is not None:
os.environ['SSHPASS'] = str(password)
argv = (["sshpass", "-e"] + sshl +
portl +
[rhost, '--', pycmd])
else:
argv = (sshl +
portl +
[rhost, '--', pycmd])
# Our which() function searches for programs in get_path()
# directories (which include PATH). This step isn't strictly
# necessary if ssh is already in the user's PATH, but it makes the
# error message friendlier if the user incorrectly passes in a
# custom ssh command that we cannot find.
abs_path = which(argv[0])
if abs_path is None:
raise Fatal("Failed to find '%s' in path %s" % (argv[0], get_path()))
argv[0] = abs_path
(s1, s2) = socket.socketpair()
def setup():
# runs in the child process
s2.close()
s1a, s1b = os.dup(s1.fileno()), os.dup(s1.fileno())
s1.close()
<|code_end|>
, generate the next line using the imports in this file:
import sys
import os
import re
import socket
import zlib
import importlib
import importlib.util
import subprocess as ssubprocess
import shlex
import ipaddress
import sshuttle.helpers as helpers
from shlex import quote
from urllib.parse import urlparse
from sshuttle.helpers import debug2, which, get_path, Fatal
and context (functions, classes, or occasionally code) from other files:
# Path: sshuttle/helpers.py
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def which(file, mode=os.F_OK | os.X_OK):
# """A wrapper around shutil.which() that searches a predictable set of
# paths and is more verbose about what is happening. See get_path()
# for more information.
# """
# path = get_path()
# rv = _which(file, mode, path)
# if rv:
# debug2("which() found '%s' at %s" % (file, rv))
# else:
# debug2("which() could not find '%s' in %s" % (file, path))
# return rv
#
# def get_path():
# """Returns a string of paths separated by os.pathsep.
#
# Users might not have all of the programs sshuttle needs in their
# PATH variable (i.e., some programs might be in /sbin). Use PATH
# and a hardcoded set of paths to search through. This function is
# used by our which() and get_env() functions. If which() and the
# subprocess environments differ, programs that which() finds might
# not be found at run time (or vice versa).
# """
# path = []
# if "PATH" in os.environ:
# path += os.environ["PATH"].split(os.pathsep)
# # Python default paths.
# path += os.defpath.split(os.pathsep)
# # /sbin, etc are not in os.defpath and may not be in PATH either.
# # /bin/ and /usr/bin below are probably redundant.
# path += ['/bin', '/usr/bin', '/sbin', '/usr/sbin']
#
# # Remove duplicates. Not strictly necessary.
# path_dedup = []
# for i in path:
# if i not in path_dedup:
# path_dedup.append(i)
#
# return os.pathsep.join(path_dedup)
#
# class Fatal(Exception):
# pass
. Output only the next line. | debug2('executing: %r' % argv) |
Given snippet: <|code_start|> #
# Specifying the exact python program to run with --python
# avoids many of the issues above. However, if
# you have a restricted shell on remote, you may only be
# able to run python if it is in your PATH (and you can't
# run programs specified with an absolute path). In that
# case, sshuttle might not work at all since it is not
# possible to run python on the remote machine---even if
# it is present.
pycmd = ("P=python3; $P -V 2>%s || P=python; "
"exec \"$P\" -c %s; exit 97") % \
(os.devnull, quote(pyscript))
pycmd = ("/bin/sh -c {}".format(quote(pycmd)))
if password is not None:
os.environ['SSHPASS'] = str(password)
argv = (["sshpass", "-e"] + sshl +
portl +
[rhost, '--', pycmd])
else:
argv = (sshl +
portl +
[rhost, '--', pycmd])
# Our which() function searches for programs in get_path()
# directories (which include PATH). This step isn't strictly
# necessary if ssh is already in the user's PATH, but it makes the
# error message friendlier if the user incorrectly passes in a
# custom ssh command that we cannot find.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import os
import re
import socket
import zlib
import importlib
import importlib.util
import subprocess as ssubprocess
import shlex
import ipaddress
import sshuttle.helpers as helpers
from shlex import quote
from urllib.parse import urlparse
from sshuttle.helpers import debug2, which, get_path, Fatal
and context:
# Path: sshuttle/helpers.py
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def which(file, mode=os.F_OK | os.X_OK):
# """A wrapper around shutil.which() that searches a predictable set of
# paths and is more verbose about what is happening. See get_path()
# for more information.
# """
# path = get_path()
# rv = _which(file, mode, path)
# if rv:
# debug2("which() found '%s' at %s" % (file, rv))
# else:
# debug2("which() could not find '%s' in %s" % (file, path))
# return rv
#
# def get_path():
# """Returns a string of paths separated by os.pathsep.
#
# Users might not have all of the programs sshuttle needs in their
# PATH variable (i.e., some programs might be in /sbin). Use PATH
# and a hardcoded set of paths to search through. This function is
# used by our which() and get_env() functions. If which() and the
# subprocess environments differ, programs that which() finds might
# not be found at run time (or vice versa).
# """
# path = []
# if "PATH" in os.environ:
# path += os.environ["PATH"].split(os.pathsep)
# # Python default paths.
# path += os.defpath.split(os.pathsep)
# # /sbin, etc are not in os.defpath and may not be in PATH either.
# # /bin/ and /usr/bin below are probably redundant.
# path += ['/bin', '/usr/bin', '/sbin', '/usr/sbin']
#
# # Remove duplicates. Not strictly necessary.
# path_dedup = []
# for i in path:
# if i not in path_dedup:
# path_dedup.append(i)
#
# return os.pathsep.join(path_dedup)
#
# class Fatal(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | abs_path = which(argv[0]) |
Continue the code snippet: <|code_start|> # avoids many of the issues above. However, if
# you have a restricted shell on remote, you may only be
# able to run python if it is in your PATH (and you can't
# run programs specified with an absolute path). In that
# case, sshuttle might not work at all since it is not
# possible to run python on the remote machine---even if
# it is present.
pycmd = ("P=python3; $P -V 2>%s || P=python; "
"exec \"$P\" -c %s; exit 97") % \
(os.devnull, quote(pyscript))
pycmd = ("/bin/sh -c {}".format(quote(pycmd)))
if password is not None:
os.environ['SSHPASS'] = str(password)
argv = (["sshpass", "-e"] + sshl +
portl +
[rhost, '--', pycmd])
else:
argv = (sshl +
portl +
[rhost, '--', pycmd])
# Our which() function searches for programs in get_path()
# directories (which include PATH). This step isn't strictly
# necessary if ssh is already in the user's PATH, but it makes the
# error message friendlier if the user incorrectly passes in a
# custom ssh command that we cannot find.
abs_path = which(argv[0])
if abs_path is None:
<|code_end|>
. Use current file imports:
import sys
import os
import re
import socket
import zlib
import importlib
import importlib.util
import subprocess as ssubprocess
import shlex
import ipaddress
import sshuttle.helpers as helpers
from shlex import quote
from urllib.parse import urlparse
from sshuttle.helpers import debug2, which, get_path, Fatal
and context (classes, functions, or code) from other files:
# Path: sshuttle/helpers.py
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def which(file, mode=os.F_OK | os.X_OK):
# """A wrapper around shutil.which() that searches a predictable set of
# paths and is more verbose about what is happening. See get_path()
# for more information.
# """
# path = get_path()
# rv = _which(file, mode, path)
# if rv:
# debug2("which() found '%s' at %s" % (file, rv))
# else:
# debug2("which() could not find '%s' in %s" % (file, path))
# return rv
#
# def get_path():
# """Returns a string of paths separated by os.pathsep.
#
# Users might not have all of the programs sshuttle needs in their
# PATH variable (i.e., some programs might be in /sbin). Use PATH
# and a hardcoded set of paths to search through. This function is
# used by our which() and get_env() functions. If which() and the
# subprocess environments differ, programs that which() finds might
# not be found at run time (or vice versa).
# """
# path = []
# if "PATH" in os.environ:
# path += os.environ["PATH"].split(os.pathsep)
# # Python default paths.
# path += os.defpath.split(os.pathsep)
# # /sbin, etc are not in os.defpath and may not be in PATH either.
# # /bin/ and /usr/bin below are probably redundant.
# path += ['/bin', '/usr/bin', '/sbin', '/usr/sbin']
#
# # Remove duplicates. Not strictly necessary.
# path_dedup = []
# for i in path:
# if i not in path_dedup:
# path_dedup.append(i)
#
# return os.pathsep.join(path_dedup)
#
# class Fatal(Exception):
# pass
. Output only the next line. | raise Fatal("Failed to find '%s' in path %s" % (argv[0], get_path())) |
Predict the next line after this snippet: <|code_start|> # avoids many of the issues above. However, if
# you have a restricted shell on remote, you may only be
# able to run python if it is in your PATH (and you can't
# run programs specified with an absolute path). In that
# case, sshuttle might not work at all since it is not
# possible to run python on the remote machine---even if
# it is present.
pycmd = ("P=python3; $P -V 2>%s || P=python; "
"exec \"$P\" -c %s; exit 97") % \
(os.devnull, quote(pyscript))
pycmd = ("/bin/sh -c {}".format(quote(pycmd)))
if password is not None:
os.environ['SSHPASS'] = str(password)
argv = (["sshpass", "-e"] + sshl +
portl +
[rhost, '--', pycmd])
else:
argv = (sshl +
portl +
[rhost, '--', pycmd])
# Our which() function searches for programs in get_path()
# directories (which include PATH). This step isn't strictly
# necessary if ssh is already in the user's PATH, but it makes the
# error message friendlier if the user incorrectly passes in a
# custom ssh command that we cannot find.
abs_path = which(argv[0])
if abs_path is None:
<|code_end|>
using the current file's imports:
import sys
import os
import re
import socket
import zlib
import importlib
import importlib.util
import subprocess as ssubprocess
import shlex
import ipaddress
import sshuttle.helpers as helpers
from shlex import quote
from urllib.parse import urlparse
from sshuttle.helpers import debug2, which, get_path, Fatal
and any relevant context from other files:
# Path: sshuttle/helpers.py
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def which(file, mode=os.F_OK | os.X_OK):
# """A wrapper around shutil.which() that searches a predictable set of
# paths and is more verbose about what is happening. See get_path()
# for more information.
# """
# path = get_path()
# rv = _which(file, mode, path)
# if rv:
# debug2("which() found '%s' at %s" % (file, rv))
# else:
# debug2("which() could not find '%s' in %s" % (file, path))
# return rv
#
# def get_path():
# """Returns a string of paths separated by os.pathsep.
#
# Users might not have all of the programs sshuttle needs in their
# PATH variable (i.e., some programs might be in /sbin). Use PATH
# and a hardcoded set of paths to search through. This function is
# used by our which() and get_env() functions. If which() and the
# subprocess environments differ, programs that which() finds might
# not be found at run time (or vice versa).
# """
# path = []
# if "PATH" in os.environ:
# path += os.environ["PATH"].split(os.pathsep)
# # Python default paths.
# path += os.defpath.split(os.pathsep)
# # /sbin, etc are not in os.defpath and may not be in PATH either.
# # /bin/ and /usr/bin below are probably redundant.
# path += ['/bin', '/usr/bin', '/sbin', '/usr/sbin']
#
# # Remove duplicates. Not strictly necessary.
# path_dedup = []
# for i in path:
# if i not in path_dedup:
# path_dedup.append(i)
#
# return os.pathsep.join(path_dedup)
#
# class Fatal(Exception):
# pass
. Output only the next line. | raise Fatal("Failed to find '%s' in path %s" % (argv[0], get_path())) |
Predict the next line for this snippet: <|code_start|>
POLL_TIME = 60 * 15
NETSTAT_POLL_TIME = 30
CACHEFILE = os.path.expanduser('~/.sshuttle.hosts')
# Have we already failed to write CACHEFILE?
CACHE_WRITE_FAILED = False
hostnames = {}
queue = {}
try:
null = open(os.devnull, 'wb')
except IOError:
_, e = sys.exc_info()[:2]
<|code_end|>
with the help of current file imports:
import time
import socket
import re
import select
import errno
import os
import sys
import platform
import subprocess as ssubprocess
import sshuttle.helpers as helpers
from sshuttle.helpers import log, debug1, debug2, debug3, get_env
and context from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
, which may contain function names, class names, or code. Output only the next line. | log('warning: %s' % e) |
Continue the code snippet: <|code_start|> % CACHEFILE)
return
for line in f:
words = line.strip().split(',')
if len(words) == 2:
(name, ip) = words
name = re.sub(r'[^-\w\.]', '-', name).strip()
# Remove characters that shouldn't be in IP
ip = re.sub(r'[^0-9.]', '', ip).strip()
if name and ip:
found_host(name, ip)
def found_host(name, ip):
"""The provided name maps to the given IP. Add the host to the
hostnames list, send the host to the sshuttle client via
stdout, and write the host to the cache file.
"""
hostname = re.sub(r'\..*', '', name)
hostname = re.sub(r'[^-\w\.]', '_', hostname)
if (ip.startswith('127.') or ip.startswith('255.') or
hostname == 'localhost'):
return
if hostname != name:
found_host(hostname, ip)
oldip = hostnames.get(name)
if oldip != ip:
hostnames[name] = ip
<|code_end|>
. Use current file imports:
import time
import socket
import re
import select
import errno
import os
import sys
import platform
import subprocess as ssubprocess
import sshuttle.helpers as helpers
from sshuttle.helpers import log, debug1, debug2, debug3, get_env
and context (classes, functions, or code) from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
. Output only the next line. | debug1('Found: %s: %s' % (name, ip)) |
Predict the next line after this snippet: <|code_start|> ip = re.sub(r'[^0-9.]', '', ip).strip()
if name and ip:
found_host(name, ip)
def found_host(name, ip):
"""The provided name maps to the given IP. Add the host to the
hostnames list, send the host to the sshuttle client via
stdout, and write the host to the cache file.
"""
hostname = re.sub(r'\..*', '', name)
hostname = re.sub(r'[^-\w\.]', '_', hostname)
if (ip.startswith('127.') or ip.startswith('255.') or
hostname == 'localhost'):
return
if hostname != name:
found_host(hostname, ip)
oldip = hostnames.get(name)
if oldip != ip:
hostnames[name] = ip
debug1('Found: %s: %s' % (name, ip))
sys.stdout.write('%s,%s\n' % (name, ip))
write_host_cache()
def _check_etc_hosts():
"""If possible, read /etc/hosts to find hosts."""
filename = '/etc/hosts'
<|code_end|>
using the current file's imports:
import time
import socket
import re
import select
import errno
import os
import sys
import platform
import subprocess as ssubprocess
import sshuttle.helpers as helpers
from sshuttle.helpers import log, debug1, debug2, debug3, get_env
and any relevant context from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
. Output only the next line. | debug2(' > Reading %s on remote host' % filename) |
Predict the next line for this snippet: <|code_start|> hostname = re.sub(r'\..*', '', name)
hostname = re.sub(r'[^-\w\.]', '_', hostname)
if (ip.startswith('127.') or ip.startswith('255.') or
hostname == 'localhost'):
return
if hostname != name:
found_host(hostname, ip)
oldip = hostnames.get(name)
if oldip != ip:
hostnames[name] = ip
debug1('Found: %s: %s' % (name, ip))
sys.stdout.write('%s,%s\n' % (name, ip))
write_host_cache()
def _check_etc_hosts():
"""If possible, read /etc/hosts to find hosts."""
filename = '/etc/hosts'
debug2(' > Reading %s on remote host' % filename)
try:
for line in open(filename):
line = re.sub(r'#.*', '', line) # remove comments
words = line.strip().split()
if not words:
continue
ip = words[0]
if _is_ip(ip):
names = words[1:]
<|code_end|>
with the help of current file imports:
import time
import socket
import re
import select
import errno
import os
import sys
import platform
import subprocess as ssubprocess
import sshuttle.helpers as helpers
from sshuttle.helpers import log, debug1, debug2, debug3, get_env
and context from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
, which may contain function names, class names, or code. Output only the next line. | debug3('< %s %r' % (ip, names)) |
Next line prediction: <|code_start|>def _check_revdns(ip):
"""Use reverse DNS to try to get hostnames from an IP addresses."""
debug2(' > rev: %s' % ip)
try:
r = socket.gethostbyaddr(ip)
debug3('< %s' % r[0])
check_host(r[0])
found_host(r[0], ip)
except (OSError, socket.error, UnicodeError):
# This case is expected to occur regularly.
# debug3('< %s gethostbyaddr failed on remote host' % ip)
pass
def _check_dns(hostname):
debug2(' > dns: %s' % hostname)
try:
ip = socket.gethostbyname(hostname)
debug3('< %s' % ip)
check_host(ip)
found_host(hostname, ip)
except (socket.gaierror, UnicodeError):
pass
def _check_netstat():
debug2(' > netstat')
argv = ['netstat', '-n']
try:
p = ssubprocess.Popen(argv, stdout=ssubprocess.PIPE, stderr=null,
<|code_end|>
. Use current file imports:
(import time
import socket
import re
import select
import errno
import os
import sys
import platform
import subprocess as ssubprocess
import sshuttle.helpers as helpers
from sshuttle.helpers import log, debug1, debug2, debug3, get_env)
and context including class names, function names, or small code snippets from other files:
# Path: sshuttle/helpers.py
# def log(s):
# global logprefix
# try:
# sys.stdout.flush()
# # Put newline at end of string if line doesn't have one.
# if not s.endswith("\n"):
# s = s+"\n"
#
# prefix = logprefix
# s = s.rstrip("\n")
# for line in s.split("\n"):
# # We output with \r\n instead of \n because when we use
# # sudo with the use_pty option, the firewall process, the
# # other processes printing to the terminal will have the
# # \n move to the next line, but they will fail to reset
# # cursor to the beginning of the line. Printing output
# # with \r\n endings fixes that problem and does not appear
# # to cause problems elsewhere.
# sys.stderr.write(prefix + line + "\r\n")
# prefix = " "
# sys.stderr.flush()
# except IOError:
# # this could happen if stderr gets forcibly disconnected, eg. because
# # our tty closes. That sucks, but it's no reason to abort the program.
# pass
#
# def debug1(s):
# if verbose >= 1:
# log(s)
#
# def debug2(s):
# if verbose >= 2:
# log(s)
#
# def debug3(s):
# if verbose >= 3:
# log(s)
#
# def get_env():
# """An environment for sshuttle subprocesses. See get_path()."""
# env = {
# 'PATH': get_path(),
# 'LC_ALL': "C",
# }
# return env
. Output only the next line. | env=get_env()) |
Here is a snippet: <|code_start|> Non-existing profiles shouldn't be found
:param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
assert '1ced@4c41.a936' not in testdata
assert profiles.Profiles.get_by_email('1ced@4c41.a936') is None
def test_get_by_email(dbsession): # pylint: disable=unused-argument
""" Create Profiles, and then fetch them by email address. """
profile = profiles.Profiles(full_name='7cfeb824 a59fafe0f656', email='2c32@4fc0.beec')
# Unsaved profiles shouldn't be found
assert profiles.Profiles.get_by_email('2c32@4fc0.beec') is None
profile.save()
# Now it can be found.
assert profiles.Profiles.get_by_email('2c32@4fc0.beec') == profile
def test_login_relation(dbsession): # pylint: disable=unused-argument
""" Profiles can have a Logins relation. """
profile = profiles.Profiles(full_name='4176898b 61d515c6e423', email='61b4@4a1d.9f2b')
login = logins.Logins(password='104d4cec-9425-4e37-9de2-242c6d772eea')
assert profile.login is None
profile.login = login
assert profile.login == login
def test_memberships_relation(dbsession):
""" Profiles can have Memberships relations. """
<|code_end|>
. Write the next line using the current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import groups, logins, memberships, profiles
import sys
import warnings
import pytest
and context from other files:
# Path: models/groups.py
# class Groups(bases.BaseModel):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/memberships.py
# class Memberships(bases.BaseModel):
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
, which may include functions, classes, or code. Output only the next line. | group1 = groups.Groups(name='dfe5cf8f-1da7-4b70-aefb-8236cd894c5d') |
Predict the next line for this snippet: <|code_start|> :param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
# Include testdata so we know there are at least some records in table to search
assert profiles.Profiles.get_by_email('') is None
def test_get_by_email_unknonw(dbsession, testdata): # pylint: disable=unused-argument,redefined-outer-name
"""
Non-existing profiles shouldn't be found
:param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
assert '1ced@4c41.a936' not in testdata
assert profiles.Profiles.get_by_email('1ced@4c41.a936') is None
def test_get_by_email(dbsession): # pylint: disable=unused-argument
""" Create Profiles, and then fetch them by email address. """
profile = profiles.Profiles(full_name='7cfeb824 a59fafe0f656', email='2c32@4fc0.beec')
# Unsaved profiles shouldn't be found
assert profiles.Profiles.get_by_email('2c32@4fc0.beec') is None
profile.save()
# Now it can be found.
assert profiles.Profiles.get_by_email('2c32@4fc0.beec') == profile
def test_login_relation(dbsession): # pylint: disable=unused-argument
""" Profiles can have a Logins relation. """
profile = profiles.Profiles(full_name='4176898b 61d515c6e423', email='61b4@4a1d.9f2b')
<|code_end|>
with the help of current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import groups, logins, memberships, profiles
import sys
import warnings
import pytest
and context from other files:
# Path: models/groups.py
# class Groups(bases.BaseModel):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/memberships.py
# class Memberships(bases.BaseModel):
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
, which may contain function names, class names, or code. Output only the next line. | login = logins.Logins(password='104d4cec-9425-4e37-9de2-242c6d772eea') |
Predict the next line for this snippet: <|code_start|> :param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
assert '1ced@4c41.a936' not in testdata
assert profiles.Profiles.get_by_email('1ced@4c41.a936') is None
def test_get_by_email(dbsession): # pylint: disable=unused-argument
""" Create Profiles, and then fetch them by email address. """
profile = profiles.Profiles(full_name='7cfeb824 a59fafe0f656', email='2c32@4fc0.beec')
# Unsaved profiles shouldn't be found
assert profiles.Profiles.get_by_email('2c32@4fc0.beec') is None
profile.save()
# Now it can be found.
assert profiles.Profiles.get_by_email('2c32@4fc0.beec') == profile
def test_login_relation(dbsession): # pylint: disable=unused-argument
""" Profiles can have a Logins relation. """
profile = profiles.Profiles(full_name='4176898b 61d515c6e423', email='61b4@4a1d.9f2b')
login = logins.Logins(password='104d4cec-9425-4e37-9de2-242c6d772eea')
assert profile.login is None
profile.login = login
assert profile.login == login
def test_memberships_relation(dbsession):
""" Profiles can have Memberships relations. """
group1 = groups.Groups(name='dfe5cf8f-1da7-4b70-aefb-8236cd894c5d')
<|code_end|>
with the help of current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import groups, logins, memberships, profiles
import sys
import warnings
import pytest
and context from other files:
# Path: models/groups.py
# class Groups(bases.BaseModel):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/memberships.py
# class Memberships(bases.BaseModel):
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
, which may contain function names, class names, or code. Output only the next line. | membership1 = memberships.Memberships(group=group1) |
Predict the next line after this snippet: <|code_start|>"""
Tests for the Profiles Model
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
@pytest.fixture(scope='module')
def testdata(createdb):
"""
Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(str): List of emails for Profiles created.
"""
createdb.connect()
emails = []
data = ({'full_name': '4961e0b7 9acfd7e74533', 'email': '439b@47e7.ae97'},
{'full_name': '315ab3db 535af6a5b009', 'email': '8d3d@4719.8278'})
for record in data:
<|code_end|>
using the current file's imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import groups, logins, memberships, profiles
import sys
import warnings
import pytest
and any relevant context from other files:
# Path: models/groups.py
# class Groups(bases.BaseModel):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/memberships.py
# class Memberships(bases.BaseModel):
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
. Output only the next line. | profile = profiles.Profiles(full_name=record['full_name'], email=record['email']) |
Next line prediction: <|code_start|> """ Should convert Class Names to Database Table names. """
test_strings = {
'test': 'test',
'Test': 'test',
'TEST': 'test',
# https://stackoverflow.com/a/1176023
'CamelCase': 'camel_case',
'CamelCamelCase': 'camel_camel_case',
'Camel2Camel2Case': 'camel2_camel2_case',
'getHTTPResponseCode': 'get_http_response_code',
'get2HTTPResponseCode': 'get2_http_response_code',
'HTTPResponseCode': 'http_response_code',
'HTTPResponseCodeXYZ': 'http_response_code_xyz',
# https://gist.github.com/jaytaylor/3660565
'snakesOnAPlane': 'snakes_on_a_plane',
'SnakesOnAPlane': 'snakes_on_a_plane',
'snakes_on_a_plane': 'snakes_on_a_plane',
'IPhoneHysteria': 'i_phone_hysteria',
'iPhoneHysteria': 'i_phone_hysteria',
# These strings aren't camel case so it should do something weird:
'_Test': '__test',
'_test_Method': '_test__method',
'__test__Method': '__test___method',
'__CamelCase': '___camel_case',
'_Camel_Case': '__camel__case',
# This one might want a fix some day, but it is also bad camel case:
'getHTTPresponseCode': 'get_htt_presponse_code'
}
for camel, snake in test_strings.items():
<|code_end|>
. Use current file imports:
( from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from common import utilities
import sys
import warnings)
and context including class names, function names, or small code snippets from other files:
# Path: common/utilities.py
# def camel_to_delimiter_separated(name, glue='_'):
# def is_valid_email_address(address):
# def is_common_password(passwd):
. Output only the next line. | assert utilities.camel_to_delimiter_separated(camel) == snake |
Predict the next line for this snippet: <|code_start|>"""
Tests for our customized marshmallow Schema
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
<|code_end|>
with the help of current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
import sys
import datetime
import warnings
import marshmallow
import pytest
import sqlalchemy as sa
import sqlalchemy.orm as saorm
import ourmarshmallow
and context from other files:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
, which may contain function names, class names, or code. Output only the next line. | class FakeRelation(bases.BaseModel): |
Here is a snippet: <|code_start|>"""
Tests for the Base Model
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
<|code_end|>
. Write the next line using the current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
import sys
import datetime
import warnings
import pytest
import sqlalchemy as sa
import sqlalchemy_utils.functions
and context from other files:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
, which may include functions, classes, or code. Output only the next line. | class DummyBase(bases.Base): # pylint: disable=too-few-public-methods |
Based on the snippet: <|code_start|>"""
Tests for Relationship endpoints.
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
<|code_end|>
, predict the immediate next line with the help of imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
from ourapi.exceptions import Conflict, NotFound
import sys
import datetime
import warnings
import marshmallow
import pytest
import sqlalchemy as sa
import ourapi
import ourmarshmallow
and context (classes, functions, sometimes code) from other files:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
#
# Path: ourapi/exceptions.py
# class Conflict(JSONAPIError, werkzeug.exceptions.Conflict):
# """ 409 Conflict: fails server unique constraint or id issues. """
# pass
#
# class NotFound(JSONAPIError, werkzeug.exceptions.NotFound):
# """ 404 Not Found: Resource doesn't exist. """
# pass
. Output only the next line. | class Departments(bases.BaseModel): |
Given the code snippet: <|code_start|> Remove the parent relationship of a Department.
:param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
resource = ParentRelationship()
response = resource.get(20)
assert response == {'data': {'id': '10', 'type': 'departments'},
'links': {'related': '/departments/20/parent',
'self': '/departments/20/relationships/parent'}}
# Change parent from 10 to None
patch_data = {'data': None}
response, code = resource.patch(20, patch_data)
assert response is None
assert code == 204
response = resource.get(20)
assert response == {'data': None,
'links': {'related': '/departments/20/parent',
'self': '/departments/20/relationships/parent'}}
def test_update_one_type_mismatch_relationship(dbsession, testdata): # pylint: disable=unused-argument,redefined-outer-name,invalid-name
"""
Raise a Conflict exception when the relationship type doesn't match schema for relationship.
:param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
resource = ParentRelationship()
patch_data = {'data': {'id': '10', 'type': 'bad-type'}}
<|code_end|>
, generate the next line using the imports in this file:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
from ourapi.exceptions import Conflict, NotFound
import sys
import datetime
import warnings
import marshmallow
import pytest
import sqlalchemy as sa
import ourapi
import ourmarshmallow
and context (functions, classes, or occasionally code) from other files:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
#
# Path: ourapi/exceptions.py
# class Conflict(JSONAPIError, werkzeug.exceptions.Conflict):
# """ 409 Conflict: fails server unique constraint or id issues. """
# pass
#
# class NotFound(JSONAPIError, werkzeug.exceptions.NotFound):
# """ 404 Not Found: Resource doesn't exist. """
# pass
. Output only the next line. | with pytest.raises(Conflict): |
Given the code snippet: <|code_start|> :param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
resource = ChildrenRelationship()
response = resource.get(22)
# Just above this section is an example a related resource request returning nothing:
# http://jsonapi.org/format/#fetching-resources-responses-404
assert response == {'data': [], 'links': {'related': '/departments/22/children',
'self': '/departments/22/relationships/children'}}
def test_read_to_many_relationship(dbsession, testdata): # pylint: disable=unused-argument,redefined-outer-name
"""
Read a to many relationships.
:param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
resource = ChildrenRelationship()
response = resource.get(20)
assert response == {'data': [{'id': '21', 'type': 'departments'},
{'id': '22', 'type': 'departments'}],
'links': {'related': '/departments/20/children',
'self': '/departments/20/relationships/children'}}
def test_model_missing_relationship(dbsession, testdata): # pylint: disable=unused-argument,redefined-outer-name
"""
Model ID 999 doesn't exist so this should return a 404 Not Found exception.
:param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
resource = ChildrenRelationship()
<|code_end|>
, generate the next line using the imports in this file:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
from ourapi.exceptions import Conflict, NotFound
import sys
import datetime
import warnings
import marshmallow
import pytest
import sqlalchemy as sa
import ourapi
import ourmarshmallow
and context (functions, classes, or occasionally code) from other files:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
#
# Path: ourapi/exceptions.py
# class Conflict(JSONAPIError, werkzeug.exceptions.Conflict):
# """ 409 Conflict: fails server unique constraint or id issues. """
# pass
#
# class NotFound(JSONAPIError, werkzeug.exceptions.NotFound):
# """ 404 Not Found: Resource doesn't exist. """
# pass
. Output only the next line. | with pytest.raises(NotFound): |
Given the code snippet: <|code_start|>"""
Tests for Related model endpoints.
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
<|code_end|>
, generate the next line using the imports in this file:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
from ourapi.exceptions import NotFound
import sys
import datetime
import warnings
import pytest
import sqlalchemy as sa
import ourapi
import ourmarshmallow
and context (functions, classes, or occasionally code) from other files:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
#
# Path: ourapi/exceptions.py
# class NotFound(JSONAPIError, werkzeug.exceptions.NotFound):
# """ 404 Not Found: Resource doesn't exist. """
# pass
. Output only the next line. | class Persons(bases.BaseModel): |
Given the following code snippet before the placeholder: <|code_start|> response = resource.get(20)
assert response == {'data': [{'attributes': {'name': 'Impossible Stand'},
'id': '21',
'links': {'self': '/persons/21'},
'meta': {'modified_at': '2017-08-14T17:50:19+00:00'},
# pylint: disable=line-too-long
'relationships': {'children': {'links': {'related': '/persons/21/children',
'self': '/persons/21/relationships/children'}},
'parent': {'links': {'related': '/persons/21/parent',
'self': '/persons/21/relationships/parent'}}},
'type': 'persons'},
{'attributes': {'name': 'Carry Cool'},
'id': '22',
'links': {'self': '/persons/22'},
'meta': {'modified_at': '2017-08-14T17:50:19+00:00'},
# pylint: disable=line-too-long
'relationships': {'children': {'links': {'related': '/persons/22/children',
'self': '/persons/22/relationships/children'}},
'parent': {'links': {'related': '/persons/22/parent',
'self': '/persons/22/relationships/parent'}}},
'type': 'persons'}],
'links': {'self': '/persons/20/children'}}
def test_model_missing_relation(dbsession, testdata): # pylint: disable=unused-argument,redefined-outer-name
"""
Model ID 999 doesn't exist so this should return a 404 Not Found exception.
:param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
:param list(str) testdata: pytest fixture listing test data tokens.
"""
resource = ChildrenRelation()
<|code_end|>
, predict the next line using imports from the current file:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
from ourapi.exceptions import NotFound
import sys
import datetime
import warnings
import pytest
import sqlalchemy as sa
import ourapi
import ourmarshmallow
and context including class names, function names, and sometimes code from other files:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
#
# Path: ourapi/exceptions.py
# class NotFound(JSONAPIError, werkzeug.exceptions.NotFound):
# """ 404 Not Found: Resource doesn't exist. """
# pass
. Output only the next line. | with pytest.raises(NotFound): |
Given snippet: <|code_start|>"""
Tests for our customized marshmallow-sqlalchemy converter to support JSONAPI Relationship fields.
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
import sys
import warnings
import sqlalchemy as sa
import sqlalchemy.orm as saorm
import ourmarshmallow
and context:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
which might include code, classes, or functions. Output only the next line. | class Nodes(bases.BaseModel): |
Using the snippet: <|code_start|>
class ModelConverter(marshmallow_sqlalchemy.ModelConverter):
""" Customize SQLAlchemy Model Converter to use JSON API Relationships. """
# property2field will convert the Relationship to a List field if the prop.direction.name in
# this mapping returns True. Hack to work around that since this mapping is only used there.
# https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/af8304a33bfc11468d9ddb6c96e183964806d637/marshmallow_sqlalchemy/convert.py#L131
DIRECTION_MAPPING = {
'MANYTOONE': False,
'MANYTOMANY': False,
'ONETOMANY': False,
}
def _get_field_class_for_property(self, prop):
""" Use our Relationship field type for SQLAlchemy relations instead. """
if hasattr(prop, 'direction'):
return Relationship
return super()._get_field_class_for_property(prop)
def _add_relationship_kwargs(self, kwargs, prop):
""" Customize the kwargs for Relationship field based on prop. """
# super()._add_relationship_kwargs(kwargs, prop)
# All Schema names should be based on Model name.
kwargs['schema'] = prop.mapper.class_.__name__ + 'Schema'
# If the relation uses a list then the Relationship is many
kwargs['many'] = prop.uselist
# JSONAPI type is calculated from Model name to kebab-case.
<|code_end|>
, determine the next line of code. You have imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from common import utilities
from .fields import Relationship
import sys
import marshmallow_sqlalchemy
and context (class names, function names, or code) available:
# Path: common/utilities.py
# def camel_to_delimiter_separated(name, glue='_'):
# def is_valid_email_address(address):
# def is_common_password(passwd):
#
# Path: ourmarshmallow/fields.py
# class Relationship(marshmallow_jsonapi.fields.Relationship, marshmallow_sqlalchemy.fields.Related):
# """
# Combine the marshmallow-jsonapi.fields.Relationship with marshmallow-sqlalchemy.fields.Related.
# """
# def __init__(self, parent_self_url='', relationship_name='', parent_model=None, **kwargs):
# """
# :param str parent_self_url: Used to calculate self_url and related_url from a parent schema.
# :param str relationship_name: Name of this relationship for self_url and related_url.
# :param models.bases.BaseModel parent_model: Model Class of Schema containing this field.
# """
# # Calculate our relationship URLs beased on the parent schema's self_url
# if parent_self_url and relationship_name and kwargs['self_url_kwargs']:
# kwargs['self_url'] = '{0}/relationships/{1}'.format(parent_self_url, relationship_name)
# kwargs['related_url'] = '{0}/{1}'.format(parent_self_url, relationship_name)
# kwargs['related_url_kwargs'] = kwargs['self_url_kwargs']
#
# # Set the class of the model for the schema containing this field.
# self.parent_model = parent_model
#
# super().__init__(**kwargs)
. Output only the next line. | kwargs['type_'] = utilities.camel_to_delimiter_separated(prop.mapper.class_.__name__, |
Next line prediction: <|code_start|>"""
Customized Marshmallow-SQLAlchemy ModelConverter to combine Related and Relationship fields.
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
class ModelConverter(marshmallow_sqlalchemy.ModelConverter):
""" Customize SQLAlchemy Model Converter to use JSON API Relationships. """
# property2field will convert the Relationship to a List field if the prop.direction.name in
# this mapping returns True. Hack to work around that since this mapping is only used there.
# https://github.com/marshmallow-code/marshmallow-sqlalchemy/blob/af8304a33bfc11468d9ddb6c96e183964806d637/marshmallow_sqlalchemy/convert.py#L131
DIRECTION_MAPPING = {
'MANYTOONE': False,
'MANYTOMANY': False,
'ONETOMANY': False,
}
def _get_field_class_for_property(self, prop):
""" Use our Relationship field type for SQLAlchemy relations instead. """
if hasattr(prop, 'direction'):
<|code_end|>
. Use current file imports:
( from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from common import utilities
from .fields import Relationship
import sys
import marshmallow_sqlalchemy)
and context including class names, function names, or small code snippets from other files:
# Path: common/utilities.py
# def camel_to_delimiter_separated(name, glue='_'):
# def is_valid_email_address(address):
# def is_common_password(passwd):
#
# Path: ourmarshmallow/fields.py
# class Relationship(marshmallow_jsonapi.fields.Relationship, marshmallow_sqlalchemy.fields.Related):
# """
# Combine the marshmallow-jsonapi.fields.Relationship with marshmallow-sqlalchemy.fields.Related.
# """
# def __init__(self, parent_self_url='', relationship_name='', parent_model=None, **kwargs):
# """
# :param str parent_self_url: Used to calculate self_url and related_url from a parent schema.
# :param str relationship_name: Name of this relationship for self_url and related_url.
# :param models.bases.BaseModel parent_model: Model Class of Schema containing this field.
# """
# # Calculate our relationship URLs beased on the parent schema's self_url
# if parent_self_url and relationship_name and kwargs['self_url_kwargs']:
# kwargs['self_url'] = '{0}/relationships/{1}'.format(parent_self_url, relationship_name)
# kwargs['related_url'] = '{0}/{1}'.format(parent_self_url, relationship_name)
# kwargs['related_url_kwargs'] = kwargs['self_url_kwargs']
#
# # Set the class of the model for the schema containing this field.
# self.parent_model = parent_model
#
# super().__init__(**kwargs)
. Output only the next line. | return Relationship |
Given the following code snippet before the placeholder: <|code_start|>"""
Configuration for py.tests. Does things like setup the database and flask app for individual tests.
https://gist.github.com/alexmic/7857543
"""
warnings.simplefilter("error") # Make All warnings errors while testing.
# Setup Stream logging for py.test so log messages get output on errors too.
# If something else sets up logging first then this won't trigger.
# For example: db.py calling logging.info() or such.
<|code_end|>
, predict the next line using imports from the current file:
import warnings
import pytest
import api
import models
from common import log
and context including class names, function names, and sometimes code from other files:
# Path: common/log.py
# class RainbowLogFormatter(logging.Formatter):
# class ContextFilter(logging.Filter): # pylint: disable=too-few-public-methods
# class PapertrailHandler(logging.handlers.SysLogHandler):
# def format(self, record):
# def filter(self, record):
# def __init__(self, *args, **kwargs):
# def init_logging(level=logging.INFO):
. Output only the next line. | log.init_logging() |
Given the code snippet: <|code_start|>"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
@pytest.fixture(scope='module')
def testdata(createdb):
"""
Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(str): List of tokens for AuthenticationTokens created.
"""
createdb.connect()
tokens = []
data = ({'full_name': '24c6e6a4 960f1df1d6ac', 'email': '7d26@4f1b.a38e',
'password': 'be4b80d3-a6f2-442e-b495-2161376423ab'},
{'full_name': '8ad0c442 92728ef096a4', 'email': '6594@4fe0.8d07',
'password': 'b72da3ad-9b28-4be1-b9b0-9d611d465c31'},
{'full_name': '5a61452b 2830a9f8c820', 'email': 'a26d@433d.be92',
'password': '69073f4c-6328-47de-80c5-ab09016c69aa'})
for record in data:
profile = profiles.Profiles(full_name=record['full_name'], email=record['email'])
login = logins.Logins(password=record['password'], profile=profile)
<|code_end|>
, generate the next line using the imports in this file:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import authentication_tokens as autht
from models import logins, profiles
import sys
import datetime
import re
import warnings
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: models/authentication_tokens.py
# class AuthenticationTokens(bases.BaseModel):
# def __init__(self, *args, **kwargs):
# def _expiration():
# def _gen_token():
# def get_by_token(cls, token):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
. Output only the next line. | token = autht.AuthenticationTokens(login=login) |
Continue the code snippet: <|code_start|>Tests for Authentication Tokens
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
@pytest.fixture(scope='module')
def testdata(createdb):
"""
Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(str): List of tokens for AuthenticationTokens created.
"""
createdb.connect()
tokens = []
data = ({'full_name': '24c6e6a4 960f1df1d6ac', 'email': '7d26@4f1b.a38e',
'password': 'be4b80d3-a6f2-442e-b495-2161376423ab'},
{'full_name': '8ad0c442 92728ef096a4', 'email': '6594@4fe0.8d07',
'password': 'b72da3ad-9b28-4be1-b9b0-9d611d465c31'},
{'full_name': '5a61452b 2830a9f8c820', 'email': 'a26d@433d.be92',
'password': '69073f4c-6328-47de-80c5-ab09016c69aa'})
for record in data:
profile = profiles.Profiles(full_name=record['full_name'], email=record['email'])
<|code_end|>
. Use current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import authentication_tokens as autht
from models import logins, profiles
import sys
import datetime
import re
import warnings
import pytest
and context (classes, functions, or code) from other files:
# Path: models/authentication_tokens.py
# class AuthenticationTokens(bases.BaseModel):
# def __init__(self, *args, **kwargs):
# def _expiration():
# def _gen_token():
# def get_by_token(cls, token):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
. Output only the next line. | login = logins.Logins(password=record['password'], profile=profile) |
Predict the next line after this snippet: <|code_start|>"""
Tests for Authentication Tokens
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
@pytest.fixture(scope='module')
def testdata(createdb):
"""
Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(str): List of tokens for AuthenticationTokens created.
"""
createdb.connect()
tokens = []
data = ({'full_name': '24c6e6a4 960f1df1d6ac', 'email': '7d26@4f1b.a38e',
'password': 'be4b80d3-a6f2-442e-b495-2161376423ab'},
{'full_name': '8ad0c442 92728ef096a4', 'email': '6594@4fe0.8d07',
'password': 'b72da3ad-9b28-4be1-b9b0-9d611d465c31'},
{'full_name': '5a61452b 2830a9f8c820', 'email': 'a26d@433d.be92',
'password': '69073f4c-6328-47de-80c5-ab09016c69aa'})
for record in data:
<|code_end|>
using the current file's imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import authentication_tokens as autht
from models import logins, profiles
import sys
import datetime
import re
import warnings
import pytest
and any relevant context from other files:
# Path: models/authentication_tokens.py
# class AuthenticationTokens(bases.BaseModel):
# def __init__(self, *args, **kwargs):
# def _expiration():
# def _gen_token():
# def get_by_token(cls, token):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
. Output only the next line. | profile = profiles.Profiles(full_name=record['full_name'], email=record['email']) |
Predict the next line after this snippet: <|code_start|>"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
@pytest.fixture(scope='module')
def testdata(createdb):
"""
Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(str): List of tokens for ForgotPasswordTokens created.
"""
createdb.connect()
tokens = []
data = ({'full_name': 'df8df1a4 11162dcd40bb', 'email': 'c7fe@4a45.96d0',
'password': '83b6143e-1a75-4e31-abcf-c081b0176c28'},
{'full_name': '61c12783 784c62ee9e56', 'email': '7a58@438f.859e',
'password': '2faf78ca-0481-4cfe-8273-64de78690acc'},
{'full_name': '8e75abf5 4ab60edd1e23', 'email': '713e@4723.bc7a',
'password': '33df41f1-880f-44e2-bc89-7e111cc6a318'})
for record in data:
profile = profiles.Profiles(full_name=record['full_name'], email=record['email'])
login = logins.Logins(password=record['password'], profile=profile)
<|code_end|>
using the current file's imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import forgot_password_tokens as fpt
from models import logins, profiles
import sys
import datetime
import re
import warnings
import pytest
and any relevant context from other files:
# Path: models/forgot_password_tokens.py
# class ForgotPasswordTokens(bases.BaseModel):
# def __init__(self, *args, **kwargs):
# def _expiration():
# def _gen_token():
# def get_by_token(cls, token):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
. Output only the next line. | token = fpt.ForgotPasswordTokens(login=login) |
Continue the code snippet: <|code_start|>Tests for Forgot Password Tokens
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
@pytest.fixture(scope='module')
def testdata(createdb):
"""
Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(str): List of tokens for ForgotPasswordTokens created.
"""
createdb.connect()
tokens = []
data = ({'full_name': 'df8df1a4 11162dcd40bb', 'email': 'c7fe@4a45.96d0',
'password': '83b6143e-1a75-4e31-abcf-c081b0176c28'},
{'full_name': '61c12783 784c62ee9e56', 'email': '7a58@438f.859e',
'password': '2faf78ca-0481-4cfe-8273-64de78690acc'},
{'full_name': '8e75abf5 4ab60edd1e23', 'email': '713e@4723.bc7a',
'password': '33df41f1-880f-44e2-bc89-7e111cc6a318'})
for record in data:
profile = profiles.Profiles(full_name=record['full_name'], email=record['email'])
<|code_end|>
. Use current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import forgot_password_tokens as fpt
from models import logins, profiles
import sys
import datetime
import re
import warnings
import pytest
and context (classes, functions, or code) from other files:
# Path: models/forgot_password_tokens.py
# class ForgotPasswordTokens(bases.BaseModel):
# def __init__(self, *args, **kwargs):
# def _expiration():
# def _gen_token():
# def get_by_token(cls, token):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
. Output only the next line. | login = logins.Logins(password=record['password'], profile=profile) |
Next line prediction: <|code_start|>"""
Tests for Forgot Password Tokens
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
@pytest.fixture(scope='module')
def testdata(createdb):
"""
Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(str): List of tokens for ForgotPasswordTokens created.
"""
createdb.connect()
tokens = []
data = ({'full_name': 'df8df1a4 11162dcd40bb', 'email': 'c7fe@4a45.96d0',
'password': '83b6143e-1a75-4e31-abcf-c081b0176c28'},
{'full_name': '61c12783 784c62ee9e56', 'email': '7a58@438f.859e',
'password': '2faf78ca-0481-4cfe-8273-64de78690acc'},
{'full_name': '8e75abf5 4ab60edd1e23', 'email': '713e@4723.bc7a',
'password': '33df41f1-880f-44e2-bc89-7e111cc6a318'})
for record in data:
<|code_end|>
. Use current file imports:
( from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import forgot_password_tokens as fpt
from models import logins, profiles
import sys
import datetime
import re
import warnings
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: models/forgot_password_tokens.py
# class ForgotPasswordTokens(bases.BaseModel):
# def __init__(self, *args, **kwargs):
# def _expiration():
# def _gen_token():
# def get_by_token(cls, token):
#
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
. Output only the next line. | profile = profiles.Profiles(full_name=record['full_name'], email=record['email']) |
Given snippet: <|code_start|>"""
Tests for the Base API Resource class
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
def test_required_schema():
""" Resources must have a schema. """
with pytest.raises(NotImplementedError):
resource.JsonApiResource()
class BadResource(resource.JsonApiResource):
""" Missing the schema parameter """
pass
with pytest.raises(NotImplementedError):
BadResource()
def test_new_resource():
""" Resources only need a schema. """
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
from ourapi import resource
import sys
import warnings
import pytest
import sqlalchemy as sa
import ourmarshmallow
and context:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
#
# Path: ourapi/resource.py
# class JsonApiResource(base.BaseJsonApiResource):
# def __new__(cls):
# def _details(self, model_id):
# def _get_model(self, model_id):
# def _list(self):
# def delete(self, model_id):
# def get(self, model_id=None):
# def patch(self, model_id, data):
# def post(self, data):
# def register(cls, api):
which might include code, classes, or functions. Output only the next line. | class OkModel(bases.BaseModel): |
Using the snippet: <|code_start|>"""
Tests for the Base API Resource class
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
def test_required_schema():
""" Resources must have a schema. """
with pytest.raises(NotImplementedError):
<|code_end|>
, determine the next line of code. You have imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
from ourapi import resource
import sys
import warnings
import pytest
import sqlalchemy as sa
import ourmarshmallow
and context (class names, function names, or code) available:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
#
# Path: ourapi/resource.py
# class JsonApiResource(base.BaseJsonApiResource):
# def __new__(cls):
# def _details(self, model_id):
# def _get_model(self, model_id):
# def _list(self):
# def delete(self, model_id):
# def get(self, model_id=None):
# def patch(self, model_id, data):
# def post(self, data):
# def register(cls, api):
. Output only the next line. | resource.JsonApiResource() |
Given snippet: <|code_start|>"""
Tests for the API ResourceList class
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
from ourapi.exceptions import Forbidden
import sys
import datetime
import warnings
import flask
import pytest
import sqlalchemy as sa
import ourapi
import ourmarshmallow
and context:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
#
# Path: ourapi/exceptions.py
# class Forbidden(JSONAPIError, werkzeug.exceptions.Forbidden):
# """ 403 Forbidden: unsupported request to create, update, delete resource or relationship. """
# pass
which might include code, classes, or functions. Output only the next line. | class Batteries(bases.BaseModel): |
Given the code snippet: <|code_start|> :param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
"""
resource = BatteriesResource()
# Need to create a flask app and context so post can generate the URL for new model.
test_app = flask.Flask(__name__)
test_app.add_url_rule('/batteries/<int:model_id>',
view_func=BatteriesResource.as_view(BatteriesResource.__name__))
post_data = {'data': {'attributes': {'charge': 88.96770429362424}, 'type': 'batteries'}}
with test_app.test_request_context():
response, code, headers = resource.post(post_data)
assert code == 201
assert headers == {'Location': '/batteries/1'}
assert response == {'data': {'attributes': {'charge': 88.96770429362424},
'id': '1',
'links': {'self': '/batteries/1'},
# Correct the timestamp, which we will assume is correct
'meta': {'modified_at': response['data']['meta']['modified_at']},
'type': 'batteries'},
'links': {'self': '/batteries/1'}}
def test_create_id_conflict(dbsession): # pylint: disable=unused-argument
"""
ourapi doesn't support client generated ids.
:param sqlalchemy.orm.session.Session dbsession: pytest fixture for database session
"""
resource = BatteriesResource()
post_data = {'data': {'attributes': {'charge': 67.88553490220708}, 'type': 'batteries',
'id': '50'}}
<|code_end|>
, generate the next line using the imports in this file:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from models import bases
from ourapi.exceptions import Forbidden
import sys
import datetime
import warnings
import flask
import pytest
import sqlalchemy as sa
import ourapi
import ourmarshmallow
and context (functions, classes, or occasionally code) from other files:
# Path: models/bases.py
# NO_VALUE = sa_symbol('NO_VALUE')
# class Base(object):
# class BaseModel(Base):
# def __repr__(self):
# def __str__(self):
# def __tablename__(cls): # pylint: disable=no-self-argument
# def delete(self):
# def _prepare_conditions(cls, conditions):
# def get_all(cls, conditions=None):
# def get_by_pk(cls, the_id):
# def save(self, flush=False):
#
# Path: ourapi/exceptions.py
# class Forbidden(JSONAPIError, werkzeug.exceptions.Forbidden):
# """ 403 Forbidden: unsupported request to create, update, delete resource or relationship. """
# pass
. Output only the next line. | with pytest.raises(Forbidden) as excinfo: |
Based on the snippet: <|code_start|>"""
Tests for the database module
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
def test_env():
""" Default environment should be dev. """
assert not os.environ.get('ENV') # First confirm that there isn't an ENV set.
<|code_end|>
, predict the immediate next line with the help of imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.engine.base import Engine
from sqlalchemy.orm.scoping import scoped_session
from models import db
import sys
import os
import warnings
and context (classes, functions, sometimes code) from other files:
# Path: models/db.py
# CONNECTIONS = {
# 'dev': 'postgresql://api@localhost/saas_dev',
# # 'dev': 'mysql+pymysql://root@localhost/saas_dev?charset=utf8mb4',
# 'stage': 'postgresql://api@localhost/saas_stage',
# 'prod': 'postgresql://api@localhost/saas_prod'
# }
# ENV = os.environ.get('ENV', 'dev')
# ENGINE = sqlalchemy.create_engine(CONNECTIONS[ENV])
# FACTORY = _init()
# def _init():
# def add(instance):
# def close():
# def commit():
# def connect():
# def delete(instance):
# def flush():
# def query(entity):
# def rollback():
. Output only the next line. | assert db.ENV == 'dev' |
Continue the code snippet: <|code_start|>"""
Tests for the Logins Model
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
@pytest.fixture(scope='module')
def testdata(createdb):
"""
Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(str): List of emails for Logins created.
"""
createdb.connect()
emails = []
data = ({'full_name': 'f4d94fd2 c10282e403d0', 'email': 'fca7@485d.b169',
'password': '0c37f17b-4f89-4dce-a453-887b5acb9848'},
{'full_name': 'e3391b5 586ecf591968', 'email': 'ca14@4891.92d7',
'password': '7a1bb392-cc9c-4cde-8c9d-9ae2dc638bbf'})
for record in data:
profile = profiles.Profiles(full_name=record['full_name'], email=record['email'])
<|code_end|>
. Use current file imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import logins, profiles
import sys
import warnings
import pytest
and context (classes, functions, or code) from other files:
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
. Output only the next line. | login = logins.Logins(password=record['password'], profile=profile) |
Based on the snippet: <|code_start|>"""
Tests for the Logins Model
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
try:
except ImportError:
print("WARNING: Cannot Load builtins for py3 compatibility.", file=sys.stderr)
warnings.simplefilter("error") # Make All warnings errors while testing.
@pytest.fixture(scope='module')
def testdata(createdb):
"""
Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(str): List of emails for Logins created.
"""
createdb.connect()
emails = []
data = ({'full_name': 'f4d94fd2 c10282e403d0', 'email': 'fca7@485d.b169',
'password': '0c37f17b-4f89-4dce-a453-887b5acb9848'},
{'full_name': 'e3391b5 586ecf591968', 'email': 'ca14@4891.92d7',
'password': '7a1bb392-cc9c-4cde-8c9d-9ae2dc638bbf'})
for record in data:
<|code_end|>
, predict the immediate next line with the help of imports:
from builtins import * # pylint: disable=unused-wildcard-import,redefined-builtin,wildcard-import
from sqlalchemy.exc import IntegrityError
from models import logins, profiles
import sys
import warnings
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: models/logins.py
# class Logins(bases.BaseModel):
# def get_by_email(cls, email):
# def is_valid_password(self, password):
# def password(self):
# def password(self, value):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
#
# Path: models/profiles.py
# class Profiles(bases.BaseModel):
# def get_by_email(cls, email):
# def validate_email(self, key, address): # pylint: disable=unused-argument,no-self-use
. Output only the next line. | profile = profiles.Profiles(full_name=record['full_name'], email=record['email']) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.