Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>'''
CDC Device tempaltes
'''
cdc_control_interface_descriptor = Template(
name='cdc_control_interface_descriptor',
fields=[
SubDescriptor(
name='Standard interface descriptor',
<|code_end|>
, predict the next line using imports from the current file:
from umap2.dev.cdc import FunctionalDescriptor, CommunicationClassSubclassCodes
from umap2.core.usb_class import USBClass
from umap2.core.usb import DescriptorType
from kitty.model import UInt8, LE16, RandomBytes, BitField, Static
from kitty.model import Template, Repeat, List, Container, ForEach, OneOf
from kitty.model import ElementCount
from kitty.model import MutableField
from generic import SubDescriptor
and context including class names, function names, and sometimes code from other files:
# Path: umap2/dev/cdc.py
# class FunctionalDescriptor(USBCSInterface):
# '''
# The functional descriptors are sent as Class-Specific descriptors.
# '''
# Header = 0x00
# CM = 0x01 # Call Management Functional Descriptor.
# ACM = 0x02 # Abstract Control Management Functional Descriptor.
# DLM = 0x03 # Direct Line Management Functional Descriptor.
# TR = 0x04 # Telephone Ringer Functional Descriptor.
# TCLSRC = 0x05 # Telephone Call and Line State Reporting Capabilities Functional Descriptor.
# UN = 0x06 # Union Functional Descriptor
# CS = 0x07 # Country Selection Functional Descriptor
# TOM = 0x08 # Telephone Operational Modes Functional Descriptor
# USBT = 0x09 # USB Terminal Functional Descriptor
# NCT = 0x0A # Network Channel Terminal Descriptor
# PU = 0x0B # Protocol Unit Functional Descriptor
# EU = 0x0C # Extension Unit Functional Descriptor
# MCM = 0x0D # Multi-Channel Management Functional Descriptor
# CCM = 0x0E # CAPI Control Management Functional Descriptor
# EN = 0x0F # Ethernet Networking Functional Descriptor
# ATMN = 0x10 # ATM Networking Functional Descriptor
# WHCM = 0x11 # Wireless Handset Control Model Functional Descriptor
# MDLM = 0x12 # Mobile Direct Line Model Functional Descriptor
# MDLMD = 0x13 # MDLM Detail Functional Descriptor
# DMM = 0x14 # Device Management Model Functional Descriptor
# OBEX = 0x15 # OBEX Functional Descriptor
# CMDS = 0x16 # Command Set Functional Descriptor
# CMDSD = 0x17 # Command Set Detail Functional Descriptor
# TC = 0x18 # Telephone Control Model Functional Descriptor
# OBSEXSI = 0x19 # OBEX Service Identifier Functional Descriptor
# NCM = 0x1A # NCM Functional Descriptor
#
# def __init__(self, app, phy, subtype, cs_config):
# name = FunctionalDescriptor.get_subtype_name(subtype)
# cs_config = struct.pack('B', subtype) + cs_config
# super(FunctionalDescriptor, self).__init__(name, app, phy, cs_config)
#
# @classmethod
# def get_subtype_name(cls, subtype):
# for vn in dir(cls):
# if getattr(cls, vn) == subtype:
# return vn
# return 'FunctionalDescriptor-%02x' % subtype
#
# class CommunicationClassSubclassCodes:
# '''
# Subclass codes for the communication class,
# as defined in CDC120, table 4
# '''
#
# Reserved = 0x00
# DirectLineControlModel = 0x01
# AbstractControlModel = 0x02
# TelephoneControlModel = 0x03
# MultiChannelControlModel = 0x04
# CapiControlModel = 0x05
# EthernetNetworkingControlModel = 0x06
# AtmNetworkingControlModel = 0x07
# WirelessHandsetControlModel = 0x08
# DeviceManagement = 0x09
# MobileDirectLineModel = 0x0a
# Obex = 0x0b
# EthernetEmulationModel = 0x0c
# NetworkControlModel = 0x0d
# # 0x0e - 0x7f - reserved (future use)
# # 0x80 - 0xfe - reserved (vendor specific)
#
# Path: umap2/core/usb_class.py
# class USBClass(USBBaseActor):
# name = 'Class'
#
# Unspecified = 0x00
# Audio = 0x01
# CDC = 0x02
# HID = 0x03
# PID = 0x05
# Image = 0x06
# Printer = 0x07
# MassStorage = 0x08
# Hub = 0x09
# CDCData = 0x0a
# SmartCard = 0x0b
# ContentSecurity = 0x0d
# Video = 0x0e
# PHDC = 0x0f
# AudioVideo = 0x10
# Billboard = 0x11
# DiagnosticDevice = 0xdc
# WirelessController = 0xe0
# Miscellaneous = 0xed
# ApplicationSpecific = 0xfe
# VendorSpecific = 0xff
#
# def __init__(self, app, phy):
# '''
# :param app: Umap2 application
# :param phy: Physical connection
# '''
# super(USBClass, self).__init__(app, phy)
# self.setup_request_handlers()
# self.device = None
# self.interface = None
# self.endpoint = None
#
# def setup_request_handlers(self):
# self.setup_local_handlers()
# self.request_handlers = {
# x: self._global_handler for x in self.local_handlers
# }
#
# def setup_local_handlers(self):
# self.local_handlers = {}
#
# def _global_handler(self, req):
# handler = self.local_handlers[req.request]
# response = handler(req)
# if response is not None:
# self.phy.send_on_endpoint(0, response)
# self.usb_function_supported('class specific setup request received')
#
# def default_handler(self, req):
# self._global_handler(req)
#
# Path: umap2/core/usb.py
# class DescriptorType(object):
# device = 0x01
# configuration = 0x02
# string = 0x03
# interface = 0x04
# endpoint = 0x05
# device_qualifier = 0x06
# other_speed_configuration = 0x07
# interface_power = 0x08
# bos = 0x0f
# device_capability = 0x10
# hid = 0x21
# report = 0x22
# cs_interface = 0x24
# cs_endpoint = 0x25
# hub = 0x29
. Output only the next line. | descriptor_type=DescriptorType.interface, |
Predict the next line for this snippet: <|code_start|>'''
Physical layer for testing umap2 core and devices
'''
class SendDataEvent(TestEvent):
'''
Event that signify data that is sent on an endpoint
'''
def __init__(self, ep_num, data):
super(SendDataEvent, self).__init__()
self.ep_num = ep_num
self.data = data
class StallEp0Event(TestEvent):
pass
<|code_end|>
with the help of current file imports:
from umap2.phy.iphy import PhyInterface
from infra_event_handler import TestEvent
and context from other files:
# Path: umap2/phy/iphy.py
# class PhyInterface(object):
# '''
# This class specifies the API that a physical interface should conform to
# '''
#
# def __init__(self, app, name):
# '''
# :type app: :class:`~umap2.app.base.Umap2App`
# :param app: application instance
# '''
# self.app = app
# self.name = name
# self.logger = logging.getLogger('umap2')
# self.stop = False
# self.connected_device = None
#
# def connect(self, usb_device):
# '''
# Connect a USB device
#
# :type usb_device: :class:`~umap2.core.usb_class.USBClass`
# :param usb_device: USB device class
# '''
# self.connected_device = usb_device
#
# def disconnect(self):
# '''
# Disconnect a device.
# Once this function returns, the phy doesn't have a reference to the
# device.
#
# :return: the disconnected device (if was connected)
# '''
# if self.connected_device:
# self.info('Disconnected device %s' % self.connected_device.name)
# else:
# self.info('Disconnect called when already disconnected')
# dev = self.connected_device
# self.connected_device = None
# return dev
#
# def is_connected(self):
# return self.connected_device is not None
#
# def send_on_endpoint(self, ep_num, data):
# '''
# Send data on a specific endpoint
#
# :param ep_num: number of endpoint
# :param data: data to send
# '''
# raise NotImplementedError('should be implemented in subclass')
#
# def stall_ep0(self):
# '''
# Stalls control endpoint (0)
# '''
# raise NotImplementedError('should be implemented in subclass')
#
# def run(self):
# '''
# Handle USB requests
# '''
# raise NotImplementedError('should be implemented in subclass')
#
# def verbose(self, msg, *args, **kwargs):
# self.logger.verbose('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def debug(self, msg, *args, **kwargs):
# self.logger.debug('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def info(self, msg, *args, **kwargs):
# self.logger.info('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def warning(self, msg, *args, **kwargs):
# self.logger.warning('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def error(self, msg, *args, **kwargs):
# self.logger.error('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def critical(self, msg, *args, **kwargs):
# self.logger.critical('[%s] %s' % (self.name, msg), *args, **kwargs)
#
# def always(self, msg, *args, **kwargs):
# self.logger.always('[%s] %s' % (self.name, msg), *args, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | class TestPhy(PhyInterface): |
Next line prediction: <|code_start|>}
class PathAwareHookProxy:
"""
this helper wraps around hook callers
until pluggy supports fixingcalls, this one will do
it currently doesn't return full hook caller proxies for fixed hooks,
this may have to be changed later depending on bugs
"""
def __init__(self, hook_caller):
self.__hook_caller = hook_caller
def __dir__(self):
return dir(self.__hook_caller)
def __getattr__(self, key, _wraps=functools.wraps):
hook = getattr(self.__hook_caller, key)
if key not in imply_paths_hooks:
self.__dict__[key] = hook
return hook
else:
path_var, fspath_var = imply_paths_hooks[key]
@_wraps(hook)
def fixed_hook(**kw):
path_value: Optional[Path] = kw.pop(path_var, None)
<|code_end|>
. Use current file imports:
(import functools
import warnings
from pathlib import Path
from typing import Optional
from ..compat import LEGACY_PATH
from ..compat import legacy_path
from ..deprecated import HOOK_LEGACY_PATH_ARG
from _pytest.nodes import _check_path)
and context including class names, function names, or small code snippets from other files:
# Path: src/_pytest/compat.py
# LEGACY_PATH = py.path. local
#
# Path: src/_pytest/compat.py
# def legacy_path(path: Union[str, "os.PathLike[str]"]) -> LEGACY_PATH:
# """Internal wrapper to prepare lazy proxies for legacy_path instances"""
# return LEGACY_PATH(path)
#
# Path: src/_pytest/deprecated.py
# HOOK_LEGACY_PATH_ARG = UnformattedWarning(
# PytestRemovedIn8Warning,
# "The ({pylib_path_arg}: py.path.local) argument is deprecated, please use ({pathlib_path_arg}: pathlib.Path)\n"
# "see https://docs.pytest.org/en/latest/deprecations.html"
# "#py-path-local-arguments-for-hooks-replaced-with-pathlib-path",
# )
. Output only the next line. | fspath_value: Optional[LEGACY_PATH] = kw.pop(fspath_var, None) |
Using the snippet: <|code_start|> def __init__(self, hook_caller):
self.__hook_caller = hook_caller
def __dir__(self):
return dir(self.__hook_caller)
def __getattr__(self, key, _wraps=functools.wraps):
hook = getattr(self.__hook_caller, key)
if key not in imply_paths_hooks:
self.__dict__[key] = hook
return hook
else:
path_var, fspath_var = imply_paths_hooks[key]
@_wraps(hook)
def fixed_hook(**kw):
path_value: Optional[Path] = kw.pop(path_var, None)
fspath_value: Optional[LEGACY_PATH] = kw.pop(fspath_var, None)
if fspath_value is not None:
warnings.warn(
HOOK_LEGACY_PATH_ARG.format(
pylib_path_arg=fspath_var, pathlib_path_arg=path_var
),
stacklevel=2,
)
if path_value is not None:
if fspath_value is not None:
_check_path(path_value, fspath_value)
else:
<|code_end|>
, determine the next line of code. You have imports:
import functools
import warnings
from pathlib import Path
from typing import Optional
from ..compat import LEGACY_PATH
from ..compat import legacy_path
from ..deprecated import HOOK_LEGACY_PATH_ARG
from _pytest.nodes import _check_path
and context (class names, function names, or code) available:
# Path: src/_pytest/compat.py
# LEGACY_PATH = py.path. local
#
# Path: src/_pytest/compat.py
# def legacy_path(path: Union[str, "os.PathLike[str]"]) -> LEGACY_PATH:
# """Internal wrapper to prepare lazy proxies for legacy_path instances"""
# return LEGACY_PATH(path)
#
# Path: src/_pytest/deprecated.py
# HOOK_LEGACY_PATH_ARG = UnformattedWarning(
# PytestRemovedIn8Warning,
# "The ({pylib_path_arg}: py.path.local) argument is deprecated, please use ({pathlib_path_arg}: pathlib.Path)\n"
# "see https://docs.pytest.org/en/latest/deprecations.html"
# "#py-path-local-arguments-for-hooks-replaced-with-pathlib-path",
# )
. Output only the next line. | fspath_value = legacy_path(path_value) |
Here is a snippet: <|code_start|>class PathAwareHookProxy:
"""
this helper wraps around hook callers
until pluggy supports fixingcalls, this one will do
it currently doesn't return full hook caller proxies for fixed hooks,
this may have to be changed later depending on bugs
"""
def __init__(self, hook_caller):
self.__hook_caller = hook_caller
def __dir__(self):
return dir(self.__hook_caller)
def __getattr__(self, key, _wraps=functools.wraps):
hook = getattr(self.__hook_caller, key)
if key not in imply_paths_hooks:
self.__dict__[key] = hook
return hook
else:
path_var, fspath_var = imply_paths_hooks[key]
@_wraps(hook)
def fixed_hook(**kw):
path_value: Optional[Path] = kw.pop(path_var, None)
fspath_value: Optional[LEGACY_PATH] = kw.pop(fspath_var, None)
if fspath_value is not None:
warnings.warn(
<|code_end|>
. Write the next line using the current file imports:
import functools
import warnings
from pathlib import Path
from typing import Optional
from ..compat import LEGACY_PATH
from ..compat import legacy_path
from ..deprecated import HOOK_LEGACY_PATH_ARG
from _pytest.nodes import _check_path
and context from other files:
# Path: src/_pytest/compat.py
# LEGACY_PATH = py.path. local
#
# Path: src/_pytest/compat.py
# def legacy_path(path: Union[str, "os.PathLike[str]"]) -> LEGACY_PATH:
# """Internal wrapper to prepare lazy proxies for legacy_path instances"""
# return LEGACY_PATH(path)
#
# Path: src/_pytest/deprecated.py
# HOOK_LEGACY_PATH_ARG = UnformattedWarning(
# PytestRemovedIn8Warning,
# "The ({pylib_path_arg}: py.path.local) argument is deprecated, please use ({pathlib_path_arg}: pathlib.Path)\n"
# "see https://docs.pytest.org/en/latest/deprecations.html"
# "#py-path-local-arguments-for-hooks-replaced-with-pathlib-path",
# )
, which may include functions, classes, or code. Output only the next line. | HOOK_LEGACY_PATH_ARG.format( |
Based on the snippet: <|code_start|> f_name = func.__name__
_, lineno = getfslineno(func)
raise Collector.CollectError(
"Empty parameter set in '%s' at line %d" % (f_name, lineno + 1)
)
else:
raise LookupError(requested_mark)
return mark
class ParameterSet(NamedTuple):
values: Sequence[Union[object, NotSetType]]
marks: Collection[Union["MarkDecorator", "Mark"]]
id: Optional[str]
@classmethod
def param(
cls,
*values: object,
marks: Union["MarkDecorator", Collection[Union["MarkDecorator", "Mark"]]] = (),
id: Optional[str] = None,
) -> "ParameterSet":
if isinstance(marks, MarkDecorator):
marks = (marks,)
else:
assert isinstance(marks, collections.abc.Collection)
if id is not None:
if not isinstance(id, str):
raise TypeError(f"Expected id to be a string, got {type(id)}: {id!r}")
<|code_end|>
, predict the immediate next line with the help of imports:
import collections.abc
import inspect
import warnings
import attr
from typing import Any
from typing import Callable
from typing import Collection
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Mapping
from typing import MutableMapping
from typing import NamedTuple
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
from .._code import getfslineno
from ..compat import ascii_escaped
from ..compat import final
from ..compat import NOTSET
from ..compat import NotSetType
from _pytest.config import Config
from _pytest.deprecated import check_ispytest
from _pytest.outcomes import fail
from _pytest.warning_types import PytestUnknownMarkWarning
from ..nodes import Node
from ..nodes import Collector
from _pytest.scope import _ScopeName
and context (classes, functions, sometimes code) from other files:
# Path: src/_pytest/compat.py
# def ascii_escaped(val: Union[bytes, str]) -> str:
# r"""If val is pure ASCII, return it as an str, otherwise, escape
# bytes objects into a sequence of escaped bytes:
#
# b'\xc3\xb4\xc5\xd6' -> r'\xc3\xb4\xc5\xd6'
#
# and escapes unicode objects into a sequence of escaped unicode
# ids, e.g.:
#
# r'4\nV\U00043efa\x0eMXWB\x1e\u3028\u15fd\xcd\U0007d944'
#
# Note:
# The obvious "v.decode('unicode-escape')" will return
# valid UTF-8 unicode if it finds them in bytes, but we
# want to return escaped bytes for any byte, even if they match
# a UTF-8 string.
# """
# if isinstance(val, bytes):
# ret = _bytes_to_ascii(val)
# else:
# ret = val.encode("unicode_escape").decode("ascii")
# return _translate_non_printable(ret)
#
# Path: src/_pytest/compat.py
# def final(f):
# return f
#
# Path: src/_pytest/compat.py
# NOTSET: "Final" = NotSetType.token # noqa: E305
#
# Path: src/_pytest/compat.py
# class NotSetType(enum.Enum):
# token = 0
. Output only the next line. | id = ascii_escaped(id) |
Here is a snippet: <|code_start|> if parameters:
# Check all parameter sets have the correct number of values.
for param in parameters:
if len(param.values) != len(argnames):
msg = (
'{nodeid}: in "parametrize" the number of names ({names_len}):\n'
" {names}\n"
"must be equal to the number of values ({values_len}):\n"
" {values}"
)
fail(
msg.format(
nodeid=nodeid,
values=param.values,
names=argnames,
names_len=len(argnames),
values_len=len(param.values),
),
pytrace=False,
)
else:
# Empty parameter set (likely computed at runtime): create a single
# parameter set with NOTSET values, with the "empty parameter set" mark applied to it.
mark = get_empty_parameterset_mark(config, argnames, func)
parameters.append(
ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)
)
return argnames, parameters
<|code_end|>
. Write the next line using the current file imports:
import collections.abc
import inspect
import warnings
import attr
from typing import Any
from typing import Callable
from typing import Collection
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Mapping
from typing import MutableMapping
from typing import NamedTuple
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
from .._code import getfslineno
from ..compat import ascii_escaped
from ..compat import final
from ..compat import NOTSET
from ..compat import NotSetType
from _pytest.config import Config
from _pytest.deprecated import check_ispytest
from _pytest.outcomes import fail
from _pytest.warning_types import PytestUnknownMarkWarning
from ..nodes import Node
from ..nodes import Collector
from _pytest.scope import _ScopeName
and context from other files:
# Path: src/_pytest/compat.py
# def ascii_escaped(val: Union[bytes, str]) -> str:
# r"""If val is pure ASCII, return it as an str, otherwise, escape
# bytes objects into a sequence of escaped bytes:
#
# b'\xc3\xb4\xc5\xd6' -> r'\xc3\xb4\xc5\xd6'
#
# and escapes unicode objects into a sequence of escaped unicode
# ids, e.g.:
#
# r'4\nV\U00043efa\x0eMXWB\x1e\u3028\u15fd\xcd\U0007d944'
#
# Note:
# The obvious "v.decode('unicode-escape')" will return
# valid UTF-8 unicode if it finds them in bytes, but we
# want to return escaped bytes for any byte, even if they match
# a UTF-8 string.
# """
# if isinstance(val, bytes):
# ret = _bytes_to_ascii(val)
# else:
# ret = val.encode("unicode_escape").decode("ascii")
# return _translate_non_printable(ret)
#
# Path: src/_pytest/compat.py
# def final(f):
# return f
#
# Path: src/_pytest/compat.py
# NOTSET: "Final" = NotSetType.token # noqa: E305
#
# Path: src/_pytest/compat.py
# class NotSetType(enum.Enum):
# token = 0
, which may include functions, classes, or code. Output only the next line. | @final |
Here is a snippet: <|code_start|> ) -> Tuple[Union[List[str], Tuple[str, ...]], List["ParameterSet"]]:
argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)
parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)
del argvalues
if parameters:
# Check all parameter sets have the correct number of values.
for param in parameters:
if len(param.values) != len(argnames):
msg = (
'{nodeid}: in "parametrize" the number of names ({names_len}):\n'
" {names}\n"
"must be equal to the number of values ({values_len}):\n"
" {values}"
)
fail(
msg.format(
nodeid=nodeid,
values=param.values,
names=argnames,
names_len=len(argnames),
values_len=len(param.values),
),
pytrace=False,
)
else:
# Empty parameter set (likely computed at runtime): create a single
# parameter set with NOTSET values, with the "empty parameter set" mark applied to it.
mark = get_empty_parameterset_mark(config, argnames, func)
parameters.append(
<|code_end|>
. Write the next line using the current file imports:
import collections.abc
import inspect
import warnings
import attr
from typing import Any
from typing import Callable
from typing import Collection
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Mapping
from typing import MutableMapping
from typing import NamedTuple
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
from .._code import getfslineno
from ..compat import ascii_escaped
from ..compat import final
from ..compat import NOTSET
from ..compat import NotSetType
from _pytest.config import Config
from _pytest.deprecated import check_ispytest
from _pytest.outcomes import fail
from _pytest.warning_types import PytestUnknownMarkWarning
from ..nodes import Node
from ..nodes import Collector
from _pytest.scope import _ScopeName
and context from other files:
# Path: src/_pytest/compat.py
# def ascii_escaped(val: Union[bytes, str]) -> str:
# r"""If val is pure ASCII, return it as an str, otherwise, escape
# bytes objects into a sequence of escaped bytes:
#
# b'\xc3\xb4\xc5\xd6' -> r'\xc3\xb4\xc5\xd6'
#
# and escapes unicode objects into a sequence of escaped unicode
# ids, e.g.:
#
# r'4\nV\U00043efa\x0eMXWB\x1e\u3028\u15fd\xcd\U0007d944'
#
# Note:
# The obvious "v.decode('unicode-escape')" will return
# valid UTF-8 unicode if it finds them in bytes, but we
# want to return escaped bytes for any byte, even if they match
# a UTF-8 string.
# """
# if isinstance(val, bytes):
# ret = _bytes_to_ascii(val)
# else:
# ret = val.encode("unicode_escape").decode("ascii")
# return _translate_non_printable(ret)
#
# Path: src/_pytest/compat.py
# def final(f):
# return f
#
# Path: src/_pytest/compat.py
# NOTSET: "Final" = NotSetType.token # noqa: E305
#
# Path: src/_pytest/compat.py
# class NotSetType(enum.Enum):
# token = 0
, which may include functions, classes, or code. Output only the next line. | ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None) |
Predict the next line after this snippet: <|code_start|>
def get_empty_parameterset_mark(
config: Config, argnames: Sequence[str], func
) -> "MarkDecorator":
fs, lineno = getfslineno(func)
reason = "got empty parameter set %r, function %s at %s:%d" % (
argnames,
func.__name__,
fs,
lineno,
)
requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)
if requested_mark in ("", None, "skip"):
mark = MARK_GEN.skip(reason=reason)
elif requested_mark == "xfail":
mark = MARK_GEN.xfail(reason=reason, run=False)
elif requested_mark == "fail_at_collect":
f_name = func.__name__
_, lineno = getfslineno(func)
raise Collector.CollectError(
"Empty parameter set in '%s' at line %d" % (f_name, lineno + 1)
)
else:
raise LookupError(requested_mark)
return mark
class ParameterSet(NamedTuple):
<|code_end|>
using the current file's imports:
import collections.abc
import inspect
import warnings
import attr
from typing import Any
from typing import Callable
from typing import Collection
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Mapping
from typing import MutableMapping
from typing import NamedTuple
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
from .._code import getfslineno
from ..compat import ascii_escaped
from ..compat import final
from ..compat import NOTSET
from ..compat import NotSetType
from _pytest.config import Config
from _pytest.deprecated import check_ispytest
from _pytest.outcomes import fail
from _pytest.warning_types import PytestUnknownMarkWarning
from ..nodes import Node
from ..nodes import Collector
from _pytest.scope import _ScopeName
and any relevant context from other files:
# Path: src/_pytest/compat.py
# def ascii_escaped(val: Union[bytes, str]) -> str:
# r"""If val is pure ASCII, return it as an str, otherwise, escape
# bytes objects into a sequence of escaped bytes:
#
# b'\xc3\xb4\xc5\xd6' -> r'\xc3\xb4\xc5\xd6'
#
# and escapes unicode objects into a sequence of escaped unicode
# ids, e.g.:
#
# r'4\nV\U00043efa\x0eMXWB\x1e\u3028\u15fd\xcd\U0007d944'
#
# Note:
# The obvious "v.decode('unicode-escape')" will return
# valid UTF-8 unicode if it finds them in bytes, but we
# want to return escaped bytes for any byte, even if they match
# a UTF-8 string.
# """
# if isinstance(val, bytes):
# ret = _bytes_to_ascii(val)
# else:
# ret = val.encode("unicode_escape").decode("ascii")
# return _translate_non_printable(ret)
#
# Path: src/_pytest/compat.py
# def final(f):
# return f
#
# Path: src/_pytest/compat.py
# NOTSET: "Final" = NotSetType.token # noqa: E305
#
# Path: src/_pytest/compat.py
# class NotSetType(enum.Enum):
# token = 0
. Output only the next line. | values: Sequence[Union[object, NotSetType]] |
Given the following code snippet before the placeholder: <|code_start|> def for_config(cls, config: Config, *, _ispytest: bool = False) -> "Cache":
"""Create the Cache instance for a Config.
:meta private:
"""
check_ispytest(_ispytest)
cachedir = cls.cache_dir_from_config(config, _ispytest=True)
if config.getoption("cacheclear") and cachedir.is_dir():
cls.clear_cache(cachedir, _ispytest=True)
return cls(cachedir, config, _ispytest=True)
@classmethod
def clear_cache(cls, cachedir: Path, _ispytest: bool = False) -> None:
"""Clear the sub-directories used to hold cached directories and values.
:meta private:
"""
check_ispytest(_ispytest)
for prefix in (cls._CACHE_PREFIX_DIRS, cls._CACHE_PREFIX_VALUES):
d = cachedir / prefix
if d.is_dir():
rm_rf(d)
@staticmethod
def cache_dir_from_config(config: Config, *, _ispytest: bool = False) -> Path:
"""Get the path to the cache directory for a Config.
:meta private:
"""
check_ispytest(_ispytest)
<|code_end|>
, predict the next line using imports from the current file:
import json
import os
import attr
import warnings
from pathlib import Path
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import List
from typing import Optional
from typing import Set
from typing import Union
from .pathlib import resolve_from_str
from .pathlib import rm_rf
from .reports import CollectReport
from _pytest import nodes
from _pytest._io import TerminalWriter
from _pytest.compat import final
from _pytest.config import Config
from _pytest.config import ExitCode
from _pytest.config import hookimpl
from _pytest.config.argparsing import Parser
from _pytest.deprecated import check_ispytest
from _pytest.fixtures import fixture
from _pytest.fixtures import FixtureRequest
from _pytest.main import Session
from _pytest.python import Module
from _pytest.python import Package
from _pytest.reports import TestReport
from _pytest.warning_types import PytestCacheWarning
from _pytest.main import wrap_session
from pprint import pformat
and context including class names, function names, and sometimes code from other files:
# Path: src/_pytest/pathlib.py
# def resolve_from_str(input: str, rootpath: Path) -> Path:
# input = expanduser(input)
# input = expandvars(input)
# if isabs(input):
# return Path(input)
# else:
# return rootpath.joinpath(input)
#
# Path: src/_pytest/pathlib.py
# def rm_rf(path: Path) -> None:
# """Remove the path contents recursively, even if some elements
# are read-only."""
# path = ensure_extended_length_path(path)
# onerror = partial(on_rm_rf_error, start_path=path)
# shutil.rmtree(str(path), onerror=onerror)
#
# Path: src/_pytest/reports.py
# class CollectReport(BaseReport):
# """Collection report object.
#
# Reports can contain arbitrary extra attributes.
# """
#
# when = "collect"
#
# def __init__(
# self,
# nodeid: str,
# outcome: "Literal['passed', 'failed', 'skipped']",
# longrepr: Union[
# None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
# ],
# result: Optional[List[Union[Item, Collector]]],
# sections: Iterable[Tuple[str, str]] = (),
# **extra,
# ) -> None:
# #: Normalized collection nodeid.
# self.nodeid = nodeid
#
# #: Test outcome, always one of "passed", "failed", "skipped".
# self.outcome = outcome
#
# #: None or a failure representation.
# self.longrepr = longrepr
#
# #: The collected items and collection nodes.
# self.result = result or []
#
# #: Tuples of str ``(heading, content)`` with extra information
# #: for the test report. Used by pytest to add text captured
# #: from ``stdout``, ``stderr``, and intercepted logging events. May
# #: be used by other plugins to add arbitrary information to reports.
# self.sections = list(sections)
#
# self.__dict__.update(extra)
#
# @property
# def location(self):
# return (self.fspath, None, self.fspath)
#
# def __repr__(self) -> str:
# return "<CollectReport {!r} lenresult={} outcome={!r}>".format(
# self.nodeid, len(self.result), self.outcome
# )
. Output only the next line. | return resolve_from_str(config.getini("cache_dir"), config.rootpath) |
Predict the next line for this snippet: <|code_start|>
def __init__(
self, cachedir: Path, config: Config, *, _ispytest: bool = False
) -> None:
check_ispytest(_ispytest)
self._cachedir = cachedir
self._config = config
@classmethod
def for_config(cls, config: Config, *, _ispytest: bool = False) -> "Cache":
"""Create the Cache instance for a Config.
:meta private:
"""
check_ispytest(_ispytest)
cachedir = cls.cache_dir_from_config(config, _ispytest=True)
if config.getoption("cacheclear") and cachedir.is_dir():
cls.clear_cache(cachedir, _ispytest=True)
return cls(cachedir, config, _ispytest=True)
@classmethod
def clear_cache(cls, cachedir: Path, _ispytest: bool = False) -> None:
"""Clear the sub-directories used to hold cached directories and values.
:meta private:
"""
check_ispytest(_ispytest)
for prefix in (cls._CACHE_PREFIX_DIRS, cls._CACHE_PREFIX_VALUES):
d = cachedir / prefix
if d.is_dir():
<|code_end|>
with the help of current file imports:
import json
import os
import attr
import warnings
from pathlib import Path
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import List
from typing import Optional
from typing import Set
from typing import Union
from .pathlib import resolve_from_str
from .pathlib import rm_rf
from .reports import CollectReport
from _pytest import nodes
from _pytest._io import TerminalWriter
from _pytest.compat import final
from _pytest.config import Config
from _pytest.config import ExitCode
from _pytest.config import hookimpl
from _pytest.config.argparsing import Parser
from _pytest.deprecated import check_ispytest
from _pytest.fixtures import fixture
from _pytest.fixtures import FixtureRequest
from _pytest.main import Session
from _pytest.python import Module
from _pytest.python import Package
from _pytest.reports import TestReport
from _pytest.warning_types import PytestCacheWarning
from _pytest.main import wrap_session
from pprint import pformat
and context from other files:
# Path: src/_pytest/pathlib.py
# def resolve_from_str(input: str, rootpath: Path) -> Path:
# input = expanduser(input)
# input = expandvars(input)
# if isabs(input):
# return Path(input)
# else:
# return rootpath.joinpath(input)
#
# Path: src/_pytest/pathlib.py
# def rm_rf(path: Path) -> None:
# """Remove the path contents recursively, even if some elements
# are read-only."""
# path = ensure_extended_length_path(path)
# onerror = partial(on_rm_rf_error, start_path=path)
# shutil.rmtree(str(path), onerror=onerror)
#
# Path: src/_pytest/reports.py
# class CollectReport(BaseReport):
# """Collection report object.
#
# Reports can contain arbitrary extra attributes.
# """
#
# when = "collect"
#
# def __init__(
# self,
# nodeid: str,
# outcome: "Literal['passed', 'failed', 'skipped']",
# longrepr: Union[
# None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
# ],
# result: Optional[List[Union[Item, Collector]]],
# sections: Iterable[Tuple[str, str]] = (),
# **extra,
# ) -> None:
# #: Normalized collection nodeid.
# self.nodeid = nodeid
#
# #: Test outcome, always one of "passed", "failed", "skipped".
# self.outcome = outcome
#
# #: None or a failure representation.
# self.longrepr = longrepr
#
# #: The collected items and collection nodes.
# self.result = result or []
#
# #: Tuples of str ``(heading, content)`` with extra information
# #: for the test report. Used by pytest to add text captured
# #: from ``stdout``, ``stderr``, and intercepted logging events. May
# #: be used by other plugins to add arbitrary information to reports.
# self.sections = list(sections)
#
# self.__dict__.update(extra)
#
# @property
# def location(self):
# return (self.fspath, None, self.fspath)
#
# def __repr__(self) -> str:
# return "<CollectReport {!r} lenresult={} outcome={!r}>".format(
# self.nodeid, len(self.result), self.outcome
# )
, which may contain function names, class names, or code. Output only the next line. | rm_rf(d) |
Given the following code snippet before the placeholder: <|code_start|> try:
f = path.open("w")
except OSError:
self.warn("cache could not write path {path}", path=path, _ispytest=True)
else:
with f:
f.write(data)
def _ensure_supporting_files(self) -> None:
"""Create supporting files in the cache dir that are not really part of the cache."""
readme_path = self._cachedir / "README.md"
readme_path.write_text(README_CONTENT)
gitignore_path = self._cachedir.joinpath(".gitignore")
msg = "# Created by pytest automatically.\n*\n"
gitignore_path.write_text(msg, encoding="UTF-8")
cachedir_tag_path = self._cachedir.joinpath("CACHEDIR.TAG")
cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT)
class LFPluginCollWrapper:
def __init__(self, lfplugin: "LFPlugin") -> None:
self.lfplugin = lfplugin
self._collected_at_least_one_failure = False
@hookimpl(hookwrapper=True)
def pytest_make_collect_report(self, collector: nodes.Collector):
if isinstance(collector, Session):
out = yield
<|code_end|>
, predict the next line using imports from the current file:
import json
import os
import attr
import warnings
from pathlib import Path
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import List
from typing import Optional
from typing import Set
from typing import Union
from .pathlib import resolve_from_str
from .pathlib import rm_rf
from .reports import CollectReport
from _pytest import nodes
from _pytest._io import TerminalWriter
from _pytest.compat import final
from _pytest.config import Config
from _pytest.config import ExitCode
from _pytest.config import hookimpl
from _pytest.config.argparsing import Parser
from _pytest.deprecated import check_ispytest
from _pytest.fixtures import fixture
from _pytest.fixtures import FixtureRequest
from _pytest.main import Session
from _pytest.python import Module
from _pytest.python import Package
from _pytest.reports import TestReport
from _pytest.warning_types import PytestCacheWarning
from _pytest.main import wrap_session
from pprint import pformat
and context including class names, function names, and sometimes code from other files:
# Path: src/_pytest/pathlib.py
# def resolve_from_str(input: str, rootpath: Path) -> Path:
# input = expanduser(input)
# input = expandvars(input)
# if isabs(input):
# return Path(input)
# else:
# return rootpath.joinpath(input)
#
# Path: src/_pytest/pathlib.py
# def rm_rf(path: Path) -> None:
# """Remove the path contents recursively, even if some elements
# are read-only."""
# path = ensure_extended_length_path(path)
# onerror = partial(on_rm_rf_error, start_path=path)
# shutil.rmtree(str(path), onerror=onerror)
#
# Path: src/_pytest/reports.py
# class CollectReport(BaseReport):
# """Collection report object.
#
# Reports can contain arbitrary extra attributes.
# """
#
# when = "collect"
#
# def __init__(
# self,
# nodeid: str,
# outcome: "Literal['passed', 'failed', 'skipped']",
# longrepr: Union[
# None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
# ],
# result: Optional[List[Union[Item, Collector]]],
# sections: Iterable[Tuple[str, str]] = (),
# **extra,
# ) -> None:
# #: Normalized collection nodeid.
# self.nodeid = nodeid
#
# #: Test outcome, always one of "passed", "failed", "skipped".
# self.outcome = outcome
#
# #: None or a failure representation.
# self.longrepr = longrepr
#
# #: The collected items and collection nodes.
# self.result = result or []
#
# #: Tuples of str ``(heading, content)`` with extra information
# #: for the test report. Used by pytest to add text captured
# #: from ``stdout``, ``stderr``, and intercepted logging events. May
# #: be used by other plugins to add arbitrary information to reports.
# self.sections = list(sections)
#
# self.__dict__.update(extra)
#
# @property
# def location(self):
# return (self.fspath, None, self.fspath)
#
# def __repr__(self) -> str:
# return "<CollectReport {!r} lenresult={} outcome={!r}>".format(
# self.nodeid, len(self.result), self.outcome
# )
. Output only the next line. | res: CollectReport = out.get_result() |
Continue the code snippet: <|code_start|>
@dataclass
class Overlay:
center_x: float = 0.5
center_y: float = 0.5
angle: float = 0.0
scale: float = 0.25
def get_size(self, background_size: Dimensions) -> Dimensions:
background_width, background_height = background_size
dimension = min(
int(background_width * self.scale),
int(background_height * self.scale),
)
return dimension, dimension
def get_box(
self, background_size: Dimensions, foreground_size: Dimensions | None = None
<|code_end|>
. Use current file imports:
from dataclasses import dataclass
from ..types import Box, Dimensions
and context (classes, functions, or code) from other files:
# Path: app/types.py
. Output only the next line. | ) -> Box: |
Here is a snippet: <|code_start|>
@dataclass
class Overlay:
center_x: float = 0.5
center_y: float = 0.5
angle: float = 0.0
scale: float = 0.25
<|code_end|>
. Write the next line using the current file imports:
from dataclasses import dataclass
from ..types import Box, Dimensions
and context from other files:
# Path: app/types.py
, which may include functions, classes, or code. Output only the next line. | def get_size(self, background_size: Dimensions) -> Dimensions: |
Continue the code snippet: <|code_start|>
def describe_text():
def describe_stylize():
@pytest.mark.parametrize(
("style", "before", "after"),
[
("none", "Hello, world!", "Hello, world!"),
("default", "these are words.", "These are words."),
("default", "These ARE words.", "These ARE words."),
("upper", "Hello, world!", "HELLO, WORLD!"),
("lower", "Hello, world!", "hello, world!"),
("title", "these are words", "These Are Words"),
("capitalize", "these are words", "These are words"),
("mock", "these are words", "ThEsE aRe WorDs"),
("<unknown>", "Hello, world!", "Hello, world!"),
],
)
def it_applies_style(expect, style, before, after):
<|code_end|>
. Use current file imports:
import pytest
from ..models import Text
and context (classes, functions, or code) from other files:
# Path: app/models/text.py
# class Text:
#
# style: str = "upper"
# color: str = "white"
# font: str = settings.DEFAULT_FONT
#
# anchor_x: float = 0.0
# anchor_y: float = 0.0
#
# angle: float = 0
#
# scale_x: float = 1.0
# scale_y: float = 0.2
#
# start: float = 0.0
# stop: float = 1.0
#
# @classmethod
# def get_preview(cls) -> "Text":
# return cls(
# color="#80808060",
# anchor_x=0.075,
# anchor_y=0.05,
# angle=10,
# scale_x=0.75,
# scale_y=0.75,
# )
#
# @classmethod
# def get_error(cls) -> "Text":
# return cls(color="yellow", anchor_x=0.5)
#
# @classmethod
# def get_watermark(cls) -> "Text":
# return cls(color="#FFFFFF85")
#
# @property
# def animated(self) -> bool:
# return not (self.start == 0.0 and self.stop == 1.0)
#
# def get_anchor(self, image_size: Dimensions, watermark: str = "") -> Point:
# image_width, image_height = image_size
# anchor = int(image_width * self.anchor_x), int(image_height * self.anchor_y)
# if watermark and self.anchor_x <= 0.1 and self.anchor_y >= 0.8:
# anchor = anchor[0], anchor[1] - settings.WATERMARK_HEIGHT // 2
# return anchor
#
# def get_size(self, image_size: Dimensions) -> Dimensions:
# image_width, image_height = image_size
# size = int(image_width * self.scale_x), int(image_height * self.scale_y)
# return size
#
# def get_stroke(self, width: int) -> tuple[int, str]:
# if self.color == "black":
# width = 1
# color = "#FFFFFF85"
# elif "#" in self.color:
# width = 1
# color = "#000000" + self.color[-2:]
# else:
# color = "black"
# return width, color
#
# def stylize(self, text: str, **kwargs) -> str:
# lines = [line for line in kwargs.get("lines", [text]) if line.strip()]
#
# if self.style == "none":
# return text
#
# if self.style == "default":
# text = text.capitalize() if all(line.islower() for line in lines) else text
# return text
#
# if self.style == "mock":
# return spongemock.mock(text, diversity_bias=0.75, random_seed=0)
#
# method = getattr(text, self.style or self.__class__.style, None)
# if method:
# return method()
#
# logger.warning(f"Unsupported text style: {self.style}")
# return text
. Output only the next line. | text = Text() |
Continue the code snippet: <|code_start|> chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-extensions')
chrome_options.add_argument('--disable-dev-shm-usage')
self.driver = webdriver.Chrome(
ChromeDriverManager().install(),
options=chrome_options,
)
self.driver.set_window_size(1920, 1080)
self.driver.implicitly_wait(10)
self.login()
def tearDown(self):
self.driver.quit()
def login(self):
self.driver.get('http://localhost:8000/admin')
username_field = self.driver.find_element_by_id("id_username")
password_field = self.driver.find_element_by_id("id_password")
button = self.driver.find_element_by_css_selector('input[type=submit]')
username_field.send_keys('admin')
time.sleep(1)
password_field.send_keys('admin')
time.sleep(1)
button.click()
def test_menu(self):
# Wait until baton is ready
wait = WebDriverWait(self.driver, 10)
<|code_end|>
. Use current file imports:
import time
import os
from django.test import TestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from .utils import element_has_css_class
and context (classes, functions, or code) from other files:
# Path: testapp/app/app/tests/utils.py
# class element_has_css_class(object):
# """An expectation for checking that an element has a particular css class.
# locator - used to find the element
# returns the WebElement once it has the particular css class
# """
#
# def __init__(self, locator, css_class):
# self.locator = locator
# self.css_class = css_class
#
# def __call__(self, driver):
# element = driver.find_element(*self.locator) # Finding the referenced element
# if self.css_class in element.get_attribute("class"):
# return element
# else:
# return False
. Output only the next line. | wait.until(element_has_css_class((By.TAG_NAME, 'body'), "baton-ready")) |
Predict the next line for this snippet: <|code_start|>
class TestBatonConfig(TestCase):
def test_default_config(self):
self.assertEqual(default_config['SITE_TITLE'], 'Baton')
self.assertEqual(default_config['INDEX_TITLE'], 'Site administration')
self.assertEqual(default_config['CONFIRM_UNSAVED_CHANGES'], True)
self.assertEqual(default_config['SHOW_MULTIPART_UPLOADING'], True)
self.assertEqual(default_config['ENABLE_IMAGES_PREVIEW'], True)
self.assertEqual(default_config['CHANGELIST_FILTERS_IN_MODAL'], False)
def test_get_config(self):
<|code_end|>
with the help of current file imports:
from baton.config import default_config, get_config
from django.test import TestCase
and context from other files:
# Path: baton/config.py
# def get_config(key):
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(get_config('SITE_HEADER'), 'Baton Test App') |
Next line prediction: <|code_start|>
class NewsResources(resources.ModelResource):
class Meta:
model = News
<|code_end|>
. Use current file imports:
(import json
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.contrib.contenttypes.admin import GenericStackedInline
from baton.admin import InputFilter, RelatedDropdownFilter
from rangefilter.filter import DateRangeFilter
from admin_auto_filters.filters import AutocompleteFilter
from .models import News, Category, Attachment, Video, Activity
from import_export import resources
from import_export.admin import ImportExportModelAdmin)
and context including class names, function names, or small code snippets from other files:
# Path: baton/admin.py
# class InputFilter(admin.SimpleListFilter):
# template = 'baton/filters/input_filter.html'
#
# def lookups(self, request, model_admin):
# # Dummy, required to show the filter.
# return ((),)
#
# def choices(self, changelist):
# # Grab only the "all" option.
# all_choice = next(super(InputFilter, self).choices(changelist))
# all_choice['query_parts'] = (
# (k, v)
# for k, v in changelist.get_filters_params().items()
# if k != self.parameter_name
# )
# yield all_choice
#
# class RelatedDropdownFilter(RelatedFieldListFilter):
# template = 'baton/filters/dropdown_filter.html'
#
# Path: testapp/app/news/models.py
# class News(models.Model):
# category = models.ForeignKey(
# Category,
# verbose_name='category',
# on_delete=models.CASCADE,
# related_name='news',
# )
# date = models.DateField('date')
# datetime = models.DateTimeField('datetime', blank=True, null=True, help_text='insert date')
# title = models.CharField('title', max_length=50, help_text='please insert a cool title')
# link = models.URLField('link', blank=True, null=True)
# image = FilerImageField(null=True, blank=True, on_delete=models.SET_NULL, related_name="news_image")
# content = HTMLField(verbose_name='content', help_text='html is supported')
# share = models.BooleanField(default=False)
# published = models.BooleanField(default=False)
# attachments_summary = models.TextField('attachments summary', blank=True)
# videos_summary = models.TextField('videos summary', blank=True)
# favorites = GenericRelation(Activity)
#
# class Meta:
# verbose_name = "news"
# verbose_name_plural = "news"
#
# def __str__(self):
# return '{0}'.format(self.title)
#
# class Category(models.Model):
# name = models.CharField('name', max_length=50)
#
# class Meta:
# verbose_name = "category"
# verbose_name_plural = "categories"
#
# def __str__(self):
# return "{0}".format(self.name)
#
# class Attachment(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='attachments',
# )
# file = models.FileField(upload_to='news/img')
# caption = models.TextField()
#
# class Meta:
# verbose_name = "attachment"
# verbose_name_plural = "attachments"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Video(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='videos',
# )
# code = models.CharField('video code', max_length=50)
# caption = models.TextField()
# author_email = models.EmailField(blank=True, null=True)
#
# class Meta:
# verbose_name = "video"
# verbose_name_plural = "videos"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Activity(models.Model):
# FAVORITE = 'F'
# LIKE = 'L'
# UP_VOTE = 'U'
# DOWN_VOTE = 'D'
# ACTIVITY_TYPES = (
# (FAVORITE, 'Favorite'),
# (LIKE, 'Like'),
# (UP_VOTE, 'Up Vote'),
# (DOWN_VOTE, 'Down Vote'),
# )
#
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES)
# date = models.DateTimeField(auto_now_add=True)
#
# # Below the mandatory fields for generic relation
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.PositiveIntegerField()
# content_object = GenericForeignKey()
#
# class Meta:
# verbose_name = "activity"
# verbose_name_plural = "activities"
. Output only the next line. | class TitleFilter(InputFilter): |
Based on the snippet: <|code_start|>
class NewsResources(resources.ModelResource):
class Meta:
model = News
class TitleFilter(InputFilter):
parameter_name = 'title'
title = 'title'
def queryset(self, request, queryset):
if self.value() is not None:
search_term = self.value()
return queryset.filter(
title__icontains=search_term
)
class CategoryFilter(AutocompleteFilter):
title = 'category' # display title
field_name = 'category' # name of the foreign key field
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.contrib.contenttypes.admin import GenericStackedInline
from baton.admin import InputFilter, RelatedDropdownFilter
from rangefilter.filter import DateRangeFilter
from admin_auto_filters.filters import AutocompleteFilter
from .models import News, Category, Attachment, Video, Activity
from import_export import resources
from import_export.admin import ImportExportModelAdmin
and context (classes, functions, sometimes code) from other files:
# Path: baton/admin.py
# class InputFilter(admin.SimpleListFilter):
# template = 'baton/filters/input_filter.html'
#
# def lookups(self, request, model_admin):
# # Dummy, required to show the filter.
# return ((),)
#
# def choices(self, changelist):
# # Grab only the "all" option.
# all_choice = next(super(InputFilter, self).choices(changelist))
# all_choice['query_parts'] = (
# (k, v)
# for k, v in changelist.get_filters_params().items()
# if k != self.parameter_name
# )
# yield all_choice
#
# class RelatedDropdownFilter(RelatedFieldListFilter):
# template = 'baton/filters/dropdown_filter.html'
#
# Path: testapp/app/news/models.py
# class News(models.Model):
# category = models.ForeignKey(
# Category,
# verbose_name='category',
# on_delete=models.CASCADE,
# related_name='news',
# )
# date = models.DateField('date')
# datetime = models.DateTimeField('datetime', blank=True, null=True, help_text='insert date')
# title = models.CharField('title', max_length=50, help_text='please insert a cool title')
# link = models.URLField('link', blank=True, null=True)
# image = FilerImageField(null=True, blank=True, on_delete=models.SET_NULL, related_name="news_image")
# content = HTMLField(verbose_name='content', help_text='html is supported')
# share = models.BooleanField(default=False)
# published = models.BooleanField(default=False)
# attachments_summary = models.TextField('attachments summary', blank=True)
# videos_summary = models.TextField('videos summary', blank=True)
# favorites = GenericRelation(Activity)
#
# class Meta:
# verbose_name = "news"
# verbose_name_plural = "news"
#
# def __str__(self):
# return '{0}'.format(self.title)
#
# class Category(models.Model):
# name = models.CharField('name', max_length=50)
#
# class Meta:
# verbose_name = "category"
# verbose_name_plural = "categories"
#
# def __str__(self):
# return "{0}".format(self.name)
#
# class Attachment(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='attachments',
# )
# file = models.FileField(upload_to='news/img')
# caption = models.TextField()
#
# class Meta:
# verbose_name = "attachment"
# verbose_name_plural = "attachments"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Video(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='videos',
# )
# code = models.CharField('video code', max_length=50)
# caption = models.TextField()
# author_email = models.EmailField(blank=True, null=True)
#
# class Meta:
# verbose_name = "video"
# verbose_name_plural = "videos"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Activity(models.Model):
# FAVORITE = 'F'
# LIKE = 'L'
# UP_VOTE = 'U'
# DOWN_VOTE = 'D'
# ACTIVITY_TYPES = (
# (FAVORITE, 'Favorite'),
# (LIKE, 'Like'),
# (UP_VOTE, 'Up Vote'),
# (DOWN_VOTE, 'Down Vote'),
# )
#
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES)
# date = models.DateTimeField(auto_now_add=True)
#
# # Below the mandatory fields for generic relation
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.PositiveIntegerField()
# content_object = GenericForeignKey()
#
# class Meta:
# verbose_name = "activity"
# verbose_name_plural = "activities"
. Output only the next line. | @admin.register(Category) |
Given the code snippet: <|code_start|>
class NewsResources(resources.ModelResource):
class Meta:
model = News
class TitleFilter(InputFilter):
parameter_name = 'title'
title = 'title'
def queryset(self, request, queryset):
if self.value() is not None:
search_term = self.value()
return queryset.filter(
title__icontains=search_term
)
class CategoryFilter(AutocompleteFilter):
title = 'category' # display title
field_name = 'category' # name of the foreign key field
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', )
search_fields = ('name', )
class AttachmentsInline(admin.TabularInline):
<|code_end|>
, generate the next line using the imports in this file:
import json
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.contrib.contenttypes.admin import GenericStackedInline
from baton.admin import InputFilter, RelatedDropdownFilter
from rangefilter.filter import DateRangeFilter
from admin_auto_filters.filters import AutocompleteFilter
from .models import News, Category, Attachment, Video, Activity
from import_export import resources
from import_export.admin import ImportExportModelAdmin
and context (functions, classes, or occasionally code) from other files:
# Path: baton/admin.py
# class InputFilter(admin.SimpleListFilter):
# template = 'baton/filters/input_filter.html'
#
# def lookups(self, request, model_admin):
# # Dummy, required to show the filter.
# return ((),)
#
# def choices(self, changelist):
# # Grab only the "all" option.
# all_choice = next(super(InputFilter, self).choices(changelist))
# all_choice['query_parts'] = (
# (k, v)
# for k, v in changelist.get_filters_params().items()
# if k != self.parameter_name
# )
# yield all_choice
#
# class RelatedDropdownFilter(RelatedFieldListFilter):
# template = 'baton/filters/dropdown_filter.html'
#
# Path: testapp/app/news/models.py
# class News(models.Model):
# category = models.ForeignKey(
# Category,
# verbose_name='category',
# on_delete=models.CASCADE,
# related_name='news',
# )
# date = models.DateField('date')
# datetime = models.DateTimeField('datetime', blank=True, null=True, help_text='insert date')
# title = models.CharField('title', max_length=50, help_text='please insert a cool title')
# link = models.URLField('link', blank=True, null=True)
# image = FilerImageField(null=True, blank=True, on_delete=models.SET_NULL, related_name="news_image")
# content = HTMLField(verbose_name='content', help_text='html is supported')
# share = models.BooleanField(default=False)
# published = models.BooleanField(default=False)
# attachments_summary = models.TextField('attachments summary', blank=True)
# videos_summary = models.TextField('videos summary', blank=True)
# favorites = GenericRelation(Activity)
#
# class Meta:
# verbose_name = "news"
# verbose_name_plural = "news"
#
# def __str__(self):
# return '{0}'.format(self.title)
#
# class Category(models.Model):
# name = models.CharField('name', max_length=50)
#
# class Meta:
# verbose_name = "category"
# verbose_name_plural = "categories"
#
# def __str__(self):
# return "{0}".format(self.name)
#
# class Attachment(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='attachments',
# )
# file = models.FileField(upload_to='news/img')
# caption = models.TextField()
#
# class Meta:
# verbose_name = "attachment"
# verbose_name_plural = "attachments"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Video(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='videos',
# )
# code = models.CharField('video code', max_length=50)
# caption = models.TextField()
# author_email = models.EmailField(blank=True, null=True)
#
# class Meta:
# verbose_name = "video"
# verbose_name_plural = "videos"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Activity(models.Model):
# FAVORITE = 'F'
# LIKE = 'L'
# UP_VOTE = 'U'
# DOWN_VOTE = 'D'
# ACTIVITY_TYPES = (
# (FAVORITE, 'Favorite'),
# (LIKE, 'Like'),
# (UP_VOTE, 'Up Vote'),
# (DOWN_VOTE, 'Down Vote'),
# )
#
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES)
# date = models.DateTimeField(auto_now_add=True)
#
# # Below the mandatory fields for generic relation
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.PositiveIntegerField()
# content_object = GenericForeignKey()
#
# class Meta:
# verbose_name = "activity"
# verbose_name_plural = "activities"
. Output only the next line. | model = Attachment |
Continue the code snippet: <|code_start|> model = News
class TitleFilter(InputFilter):
parameter_name = 'title'
title = 'title'
def queryset(self, request, queryset):
if self.value() is not None:
search_term = self.value()
return queryset.filter(
title__icontains=search_term
)
class CategoryFilter(AutocompleteFilter):
title = 'category' # display title
field_name = 'category' # name of the foreign key field
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', )
search_fields = ('name', )
class AttachmentsInline(admin.TabularInline):
model = Attachment
extra = 1
class VideosInline(admin.StackedInline):
<|code_end|>
. Use current file imports:
import json
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.contrib.contenttypes.admin import GenericStackedInline
from baton.admin import InputFilter, RelatedDropdownFilter
from rangefilter.filter import DateRangeFilter
from admin_auto_filters.filters import AutocompleteFilter
from .models import News, Category, Attachment, Video, Activity
from import_export import resources
from import_export.admin import ImportExportModelAdmin
and context (classes, functions, or code) from other files:
# Path: baton/admin.py
# class InputFilter(admin.SimpleListFilter):
# template = 'baton/filters/input_filter.html'
#
# def lookups(self, request, model_admin):
# # Dummy, required to show the filter.
# return ((),)
#
# def choices(self, changelist):
# # Grab only the "all" option.
# all_choice = next(super(InputFilter, self).choices(changelist))
# all_choice['query_parts'] = (
# (k, v)
# for k, v in changelist.get_filters_params().items()
# if k != self.parameter_name
# )
# yield all_choice
#
# class RelatedDropdownFilter(RelatedFieldListFilter):
# template = 'baton/filters/dropdown_filter.html'
#
# Path: testapp/app/news/models.py
# class News(models.Model):
# category = models.ForeignKey(
# Category,
# verbose_name='category',
# on_delete=models.CASCADE,
# related_name='news',
# )
# date = models.DateField('date')
# datetime = models.DateTimeField('datetime', blank=True, null=True, help_text='insert date')
# title = models.CharField('title', max_length=50, help_text='please insert a cool title')
# link = models.URLField('link', blank=True, null=True)
# image = FilerImageField(null=True, blank=True, on_delete=models.SET_NULL, related_name="news_image")
# content = HTMLField(verbose_name='content', help_text='html is supported')
# share = models.BooleanField(default=False)
# published = models.BooleanField(default=False)
# attachments_summary = models.TextField('attachments summary', blank=True)
# videos_summary = models.TextField('videos summary', blank=True)
# favorites = GenericRelation(Activity)
#
# class Meta:
# verbose_name = "news"
# verbose_name_plural = "news"
#
# def __str__(self):
# return '{0}'.format(self.title)
#
# class Category(models.Model):
# name = models.CharField('name', max_length=50)
#
# class Meta:
# verbose_name = "category"
# verbose_name_plural = "categories"
#
# def __str__(self):
# return "{0}".format(self.name)
#
# class Attachment(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='attachments',
# )
# file = models.FileField(upload_to='news/img')
# caption = models.TextField()
#
# class Meta:
# verbose_name = "attachment"
# verbose_name_plural = "attachments"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Video(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='videos',
# )
# code = models.CharField('video code', max_length=50)
# caption = models.TextField()
# author_email = models.EmailField(blank=True, null=True)
#
# class Meta:
# verbose_name = "video"
# verbose_name_plural = "videos"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Activity(models.Model):
# FAVORITE = 'F'
# LIKE = 'L'
# UP_VOTE = 'U'
# DOWN_VOTE = 'D'
# ACTIVITY_TYPES = (
# (FAVORITE, 'Favorite'),
# (LIKE, 'Like'),
# (UP_VOTE, 'Up Vote'),
# (DOWN_VOTE, 'Down Vote'),
# )
#
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES)
# date = models.DateTimeField(auto_now_add=True)
#
# # Below the mandatory fields for generic relation
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.PositiveIntegerField()
# content_object = GenericForeignKey()
#
# class Meta:
# verbose_name = "activity"
# verbose_name_plural = "activities"
. Output only the next line. | model = Video |
Next line prediction: <|code_start|>
def queryset(self, request, queryset):
if self.value() is not None:
search_term = self.value()
return queryset.filter(
title__icontains=search_term
)
class CategoryFilter(AutocompleteFilter):
title = 'category' # display title
field_name = 'category' # name of the foreign key field
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', )
search_fields = ('name', )
class AttachmentsInline(admin.TabularInline):
model = Attachment
extra = 1
class VideosInline(admin.StackedInline):
model = Video
extra = 1
classes = ('collapse-entry', 'expand-first', )
class ActivitiesInline(GenericStackedInline):
<|code_end|>
. Use current file imports:
(import json
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.contrib.contenttypes.admin import GenericStackedInline
from baton.admin import InputFilter, RelatedDropdownFilter
from rangefilter.filter import DateRangeFilter
from admin_auto_filters.filters import AutocompleteFilter
from .models import News, Category, Attachment, Video, Activity
from import_export import resources
from import_export.admin import ImportExportModelAdmin)
and context including class names, function names, or small code snippets from other files:
# Path: baton/admin.py
# class InputFilter(admin.SimpleListFilter):
# template = 'baton/filters/input_filter.html'
#
# def lookups(self, request, model_admin):
# # Dummy, required to show the filter.
# return ((),)
#
# def choices(self, changelist):
# # Grab only the "all" option.
# all_choice = next(super(InputFilter, self).choices(changelist))
# all_choice['query_parts'] = (
# (k, v)
# for k, v in changelist.get_filters_params().items()
# if k != self.parameter_name
# )
# yield all_choice
#
# class RelatedDropdownFilter(RelatedFieldListFilter):
# template = 'baton/filters/dropdown_filter.html'
#
# Path: testapp/app/news/models.py
# class News(models.Model):
# category = models.ForeignKey(
# Category,
# verbose_name='category',
# on_delete=models.CASCADE,
# related_name='news',
# )
# date = models.DateField('date')
# datetime = models.DateTimeField('datetime', blank=True, null=True, help_text='insert date')
# title = models.CharField('title', max_length=50, help_text='please insert a cool title')
# link = models.URLField('link', blank=True, null=True)
# image = FilerImageField(null=True, blank=True, on_delete=models.SET_NULL, related_name="news_image")
# content = HTMLField(verbose_name='content', help_text='html is supported')
# share = models.BooleanField(default=False)
# published = models.BooleanField(default=False)
# attachments_summary = models.TextField('attachments summary', blank=True)
# videos_summary = models.TextField('videos summary', blank=True)
# favorites = GenericRelation(Activity)
#
# class Meta:
# verbose_name = "news"
# verbose_name_plural = "news"
#
# def __str__(self):
# return '{0}'.format(self.title)
#
# class Category(models.Model):
# name = models.CharField('name', max_length=50)
#
# class Meta:
# verbose_name = "category"
# verbose_name_plural = "categories"
#
# def __str__(self):
# return "{0}".format(self.name)
#
# class Attachment(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='attachments',
# )
# file = models.FileField(upload_to='news/img')
# caption = models.TextField()
#
# class Meta:
# verbose_name = "attachment"
# verbose_name_plural = "attachments"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Video(models.Model):
# news = models.ForeignKey(
# News,
# verbose_name='news',
# on_delete=models.CASCADE,
# related_name='videos',
# )
# code = models.CharField('video code', max_length=50)
# caption = models.TextField()
# author_email = models.EmailField(blank=True, null=True)
#
# class Meta:
# verbose_name = "video"
# verbose_name_plural = "videos"
#
# def __str__(self):
# return '{0}'.format(self.caption)
#
# class Activity(models.Model):
# FAVORITE = 'F'
# LIKE = 'L'
# UP_VOTE = 'U'
# DOWN_VOTE = 'D'
# ACTIVITY_TYPES = (
# (FAVORITE, 'Favorite'),
# (LIKE, 'Like'),
# (UP_VOTE, 'Up Vote'),
# (DOWN_VOTE, 'Down Vote'),
# )
#
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES)
# date = models.DateTimeField(auto_now_add=True)
#
# # Below the mandatory fields for generic relation
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.PositiveIntegerField()
# content_object = GenericForeignKey()
#
# class Meta:
# verbose_name = "activity"
# verbose_name_plural = "activities"
. Output only the next line. | model = Activity |
Given snippet: <|code_start|>
class GetAppListJsonView(View):
@method_decorator(staff_member_required)
def dispatch(self, *args, **kwargs):
""" Only staff members can access this view """
return super(GetAppListJsonView, self).dispatch(*args, **kwargs)
def get(self, request):
""" Returns a json representing the menu voices
in a format eaten by the js menu.
Raised ImproperlyConfigured exceptions can be viewed
in the browser console
"""
self.app_list = site.get_app_list(request)
self.apps_dict = self.create_app_list_dict()
# no menu provided
items = self.get_menu(request)
if not items:
voices = self.get_default_voices()
else:
voices = []
for item in items:
self.add_voice(voices, item)
return JsonResponse(voices, safe=False)
def get_menu(self, request):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import hashlib
from django.http import JsonResponse
from django.contrib.admin import site
from django.contrib.admin.views.decorators import staff_member_required
from django.utils.decorators import method_decorator
from django.core.exceptions import ImproperlyConfigured
from django.views import View
from .config import get_config
and context:
# Path: baton/config.py
# def get_config(key):
# safe = ['SITE_HEADER', 'COPYRIGHT', 'POWERED_BY', ]
# user_settings = getattr(settings, 'BATON', None)
#
# if user_settings is None:
# value = default_config.get(key, None)
# else:
# value = user_settings.get(key, default_config.get(key, None))
#
# if key in safe:
# return mark_safe(value)
#
# return value
which might include code, classes, or functions. Output only the next line. | return get_config('MENU') |
Continue the code snippet: <|code_start|>
register = template.Library()
@register.simple_tag
def baton_config():
conf = {
"api": {
"app_list": reverse('baton-app-list-json'),
"gravatar": reverse('baton-gravatar-json'),
},
<|code_end|>
. Use current file imports:
import json
from django.urls import reverse
from django import template
from django.utils.html import escapejs
from django.core.exceptions import ImproperlyConfigured
from ..config import get_config
from google.auth.transport.requests import Request
from google.oauth2 import service_account
and context (classes, functions, or code) from other files:
# Path: baton/config.py
# def get_config(key):
# safe = ['SITE_HEADER', 'COPYRIGHT', 'POWERED_BY', ]
# user_settings = getattr(settings, 'BATON', None)
#
# if user_settings is None:
# value = default_config.get(key, None)
# else:
# value = user_settings.get(key, default_config.get(key, None))
#
# if key in safe:
# return mark_safe(value)
#
# return value
. Output only the next line. | "confirmUnsavedChanges": get_config('CONFIRM_UNSAVED_CHANGES'), |
Continue the code snippet: <|code_start|> chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-extensions')
chrome_options.add_argument('--disable-dev-shm-usage')
self.driver = webdriver.Chrome(
ChromeDriverManager().install(),
options=chrome_options,
)
self.driver.set_window_size(1920, 1080)
self.driver.implicitly_wait(10)
self.login()
def tearDown(self):
self.driver.quit()
def login(self):
self.driver.get('http://localhost:8000/admin')
username_field = self.driver.find_element_by_id("id_username")
password_field = self.driver.find_element_by_id("id_password")
button = self.driver.find_element_by_css_selector('input[type=submit]')
username_field.send_keys('admin')
time.sleep(1)
password_field.send_keys('admin')
time.sleep(1)
button.click()
def test_navbar(self):
# Wait until baton is ready
wait = WebDriverWait(self.driver, 10)
<|code_end|>
. Use current file imports:
import time
import os
from django.test import TestCase
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from .utils import element_has_css_class
and context (classes, functions, or code) from other files:
# Path: testapp/app/app/tests/utils.py
# class element_has_css_class(object):
# """An expectation for checking that an element has a particular css class.
# locator - used to find the element
# returns the WebElement once it has the particular css class
# """
#
# def __init__(self, locator, css_class):
# self.locator = locator
# self.css_class = css_class
#
# def __call__(self, driver):
# element = driver.find_element(*self.locator) # Finding the referenced element
# if self.css_class in element.get_attribute("class"):
# return element
# else:
# return False
. Output only the next line. | wait.until(element_has_css_class((By.TAG_NAME, 'body'), "baton-ready")) |
Next line prediction: <|code_start|> chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-extensions')
chrome_options.add_argument('--disable-dev-shm-usage')
self.driver = webdriver.Chrome(
ChromeDriverManager().install(),
options=chrome_options,
)
self.driver.set_window_size(1920, 1080)
self.driver.implicitly_wait(10)
self.login()
def tearDown(self):
self.driver.quit()
def login(self):
self.driver.get('http://localhost:8000/admin/news/news/')
username_field = self.driver.find_element_by_id("id_username")
password_field = self.driver.find_element_by_id("id_password")
button = self.driver.find_element_by_css_selector('input[type=submit]')
username_field.send_keys('admin')
time.sleep(1)
password_field.send_keys('admin')
time.sleep(1)
button.click()
def test_filter(self):
# Wait until baton is ready
wait = WebDriverWait(self.driver, 10)
<|code_end|>
. Use current file imports:
(import os
import time
from django.test import TestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from .utils import element_has_css_class)
and context including class names, function names, or small code snippets from other files:
# Path: testapp/app/app/tests/utils.py
# class element_has_css_class(object):
# """An expectation for checking that an element has a particular css class.
# locator - used to find the element
# returns the WebElement once it has the particular css class
# """
#
# def __init__(self, locator, css_class):
# self.locator = locator
# self.css_class = css_class
#
# def __call__(self, driver):
# element = driver.find_element(*self.locator) # Finding the referenced element
# if self.css_class in element.get_attribute("class"):
# return element
# else:
# return False
. Output only the next line. | wait.until(element_has_css_class((By.TAG_NAME, 'body'), "baton-ready")) |
Here is a snippet: <|code_start|> chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-extensions')
chrome_options.add_argument('--disable-dev-shm-usage')
self.driver = webdriver.Chrome(
ChromeDriverManager().install(),
options=chrome_options,
)
self.driver.set_window_size(1920, 1080)
self.driver.implicitly_wait(10)
self.login()
def tearDown(self):
self.driver.quit()
def login(self):
self.driver.get('http://localhost:8000/admin/news/news/3/change')
username_field = self.driver.find_element_by_id("id_username")
password_field = self.driver.find_element_by_id("id_password")
button = self.driver.find_element_by_css_selector('input[type=submit]')
username_field.send_keys('admin')
time.sleep(1)
password_field.send_keys('admin')
time.sleep(1)
button.click()
def test_tabs(self):
# Wait until baton is ready
wait = WebDriverWait(self.driver, 10)
<|code_end|>
. Write the next line using the current file imports:
import os
import time
from django.test import TestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from .utils import element_has_css_class
and context from other files:
# Path: testapp/app/app/tests/utils.py
# class element_has_css_class(object):
# """An expectation for checking that an element has a particular css class.
# locator - used to find the element
# returns the WebElement once it has the particular css class
# """
#
# def __init__(self, locator, css_class):
# self.locator = locator
# self.css_class = css_class
#
# def __call__(self, driver):
# element = driver.find_element(*self.locator) # Finding the referenced element
# if self.css_class in element.get_attribute("class"):
# return element
# else:
# return False
, which may include functions, classes, or code. Output only the next line. | wait.until(element_has_css_class((By.TAG_NAME, 'body'), "baton-ready")) |
Predict the next line after this snippet: <|code_start|> chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-extensions')
chrome_options.add_argument('--disable-dev-shm-usage')
self.driver = webdriver.Chrome(
ChromeDriverManager().install(),
options=chrome_options,
)
self.driver.set_window_size(1920, 1080)
self.driver.implicitly_wait(10)
self.login()
def tearDown(self):
self.driver.quit()
def login(self):
self.driver.get('http://localhost:8000/admin/news/news/')
username_field = self.driver.find_element_by_id("id_username")
password_field = self.driver.find_element_by_id("id_password")
button = self.driver.find_element_by_css_selector('input[type=submit]')
username_field.send_keys('admin')
time.sleep(1)
password_field.send_keys('admin')
time.sleep(1)
button.click()
def test_includes(self):
# Wait until baton is ready
wait = WebDriverWait(self.driver, 10)
<|code_end|>
using the current file's imports:
import os
import time
from django.test import TestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from .utils import element_has_css_class
and any relevant context from other files:
# Path: testapp/app/app/tests/utils.py
# class element_has_css_class(object):
# """An expectation for checking that an element has a particular css class.
# locator - used to find the element
# returns the WebElement once it has the particular css class
# """
#
# def __init__(self, locator, css_class):
# self.locator = locator
# self.css_class = css_class
#
# def __call__(self, driver):
# element = driver.find_element(*self.locator) # Finding the referenced element
# if self.css_class in element.get_attribute("class"):
# return element
# else:
# return False
. Output only the next line. | wait.until(element_has_css_class((By.TAG_NAME, 'body'), "baton-ready")) |
Predict the next line for this snippet: <|code_start|>
def tearDown(self):
self.driver.quit()
def login(self):
self.driver.get('http://localhost:8000/admin')
username_field = self.driver.find_element_by_id("id_username")
password_field = self.driver.find_element_by_id("id_password")
button = self.driver.find_element_by_css_selector('input[type=submit]')
username_field.send_keys('admin')
time.sleep(1)
password_field.send_keys('admin')
time.sleep(1)
button.click()
# selenium sees the navbar as visible because it's just moved to the left,
# we cannot use is_displayed method
def navbar_is_invisible(self, navbar):
left = int(navbar.value_of_css_property('left').replace('px', ''))
width = int(navbar.value_of_css_property('width').replace('px', ''))
return left + width <= 0
def navbar_is_visible(self, navbar):
left = int(navbar.value_of_css_property('left').replace('px', ''))
return left == 0
def test_menu(self):
# Wait until baton is ready
wait = WebDriverWait(self.driver, 10)
<|code_end|>
with the help of current file imports:
import time
import os
from django.test import TestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from .utils import element_has_css_class
and context from other files:
# Path: testapp/app/app/tests/utils.py
# class element_has_css_class(object):
# """An expectation for checking that an element has a particular css class.
# locator - used to find the element
# returns the WebElement once it has the particular css class
# """
#
# def __init__(self, locator, css_class):
# self.locator = locator
# self.css_class = css_class
#
# def __call__(self, driver):
# element = driver.find_element(*self.locator) # Finding the referenced element
# if self.css_class in element.get_attribute("class"):
# return element
# else:
# return False
, which may contain function names, class names, or code. Output only the next line. | wait.until(element_has_css_class((By.TAG_NAME, 'body'), "baton-ready")) |
Predict the next line for this snippet: <|code_start|>"""app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
urlpatterns = [
path('admin/doc/', include('django.contrib.admindocs.urls')),
path('admin/search/', admin_search),
# path('admin/newschange/<int:id>', news_change_view),
<|code_end|>
with the help of current file imports:
from baton.autodiscover import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.views import static
from django.contrib.staticfiles.views import serve
from app.views import admin_search
from news.views import news_change_view
and context from other files:
# Path: baton/autodiscover/admin.py
# class BatonAdminSite(admin.AdminSite):
# def __init__(self, *args, **kwargs):
, which may contain function names, class names, or code. Output only the next line. | path('admin/', admin.site.urls), |
Given the following code snippet before the placeholder: <|code_start|> chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-extensions')
chrome_options.add_argument('--disable-dev-shm-usage')
self.driver = webdriver.Chrome(
ChromeDriverManager().install(),
options=chrome_options,
)
self.driver.set_window_size(480, 600)
self.driver.implicitly_wait(10)
self.login()
def tearDown(self):
self.driver.quit()
def login(self):
self.driver.get('http://localhost:8000/admin')
username_field = self.driver.find_element_by_id("id_username")
password_field = self.driver.find_element_by_id("id_password")
button = self.driver.find_element_by_css_selector('input[type=submit]')
username_field.send_keys('admin')
time.sleep(1)
password_field.send_keys('admin')
time.sleep(1)
button.click()
def test_navbar(self):
# Wait until baton is ready
wait = WebDriverWait(self.driver, 10)
<|code_end|>
, predict the next line using imports from the current file:
import time
import os
from django.test import TestCase
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from .utils import element_has_css_class
and context including class names, function names, and sometimes code from other files:
# Path: testapp/app/app/tests/utils.py
# class element_has_css_class(object):
# """An expectation for checking that an element has a particular css class.
# locator - used to find the element
# returns the WebElement once it has the particular css class
# """
#
# def __init__(self, locator, css_class):
# self.locator = locator
# self.css_class = css_class
#
# def __call__(self, driver):
# element = driver.find_element(*self.locator) # Finding the referenced element
# if self.css_class in element.get_attribute("class"):
# return element
# else:
# return False
. Output only the next line. | wait.until(element_has_css_class((By.TAG_NAME, 'body'), "baton-ready")) |
Here is a snippet: <|code_start|>_config_key = r"[$\w]+" # foo, $0, $bar, $foo_$bar123$
_key_maybe_brackets = f"{_config_key}|\\[{_config_key}\\]" # foo, [foo], [$bar]
_node_access = f"\\.{_key_maybe_brackets}" # .foo, [foo], [$bar]
_node_path = f"(\\.)*({_key_maybe_brackets})({_node_access})*" # [foo].bar, .foo[bar]
_node_inter = f"\\${{\\s*{_node_path}\\s*}}" # node interpolation ${foo.bar}
_id = "[a-zA-Z_]\\w*" # foo, foo_bar, abc123
_resolver_name = f"({_id}(\\.{_id})*)?" # foo, ns.bar3, ns_1.ns_2.b0z
_arg = r"[a-zA-Z_0-9/\-\+.$%*@?|]+" # string representing a resolver argument
_args = f"{_arg}(\\s*,\\s*{_arg})*" # list of resolver arguments
_resolver_inter = f"\\${{\\s*{_resolver_name}\\s*:\\s*{_args}?\\s*}}" # ${foo:bar}
_inter = f"({_node_inter}|{_resolver_inter})" # any kind of interpolation
_outer = "([^$]|\\$(?!{))+" # any character except $ (unless not followed by {)
SIMPLE_INTERPOLATION_PATTERN = re.compile(
f"({_outer})?({_inter}({_outer})?)+$", flags=re.ASCII
)
# NOTE: SIMPLE_INTERPOLATION_PATTERN must not generate false positive matches:
# it must not accept anything that isn't a valid interpolation (per the
# interpolation grammar defined in `omegaconf/grammar/*.g4`).
class OmegaConfErrorListener(ErrorListener): # type: ignore
def syntaxError(
self,
recognizer: Any,
offending_symbol: Any,
line: Any,
column: Any,
msg: Any,
e: Any,
) -> None:
<|code_end|>
. Write the next line using the current file imports:
import re
import threading
from typing import Any
from antlr4 import CommonTokenStream, InputStream, ParserRuleContext
from antlr4.error.ErrorListener import ErrorListener
from .errors import GrammarParseError
from .grammar_visitor import ( # type: ignore
OmegaConfGrammarLexer,
OmegaConfGrammarParser,
)
and context from other files:
# Path: omegaconf/errors.py
# class GrammarParseError(OmegaConfBaseException):
# """
# Thrown when failing to parse an expression according to the ANTLR grammar.
# """
#
# Path: omegaconf/grammar_visitor.py
# class GrammarVisitor(OmegaConfGrammarParserVisitor):
# def __init__(
# self,
# node_interpolation_callback: Callable[
# [str, Optional[Set[int]]],
# Optional["Node"],
# ],
# resolver_interpolation_callback: Callable[..., Any],
# memo: Optional[Set[int]],
# **kw: Dict[Any, Any],
# ):
# def aggregateResult(self, aggregate: List[Any], nextResult: Any) -> List[Any]:
# def defaultResult(self) -> List[Any]:
# def visitConfigKey(self, ctx: OmegaConfGrammarParser.ConfigKeyContext) -> str:
# def visitConfigValue(self, ctx: OmegaConfGrammarParser.ConfigValueContext) -> Any:
# def visitDictKey(self, ctx: OmegaConfGrammarParser.DictKeyContext) -> Any:
# def visitDictContainer(
# self, ctx: OmegaConfGrammarParser.DictContainerContext
# ) -> Dict[Any, Any]:
# def visitElement(self, ctx: OmegaConfGrammarParser.ElementContext) -> Any:
# def visitInterpolation(
# self, ctx: OmegaConfGrammarParser.InterpolationContext
# ) -> Any:
# def visitInterpolationNode(
# self, ctx: OmegaConfGrammarParser.InterpolationNodeContext
# ) -> Optional["Node"]:
# def visitInterpolationResolver(
# self, ctx: OmegaConfGrammarParser.InterpolationResolverContext
# ) -> Any:
# def visitDictKeyValuePair(
# self, ctx: OmegaConfGrammarParser.DictKeyValuePairContext
# ) -> Tuple[Any, Any]:
# def visitListContainer(
# self, ctx: OmegaConfGrammarParser.ListContainerContext
# ) -> List[Any]:
# def visitPrimitive(self, ctx: OmegaConfGrammarParser.PrimitiveContext) -> Any:
# def visitQuotedValue(self, ctx: OmegaConfGrammarParser.QuotedValueContext) -> str:
# def visitResolverName(self, ctx: OmegaConfGrammarParser.ResolverNameContext) -> str:
# def visitSequence(
# self, ctx: OmegaConfGrammarParser.SequenceContext
# ) -> Generator[Any, None, None]:
# def empty_str_warning() -> None:
# def visitSingleElement(
# self, ctx: OmegaConfGrammarParser.SingleElementContext
# ) -> Any:
# def visitText(self, ctx: OmegaConfGrammarParser.TextContext) -> Any:
# def _createPrimitive(
# self,
# ctx: Union[
# OmegaConfGrammarParser.PrimitiveContext,
# OmegaConfGrammarParser.DictKeyContext,
# ],
# ) -> Any:
# def _unescape(
# self,
# seq: List[Union[TerminalNode, OmegaConfGrammarParser.InterpolationContext]],
# ) -> str:
, which may include functions, classes, or code. Output only the next line. | raise GrammarParseError(str(e) if msg is None else msg) from e |
Based on the snippet: <|code_start|> stopIndex: Any,
conflictingAlts: Any,
configs: Any,
) -> None:
# Note: for now we raise an error to be safe. However this is mostly a
# performance warning, so in the future this may be relaxed if we need
# to change the grammar in such a way that this warning cannot be
# avoided (another option would be to switch to SLL parsing mode).
raise GrammarParseError(
"ANTLR error: Attempting Full Context"
) # pragma: no cover
def reportContextSensitivity(
self,
recognizer: Any,
dfa: Any,
startIndex: Any,
stopIndex: Any,
prediction: Any,
configs: Any,
) -> None:
raise GrammarParseError("ANTLR error: ContextSensitivity") # pragma: no cover
def parse(
value: str, parser_rule: str = "configValue", lexer_mode: str = "DEFAULT_MODE"
) -> ParserRuleContext:
"""
Parse interpolated string `value` (and return the parse tree).
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import threading
from typing import Any
from antlr4 import CommonTokenStream, InputStream, ParserRuleContext
from antlr4.error.ErrorListener import ErrorListener
from .errors import GrammarParseError
from .grammar_visitor import ( # type: ignore
OmegaConfGrammarLexer,
OmegaConfGrammarParser,
)
and context (classes, functions, sometimes code) from other files:
# Path: omegaconf/errors.py
# class GrammarParseError(OmegaConfBaseException):
# """
# Thrown when failing to parse an expression according to the ANTLR grammar.
# """
#
# Path: omegaconf/grammar_visitor.py
# class GrammarVisitor(OmegaConfGrammarParserVisitor):
# def __init__(
# self,
# node_interpolation_callback: Callable[
# [str, Optional[Set[int]]],
# Optional["Node"],
# ],
# resolver_interpolation_callback: Callable[..., Any],
# memo: Optional[Set[int]],
# **kw: Dict[Any, Any],
# ):
# def aggregateResult(self, aggregate: List[Any], nextResult: Any) -> List[Any]:
# def defaultResult(self) -> List[Any]:
# def visitConfigKey(self, ctx: OmegaConfGrammarParser.ConfigKeyContext) -> str:
# def visitConfigValue(self, ctx: OmegaConfGrammarParser.ConfigValueContext) -> Any:
# def visitDictKey(self, ctx: OmegaConfGrammarParser.DictKeyContext) -> Any:
# def visitDictContainer(
# self, ctx: OmegaConfGrammarParser.DictContainerContext
# ) -> Dict[Any, Any]:
# def visitElement(self, ctx: OmegaConfGrammarParser.ElementContext) -> Any:
# def visitInterpolation(
# self, ctx: OmegaConfGrammarParser.InterpolationContext
# ) -> Any:
# def visitInterpolationNode(
# self, ctx: OmegaConfGrammarParser.InterpolationNodeContext
# ) -> Optional["Node"]:
# def visitInterpolationResolver(
# self, ctx: OmegaConfGrammarParser.InterpolationResolverContext
# ) -> Any:
# def visitDictKeyValuePair(
# self, ctx: OmegaConfGrammarParser.DictKeyValuePairContext
# ) -> Tuple[Any, Any]:
# def visitListContainer(
# self, ctx: OmegaConfGrammarParser.ListContainerContext
# ) -> List[Any]:
# def visitPrimitive(self, ctx: OmegaConfGrammarParser.PrimitiveContext) -> Any:
# def visitQuotedValue(self, ctx: OmegaConfGrammarParser.QuotedValueContext) -> str:
# def visitResolverName(self, ctx: OmegaConfGrammarParser.ResolverNameContext) -> str:
# def visitSequence(
# self, ctx: OmegaConfGrammarParser.SequenceContext
# ) -> Generator[Any, None, None]:
# def empty_str_warning() -> None:
# def visitSingleElement(
# self, ctx: OmegaConfGrammarParser.SingleElementContext
# ) -> Any:
# def visitText(self, ctx: OmegaConfGrammarParser.TextContext) -> Any:
# def _createPrimitive(
# self,
# ctx: Union[
# OmegaConfGrammarParser.PrimitiveContext,
# OmegaConfGrammarParser.DictKeyContext,
# ],
# ) -> Any:
# def _unescape(
# self,
# seq: List[Union[TerminalNode, OmegaConfGrammarParser.InterpolationContext]],
# ) -> str:
. Output only the next line. | l_mode = getattr(OmegaConfGrammarLexer, lexer_mode) |
Next line prediction: <|code_start|>
def reportContextSensitivity(
self,
recognizer: Any,
dfa: Any,
startIndex: Any,
stopIndex: Any,
prediction: Any,
configs: Any,
) -> None:
raise GrammarParseError("ANTLR error: ContextSensitivity") # pragma: no cover
def parse(
value: str, parser_rule: str = "configValue", lexer_mode: str = "DEFAULT_MODE"
) -> ParserRuleContext:
"""
Parse interpolated string `value` (and return the parse tree).
"""
l_mode = getattr(OmegaConfGrammarLexer, lexer_mode)
istream = InputStream(value)
cached = getattr(_grammar_cache, "data", None)
if cached is None:
error_listener = OmegaConfErrorListener()
lexer = OmegaConfGrammarLexer(istream)
lexer.removeErrorListeners()
lexer.addErrorListener(error_listener)
lexer.mode(l_mode)
token_stream = CommonTokenStream(lexer)
<|code_end|>
. Use current file imports:
(import re
import threading
from typing import Any
from antlr4 import CommonTokenStream, InputStream, ParserRuleContext
from antlr4.error.ErrorListener import ErrorListener
from .errors import GrammarParseError
from .grammar_visitor import ( # type: ignore
OmegaConfGrammarLexer,
OmegaConfGrammarParser,
))
and context including class names, function names, or small code snippets from other files:
# Path: omegaconf/errors.py
# class GrammarParseError(OmegaConfBaseException):
# """
# Thrown when failing to parse an expression according to the ANTLR grammar.
# """
#
# Path: omegaconf/grammar_visitor.py
# class GrammarVisitor(OmegaConfGrammarParserVisitor):
# def __init__(
# self,
# node_interpolation_callback: Callable[
# [str, Optional[Set[int]]],
# Optional["Node"],
# ],
# resolver_interpolation_callback: Callable[..., Any],
# memo: Optional[Set[int]],
# **kw: Dict[Any, Any],
# ):
# def aggregateResult(self, aggregate: List[Any], nextResult: Any) -> List[Any]:
# def defaultResult(self) -> List[Any]:
# def visitConfigKey(self, ctx: OmegaConfGrammarParser.ConfigKeyContext) -> str:
# def visitConfigValue(self, ctx: OmegaConfGrammarParser.ConfigValueContext) -> Any:
# def visitDictKey(self, ctx: OmegaConfGrammarParser.DictKeyContext) -> Any:
# def visitDictContainer(
# self, ctx: OmegaConfGrammarParser.DictContainerContext
# ) -> Dict[Any, Any]:
# def visitElement(self, ctx: OmegaConfGrammarParser.ElementContext) -> Any:
# def visitInterpolation(
# self, ctx: OmegaConfGrammarParser.InterpolationContext
# ) -> Any:
# def visitInterpolationNode(
# self, ctx: OmegaConfGrammarParser.InterpolationNodeContext
# ) -> Optional["Node"]:
# def visitInterpolationResolver(
# self, ctx: OmegaConfGrammarParser.InterpolationResolverContext
# ) -> Any:
# def visitDictKeyValuePair(
# self, ctx: OmegaConfGrammarParser.DictKeyValuePairContext
# ) -> Tuple[Any, Any]:
# def visitListContainer(
# self, ctx: OmegaConfGrammarParser.ListContainerContext
# ) -> List[Any]:
# def visitPrimitive(self, ctx: OmegaConfGrammarParser.PrimitiveContext) -> Any:
# def visitQuotedValue(self, ctx: OmegaConfGrammarParser.QuotedValueContext) -> str:
# def visitResolverName(self, ctx: OmegaConfGrammarParser.ResolverNameContext) -> str:
# def visitSequence(
# self, ctx: OmegaConfGrammarParser.SequenceContext
# ) -> Generator[Any, None, None]:
# def empty_str_warning() -> None:
# def visitSingleElement(
# self, ctx: OmegaConfGrammarParser.SingleElementContext
# ) -> Any:
# def visitText(self, ctx: OmegaConfGrammarParser.TextContext) -> Any:
# def _createPrimitive(
# self,
# ctx: Union[
# OmegaConfGrammarParser.PrimitiveContext,
# OmegaConfGrammarParser.DictKeyContext,
# ],
# ) -> Any:
# def _unescape(
# self,
# seq: List[Union[TerminalNode, OmegaConfGrammarParser.InterpolationContext]],
# ) -> str:
. Output only the next line. | parser = OmegaConfGrammarParser(token_stream) |
Predict the next line for this snippet: <|code_start|> string input which is the key's dot path (ex: `"foo.bar"`).
:param resolver_interpolation_callback: Callback function that is called when
needing to resolve a resolver interpolation. This function should accept
three keyword arguments: `name` (str, the name of the resolver),
`args` (tuple, the inputs to the resolver), and `args_str` (tuple,
the string representation of the inputs to the resolver).
:param kw: Additional keyword arguments to be forwarded to parent class.
"""
super().__init__(**kw)
self.node_interpolation_callback = node_interpolation_callback
self.resolver_interpolation_callback = resolver_interpolation_callback
self.memo = memo
def aggregateResult(self, aggregate: List[Any], nextResult: Any) -> List[Any]:
raise NotImplementedError
def defaultResult(self) -> List[Any]:
# Raising an exception because not currently used (like `aggregateResult()`).
raise NotImplementedError
def visitConfigKey(self, ctx: OmegaConfGrammarParser.ConfigKeyContext) -> str:
# interpolation | ID | INTER_KEY
assert ctx.getChildCount() == 1
child = ctx.getChild(0)
if isinstance(child, OmegaConfGrammarParser.InterpolationContext):
res = _get_value(self.visitInterpolation(child))
if not isinstance(res, str):
<|code_end|>
with the help of current file imports:
import sys
import warnings
from itertools import zip_longest
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Union,
)
from antlr4 import TerminalNode
from .errors import InterpolationResolutionError
from .base import Node # noqa F401
from omegaconf.grammar.gen.OmegaConfGrammarLexer import OmegaConfGrammarLexer
from omegaconf.grammar.gen.OmegaConfGrammarParser import OmegaConfGrammarParser
from omegaconf.grammar.gen.OmegaConfGrammarParserVisitor import (
OmegaConfGrammarParserVisitor,
)
from ._utils import _get_value
from ._utils import _get_value
from ._utils import _get_value
from ._utils import _get_value
and context from other files:
# Path: omegaconf/errors.py
# class InterpolationResolutionError(OmegaConfBaseException, ValueError):
# """
# Base class for exceptions raised when resolving an interpolation.
# """
, which may contain function names, class names, or code. Output only the next line. | raise InterpolationResolutionError( |
Predict the next line after this snippet: <|code_start|># type: ignore
"""
OmegaConf setup
Instructions:
# Build:
rm -rf dist/ omegaconf.egg-info/
python -m build
# Upload:
twine upload dist/*
"""
with pathlib.Path("requirements/base.txt").open() as requirements_txt:
install_requires = [
str(requirement)
for requirement in pkg_resources.parse_requirements(requirements_txt)
]
with open("README.md", "r") as fh:
LONG_DESC = fh.read()
setuptools.setup(
cmdclass={
<|code_end|>
using the current file's imports:
import pathlib
import pkg_resources
import setuptools
from build_helpers.build_helpers import (
ANTLRCommand,
BuildPyCommand,
CleanCommand,
DevelopCommand,
SDistCommand,
find_version,
)
and any relevant context from other files:
# Path: build_helpers/build_helpers.py
# class ANTLRCommand(Command): # type: ignore # pragma: no cover
# """Generate parsers using ANTLR."""
#
# description = "Run ANTLR"
# user_options: List[str] = []
#
# def run(self) -> None:
# """Run command."""
# build_dir = Path(__file__).parent.absolute()
# project_root = build_dir.parent
# for grammar in [
# "OmegaConfGrammarLexer.g4",
# "OmegaConfGrammarParser.g4",
# ]:
# command = [
# "java",
# "-jar",
# str(build_dir / "bin" / "antlr-4.8-complete.jar"),
# "-Dlanguage=Python3",
# "-o",
# str(project_root / "omegaconf" / "grammar" / "gen"),
# "-Xexact-output-dir",
# "-visitor",
# str(project_root / "omegaconf" / "grammar" / grammar),
# ]
#
# self.announce(
# f"Generating parser for Python3: {command}",
# level=distutils.log.INFO,
# )
#
# subprocess.check_call(command)
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class BuildPyCommand(build_py.build_py): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run:
# self.run_command("clean")
# run_antlr(self)
# build_py.build_py.run(self)
#
# class CleanCommand(Command): # type: ignore # pragma: no cover
# """
# Our custom command to clean out junk files.
# """
#
# description = "Cleans out generated and junk files we don't want in the repo"
# dry_run: bool
# user_options: List[str] = []
#
# def run(self) -> None:
# root = Path(__file__).parent.parent.absolute()
# files = find(
# root=root,
# include_files=["^omegaconf/grammar/gen/.*"],
# include_dirs=[
# "^omegaconf\\.egg-info$",
# "\\.eggs$",
# "^\\.mypy_cache$",
# "^\\.pytest_cache$",
# ".*/__pycache__$",
# "^__pycache__$",
# "^build$",
# ],
# scan_exclude=["^.git$", "^.nox/.*$"],
# excludes=[".*\\.gitignore$", ".*/__init__.py"],
# )
#
# if self.dry_run:
# print("Dry run! Would clean up the following files and dirs:")
# print("\n".join(sorted(map(str, files))))
# else:
# for f in files:
# if f.exists():
# if f.is_dir():
# shutil.rmtree(f, ignore_errors=True)
# else:
# f.unlink()
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class DevelopCommand(develop.develop): # pragma: no cover
# def run(self) -> None: # type: ignore
# if not self.dry_run:
# run_antlr(self)
# develop.develop.run(self)
#
# class SDistCommand(sdist.sdist): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run: # type: ignore
# self.run_command("clean")
# run_antlr(self)
# sdist.sdist.run(self)
#
# def find_version(*file_paths: str) -> str:
# root = Path(__file__).parent.parent.absolute()
# with codecs.open(root / Path(*file_paths), "r") as fp: # type: ignore
# version_file = fp.read()
# version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
# if version_match:
# return version_match.group(1)
# raise RuntimeError("Unable to find version string.") # pragma: no cover
. Output only the next line. | "antlr": ANTLRCommand, |
Here is a snippet: <|code_start|># type: ignore
"""
OmegaConf setup
Instructions:
# Build:
rm -rf dist/ omegaconf.egg-info/
python -m build
# Upload:
twine upload dist/*
"""
with pathlib.Path("requirements/base.txt").open() as requirements_txt:
install_requires = [
str(requirement)
for requirement in pkg_resources.parse_requirements(requirements_txt)
]
with open("README.md", "r") as fh:
LONG_DESC = fh.read()
setuptools.setup(
cmdclass={
"antlr": ANTLRCommand,
"clean": CleanCommand,
"sdist": SDistCommand,
<|code_end|>
. Write the next line using the current file imports:
import pathlib
import pkg_resources
import setuptools
from build_helpers.build_helpers import (
ANTLRCommand,
BuildPyCommand,
CleanCommand,
DevelopCommand,
SDistCommand,
find_version,
)
and context from other files:
# Path: build_helpers/build_helpers.py
# class ANTLRCommand(Command): # type: ignore # pragma: no cover
# """Generate parsers using ANTLR."""
#
# description = "Run ANTLR"
# user_options: List[str] = []
#
# def run(self) -> None:
# """Run command."""
# build_dir = Path(__file__).parent.absolute()
# project_root = build_dir.parent
# for grammar in [
# "OmegaConfGrammarLexer.g4",
# "OmegaConfGrammarParser.g4",
# ]:
# command = [
# "java",
# "-jar",
# str(build_dir / "bin" / "antlr-4.8-complete.jar"),
# "-Dlanguage=Python3",
# "-o",
# str(project_root / "omegaconf" / "grammar" / "gen"),
# "-Xexact-output-dir",
# "-visitor",
# str(project_root / "omegaconf" / "grammar" / grammar),
# ]
#
# self.announce(
# f"Generating parser for Python3: {command}",
# level=distutils.log.INFO,
# )
#
# subprocess.check_call(command)
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class BuildPyCommand(build_py.build_py): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run:
# self.run_command("clean")
# run_antlr(self)
# build_py.build_py.run(self)
#
# class CleanCommand(Command): # type: ignore # pragma: no cover
# """
# Our custom command to clean out junk files.
# """
#
# description = "Cleans out generated and junk files we don't want in the repo"
# dry_run: bool
# user_options: List[str] = []
#
# def run(self) -> None:
# root = Path(__file__).parent.parent.absolute()
# files = find(
# root=root,
# include_files=["^omegaconf/grammar/gen/.*"],
# include_dirs=[
# "^omegaconf\\.egg-info$",
# "\\.eggs$",
# "^\\.mypy_cache$",
# "^\\.pytest_cache$",
# ".*/__pycache__$",
# "^__pycache__$",
# "^build$",
# ],
# scan_exclude=["^.git$", "^.nox/.*$"],
# excludes=[".*\\.gitignore$", ".*/__init__.py"],
# )
#
# if self.dry_run:
# print("Dry run! Would clean up the following files and dirs:")
# print("\n".join(sorted(map(str, files))))
# else:
# for f in files:
# if f.exists():
# if f.is_dir():
# shutil.rmtree(f, ignore_errors=True)
# else:
# f.unlink()
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class DevelopCommand(develop.develop): # pragma: no cover
# def run(self) -> None: # type: ignore
# if not self.dry_run:
# run_antlr(self)
# develop.develop.run(self)
#
# class SDistCommand(sdist.sdist): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run: # type: ignore
# self.run_command("clean")
# run_antlr(self)
# sdist.sdist.run(self)
#
# def find_version(*file_paths: str) -> str:
# root = Path(__file__).parent.parent.absolute()
# with codecs.open(root / Path(*file_paths), "r") as fp: # type: ignore
# version_file = fp.read()
# version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
# if version_match:
# return version_match.group(1)
# raise RuntimeError("Unable to find version string.") # pragma: no cover
, which may include functions, classes, or code. Output only the next line. | "build_py": BuildPyCommand, |
Given the code snippet: <|code_start|># type: ignore
"""
OmegaConf setup
Instructions:
# Build:
rm -rf dist/ omegaconf.egg-info/
python -m build
# Upload:
twine upload dist/*
"""
with pathlib.Path("requirements/base.txt").open() as requirements_txt:
install_requires = [
str(requirement)
for requirement in pkg_resources.parse_requirements(requirements_txt)
]
with open("README.md", "r") as fh:
LONG_DESC = fh.read()
setuptools.setup(
cmdclass={
"antlr": ANTLRCommand,
<|code_end|>
, generate the next line using the imports in this file:
import pathlib
import pkg_resources
import setuptools
from build_helpers.build_helpers import (
ANTLRCommand,
BuildPyCommand,
CleanCommand,
DevelopCommand,
SDistCommand,
find_version,
)
and context (functions, classes, or occasionally code) from other files:
# Path: build_helpers/build_helpers.py
# class ANTLRCommand(Command): # type: ignore # pragma: no cover
# """Generate parsers using ANTLR."""
#
# description = "Run ANTLR"
# user_options: List[str] = []
#
# def run(self) -> None:
# """Run command."""
# build_dir = Path(__file__).parent.absolute()
# project_root = build_dir.parent
# for grammar in [
# "OmegaConfGrammarLexer.g4",
# "OmegaConfGrammarParser.g4",
# ]:
# command = [
# "java",
# "-jar",
# str(build_dir / "bin" / "antlr-4.8-complete.jar"),
# "-Dlanguage=Python3",
# "-o",
# str(project_root / "omegaconf" / "grammar" / "gen"),
# "-Xexact-output-dir",
# "-visitor",
# str(project_root / "omegaconf" / "grammar" / grammar),
# ]
#
# self.announce(
# f"Generating parser for Python3: {command}",
# level=distutils.log.INFO,
# )
#
# subprocess.check_call(command)
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class BuildPyCommand(build_py.build_py): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run:
# self.run_command("clean")
# run_antlr(self)
# build_py.build_py.run(self)
#
# class CleanCommand(Command): # type: ignore # pragma: no cover
# """
# Our custom command to clean out junk files.
# """
#
# description = "Cleans out generated and junk files we don't want in the repo"
# dry_run: bool
# user_options: List[str] = []
#
# def run(self) -> None:
# root = Path(__file__).parent.parent.absolute()
# files = find(
# root=root,
# include_files=["^omegaconf/grammar/gen/.*"],
# include_dirs=[
# "^omegaconf\\.egg-info$",
# "\\.eggs$",
# "^\\.mypy_cache$",
# "^\\.pytest_cache$",
# ".*/__pycache__$",
# "^__pycache__$",
# "^build$",
# ],
# scan_exclude=["^.git$", "^.nox/.*$"],
# excludes=[".*\\.gitignore$", ".*/__init__.py"],
# )
#
# if self.dry_run:
# print("Dry run! Would clean up the following files and dirs:")
# print("\n".join(sorted(map(str, files))))
# else:
# for f in files:
# if f.exists():
# if f.is_dir():
# shutil.rmtree(f, ignore_errors=True)
# else:
# f.unlink()
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class DevelopCommand(develop.develop): # pragma: no cover
# def run(self) -> None: # type: ignore
# if not self.dry_run:
# run_antlr(self)
# develop.develop.run(self)
#
# class SDistCommand(sdist.sdist): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run: # type: ignore
# self.run_command("clean")
# run_antlr(self)
# sdist.sdist.run(self)
#
# def find_version(*file_paths: str) -> str:
# root = Path(__file__).parent.parent.absolute()
# with codecs.open(root / Path(*file_paths), "r") as fp: # type: ignore
# version_file = fp.read()
# version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
# if version_match:
# return version_match.group(1)
# raise RuntimeError("Unable to find version string.") # pragma: no cover
. Output only the next line. | "clean": CleanCommand, |
Given the following code snippet before the placeholder: <|code_start|># type: ignore
"""
OmegaConf setup
Instructions:
# Build:
rm -rf dist/ omegaconf.egg-info/
python -m build
# Upload:
twine upload dist/*
"""
with pathlib.Path("requirements/base.txt").open() as requirements_txt:
install_requires = [
str(requirement)
for requirement in pkg_resources.parse_requirements(requirements_txt)
]
with open("README.md", "r") as fh:
LONG_DESC = fh.read()
setuptools.setup(
cmdclass={
"antlr": ANTLRCommand,
"clean": CleanCommand,
"sdist": SDistCommand,
"build_py": BuildPyCommand,
<|code_end|>
, predict the next line using imports from the current file:
import pathlib
import pkg_resources
import setuptools
from build_helpers.build_helpers import (
ANTLRCommand,
BuildPyCommand,
CleanCommand,
DevelopCommand,
SDistCommand,
find_version,
)
and context including class names, function names, and sometimes code from other files:
# Path: build_helpers/build_helpers.py
# class ANTLRCommand(Command): # type: ignore # pragma: no cover
# """Generate parsers using ANTLR."""
#
# description = "Run ANTLR"
# user_options: List[str] = []
#
# def run(self) -> None:
# """Run command."""
# build_dir = Path(__file__).parent.absolute()
# project_root = build_dir.parent
# for grammar in [
# "OmegaConfGrammarLexer.g4",
# "OmegaConfGrammarParser.g4",
# ]:
# command = [
# "java",
# "-jar",
# str(build_dir / "bin" / "antlr-4.8-complete.jar"),
# "-Dlanguage=Python3",
# "-o",
# str(project_root / "omegaconf" / "grammar" / "gen"),
# "-Xexact-output-dir",
# "-visitor",
# str(project_root / "omegaconf" / "grammar" / grammar),
# ]
#
# self.announce(
# f"Generating parser for Python3: {command}",
# level=distutils.log.INFO,
# )
#
# subprocess.check_call(command)
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class BuildPyCommand(build_py.build_py): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run:
# self.run_command("clean")
# run_antlr(self)
# build_py.build_py.run(self)
#
# class CleanCommand(Command): # type: ignore # pragma: no cover
# """
# Our custom command to clean out junk files.
# """
#
# description = "Cleans out generated and junk files we don't want in the repo"
# dry_run: bool
# user_options: List[str] = []
#
# def run(self) -> None:
# root = Path(__file__).parent.parent.absolute()
# files = find(
# root=root,
# include_files=["^omegaconf/grammar/gen/.*"],
# include_dirs=[
# "^omegaconf\\.egg-info$",
# "\\.eggs$",
# "^\\.mypy_cache$",
# "^\\.pytest_cache$",
# ".*/__pycache__$",
# "^__pycache__$",
# "^build$",
# ],
# scan_exclude=["^.git$", "^.nox/.*$"],
# excludes=[".*\\.gitignore$", ".*/__init__.py"],
# )
#
# if self.dry_run:
# print("Dry run! Would clean up the following files and dirs:")
# print("\n".join(sorted(map(str, files))))
# else:
# for f in files:
# if f.exists():
# if f.is_dir():
# shutil.rmtree(f, ignore_errors=True)
# else:
# f.unlink()
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class DevelopCommand(develop.develop): # pragma: no cover
# def run(self) -> None: # type: ignore
# if not self.dry_run:
# run_antlr(self)
# develop.develop.run(self)
#
# class SDistCommand(sdist.sdist): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run: # type: ignore
# self.run_command("clean")
# run_antlr(self)
# sdist.sdist.run(self)
#
# def find_version(*file_paths: str) -> str:
# root = Path(__file__).parent.parent.absolute()
# with codecs.open(root / Path(*file_paths), "r") as fp: # type: ignore
# version_file = fp.read()
# version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
# if version_match:
# return version_match.group(1)
# raise RuntimeError("Unable to find version string.") # pragma: no cover
. Output only the next line. | "develop": DevelopCommand, |
Here is a snippet: <|code_start|># type: ignore
"""
OmegaConf setup
Instructions:
# Build:
rm -rf dist/ omegaconf.egg-info/
python -m build
# Upload:
twine upload dist/*
"""
with pathlib.Path("requirements/base.txt").open() as requirements_txt:
install_requires = [
str(requirement)
for requirement in pkg_resources.parse_requirements(requirements_txt)
]
with open("README.md", "r") as fh:
LONG_DESC = fh.read()
setuptools.setup(
cmdclass={
"antlr": ANTLRCommand,
"clean": CleanCommand,
<|code_end|>
. Write the next line using the current file imports:
import pathlib
import pkg_resources
import setuptools
from build_helpers.build_helpers import (
ANTLRCommand,
BuildPyCommand,
CleanCommand,
DevelopCommand,
SDistCommand,
find_version,
)
and context from other files:
# Path: build_helpers/build_helpers.py
# class ANTLRCommand(Command): # type: ignore # pragma: no cover
# """Generate parsers using ANTLR."""
#
# description = "Run ANTLR"
# user_options: List[str] = []
#
# def run(self) -> None:
# """Run command."""
# build_dir = Path(__file__).parent.absolute()
# project_root = build_dir.parent
# for grammar in [
# "OmegaConfGrammarLexer.g4",
# "OmegaConfGrammarParser.g4",
# ]:
# command = [
# "java",
# "-jar",
# str(build_dir / "bin" / "antlr-4.8-complete.jar"),
# "-Dlanguage=Python3",
# "-o",
# str(project_root / "omegaconf" / "grammar" / "gen"),
# "-Xexact-output-dir",
# "-visitor",
# str(project_root / "omegaconf" / "grammar" / grammar),
# ]
#
# self.announce(
# f"Generating parser for Python3: {command}",
# level=distutils.log.INFO,
# )
#
# subprocess.check_call(command)
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class BuildPyCommand(build_py.build_py): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run:
# self.run_command("clean")
# run_antlr(self)
# build_py.build_py.run(self)
#
# class CleanCommand(Command): # type: ignore # pragma: no cover
# """
# Our custom command to clean out junk files.
# """
#
# description = "Cleans out generated and junk files we don't want in the repo"
# dry_run: bool
# user_options: List[str] = []
#
# def run(self) -> None:
# root = Path(__file__).parent.parent.absolute()
# files = find(
# root=root,
# include_files=["^omegaconf/grammar/gen/.*"],
# include_dirs=[
# "^omegaconf\\.egg-info$",
# "\\.eggs$",
# "^\\.mypy_cache$",
# "^\\.pytest_cache$",
# ".*/__pycache__$",
# "^__pycache__$",
# "^build$",
# ],
# scan_exclude=["^.git$", "^.nox/.*$"],
# excludes=[".*\\.gitignore$", ".*/__init__.py"],
# )
#
# if self.dry_run:
# print("Dry run! Would clean up the following files and dirs:")
# print("\n".join(sorted(map(str, files))))
# else:
# for f in files:
# if f.exists():
# if f.is_dir():
# shutil.rmtree(f, ignore_errors=True)
# else:
# f.unlink()
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class DevelopCommand(develop.develop): # pragma: no cover
# def run(self) -> None: # type: ignore
# if not self.dry_run:
# run_antlr(self)
# develop.develop.run(self)
#
# class SDistCommand(sdist.sdist): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run: # type: ignore
# self.run_command("clean")
# run_antlr(self)
# sdist.sdist.run(self)
#
# def find_version(*file_paths: str) -> str:
# root = Path(__file__).parent.parent.absolute()
# with codecs.open(root / Path(*file_paths), "r") as fp: # type: ignore
# version_file = fp.read()
# version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
# if version_match:
# return version_match.group(1)
# raise RuntimeError("Unable to find version string.") # pragma: no cover
, which may include functions, classes, or code. Output only the next line. | "sdist": SDistCommand, |
Next line prediction: <|code_start|>"""
OmegaConf setup
Instructions:
# Build:
rm -rf dist/ omegaconf.egg-info/
python -m build
# Upload:
twine upload dist/*
"""
with pathlib.Path("requirements/base.txt").open() as requirements_txt:
install_requires = [
str(requirement)
for requirement in pkg_resources.parse_requirements(requirements_txt)
]
with open("README.md", "r") as fh:
LONG_DESC = fh.read()
setuptools.setup(
cmdclass={
"antlr": ANTLRCommand,
"clean": CleanCommand,
"sdist": SDistCommand,
"build_py": BuildPyCommand,
"develop": DevelopCommand,
},
name="omegaconf",
<|code_end|>
. Use current file imports:
(import pathlib
import pkg_resources
import setuptools
from build_helpers.build_helpers import (
ANTLRCommand,
BuildPyCommand,
CleanCommand,
DevelopCommand,
SDistCommand,
find_version,
))
and context including class names, function names, or small code snippets from other files:
# Path: build_helpers/build_helpers.py
# class ANTLRCommand(Command): # type: ignore # pragma: no cover
# """Generate parsers using ANTLR."""
#
# description = "Run ANTLR"
# user_options: List[str] = []
#
# def run(self) -> None:
# """Run command."""
# build_dir = Path(__file__).parent.absolute()
# project_root = build_dir.parent
# for grammar in [
# "OmegaConfGrammarLexer.g4",
# "OmegaConfGrammarParser.g4",
# ]:
# command = [
# "java",
# "-jar",
# str(build_dir / "bin" / "antlr-4.8-complete.jar"),
# "-Dlanguage=Python3",
# "-o",
# str(project_root / "omegaconf" / "grammar" / "gen"),
# "-Xexact-output-dir",
# "-visitor",
# str(project_root / "omegaconf" / "grammar" / grammar),
# ]
#
# self.announce(
# f"Generating parser for Python3: {command}",
# level=distutils.log.INFO,
# )
#
# subprocess.check_call(command)
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class BuildPyCommand(build_py.build_py): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run:
# self.run_command("clean")
# run_antlr(self)
# build_py.build_py.run(self)
#
# class CleanCommand(Command): # type: ignore # pragma: no cover
# """
# Our custom command to clean out junk files.
# """
#
# description = "Cleans out generated and junk files we don't want in the repo"
# dry_run: bool
# user_options: List[str] = []
#
# def run(self) -> None:
# root = Path(__file__).parent.parent.absolute()
# files = find(
# root=root,
# include_files=["^omegaconf/grammar/gen/.*"],
# include_dirs=[
# "^omegaconf\\.egg-info$",
# "\\.eggs$",
# "^\\.mypy_cache$",
# "^\\.pytest_cache$",
# ".*/__pycache__$",
# "^__pycache__$",
# "^build$",
# ],
# scan_exclude=["^.git$", "^.nox/.*$"],
# excludes=[".*\\.gitignore$", ".*/__init__.py"],
# )
#
# if self.dry_run:
# print("Dry run! Would clean up the following files and dirs:")
# print("\n".join(sorted(map(str, files))))
# else:
# for f in files:
# if f.exists():
# if f.is_dir():
# shutil.rmtree(f, ignore_errors=True)
# else:
# f.unlink()
#
# def initialize_options(self) -> None:
# pass
#
# def finalize_options(self) -> None:
# pass
#
# class DevelopCommand(develop.develop): # pragma: no cover
# def run(self) -> None: # type: ignore
# if not self.dry_run:
# run_antlr(self)
# develop.develop.run(self)
#
# class SDistCommand(sdist.sdist): # pragma: no cover
# def run(self) -> None:
# if not self.dry_run: # type: ignore
# self.run_command("clean")
# run_antlr(self)
# sdist.sdist.run(self)
#
# def find_version(*file_paths: str) -> str:
# root = Path(__file__).parent.parent.absolute()
# with codecs.open(root / Path(*file_paths), "r") as fp: # type: ignore
# version_file = fp.read()
# version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
# if version_match:
# return version_match.group(1)
# raise RuntimeError("Unable to find version string.") # pragma: no cover
. Output only the next line. | version=find_version("omegaconf", "version.py"), |
Based on the snippet: <|code_start|> "test_files",
["^.*/junk.txt"],
[],
[],
[],
["a/b/junk.txt", "c/junk.txt"],
id="junk_only",
),
pytest.param("test_files", [], ["^a$"], [], [], ["a"], id="exact_a"),
pytest.param(
"test_files",
[],
[".*bad_dir$"],
[],
[],
["a/b/bad_dir", "c/bad_dir"],
id="bad_dirs",
),
],
)
def test_find(
path_rel: str,
include_files: List[str],
include_dirs: List[str],
excludes: List[str],
scan_exclude: List[str],
expected: List[str],
) -> None:
basedir = Path(__file__).parent.absolute()
path = basedir / path_rel
<|code_end|>
, predict the immediate next line with the help of imports:
from pathlib import Path
from typing import List
from build_helpers.build_helpers import find, find_version, matches
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: build_helpers/build_helpers.py
# def find(
# root: Path,
# include_files: List[str],
# include_dirs: List[str],
# excludes: List[str],
# rbase: Optional[Path] = None,
# scan_exclude: Optional[List[str]] = None,
# ) -> List[Path]:
# if rbase is None:
# rbase = Path()
# if scan_exclude is None:
# scan_exclude = []
# files = []
# scan_root = root / rbase
# for entry in scan_root.iterdir():
# path = rbase / entry.name
# if matches(scan_exclude, path):
# continue
#
# if entry.is_dir():
# if matches(include_dirs, path):
# if not matches(excludes, path):
# files.append(path)
# else:
# ret = find(
# root=root,
# include_files=include_files,
# include_dirs=include_dirs,
# excludes=excludes,
# rbase=path,
# scan_exclude=scan_exclude,
# )
# files.extend(ret)
# else:
# if matches(include_files, path) and not matches(excludes, path):
# files.append(path)
#
# return files
#
# def find_version(*file_paths: str) -> str:
# root = Path(__file__).parent.parent.absolute()
# with codecs.open(root / Path(*file_paths), "r") as fp: # type: ignore
# version_file = fp.read()
# version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
# if version_match:
# return version_match.group(1)
# raise RuntimeError("Unable to find version string.") # pragma: no cover
#
# def matches(patterns: List[str], path: Path) -> bool:
# string = str(path).replace(os.sep, "/") # for Windows
# for pattern in patterns:
# if re.match(pattern, string):
# return True
# return False
. Output only the next line. | ret = find( |
Based on the snippet: <|code_start|> expected: List[str],
) -> None:
basedir = Path(__file__).parent.absolute()
path = basedir / path_rel
ret = find(
root=path,
excludes=excludes,
include_files=include_files,
include_dirs=include_dirs,
scan_exclude=scan_exclude,
)
ret_set = set([str(x) for x in ret])
expected_set = set([str(Path(x)) for x in expected])
assert ret_set == expected_set
@pytest.mark.parametrize(
"patterns,query,expected",
[
(["^a/.*"], Path("a") / "b.txt", True),
(["^/foo/bar/.*"], Path("/foo") / "bar" / "blag", True),
],
)
def test_matches(patterns: List[str], query: Path, expected: bool) -> None:
ret = matches(patterns, query)
assert ret == expected
def test_find_version() -> None:
<|code_end|>
, predict the immediate next line with the help of imports:
from pathlib import Path
from typing import List
from build_helpers.build_helpers import find, find_version, matches
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: build_helpers/build_helpers.py
# def find(
# root: Path,
# include_files: List[str],
# include_dirs: List[str],
# excludes: List[str],
# rbase: Optional[Path] = None,
# scan_exclude: Optional[List[str]] = None,
# ) -> List[Path]:
# if rbase is None:
# rbase = Path()
# if scan_exclude is None:
# scan_exclude = []
# files = []
# scan_root = root / rbase
# for entry in scan_root.iterdir():
# path = rbase / entry.name
# if matches(scan_exclude, path):
# continue
#
# if entry.is_dir():
# if matches(include_dirs, path):
# if not matches(excludes, path):
# files.append(path)
# else:
# ret = find(
# root=root,
# include_files=include_files,
# include_dirs=include_dirs,
# excludes=excludes,
# rbase=path,
# scan_exclude=scan_exclude,
# )
# files.extend(ret)
# else:
# if matches(include_files, path) and not matches(excludes, path):
# files.append(path)
#
# return files
#
# def find_version(*file_paths: str) -> str:
# root = Path(__file__).parent.parent.absolute()
# with codecs.open(root / Path(*file_paths), "r") as fp: # type: ignore
# version_file = fp.read()
# version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
# if version_match:
# return version_match.group(1)
# raise RuntimeError("Unable to find version string.") # pragma: no cover
#
# def matches(patterns: List[str], path: Path) -> bool:
# string = str(path).replace(os.sep, "/") # for Windows
# for pattern in patterns:
# if re.match(pattern, string):
# return True
# return False
. Output only the next line. | version = find_version("omegaconf", "version.py") |
Given the code snippet: <|code_start|> path_rel: str,
include_files: List[str],
include_dirs: List[str],
excludes: List[str],
scan_exclude: List[str],
expected: List[str],
) -> None:
basedir = Path(__file__).parent.absolute()
path = basedir / path_rel
ret = find(
root=path,
excludes=excludes,
include_files=include_files,
include_dirs=include_dirs,
scan_exclude=scan_exclude,
)
ret_set = set([str(x) for x in ret])
expected_set = set([str(Path(x)) for x in expected])
assert ret_set == expected_set
@pytest.mark.parametrize(
"patterns,query,expected",
[
(["^a/.*"], Path("a") / "b.txt", True),
(["^/foo/bar/.*"], Path("/foo") / "bar" / "blag", True),
],
)
def test_matches(patterns: List[str], query: Path, expected: bool) -> None:
<|code_end|>
, generate the next line using the imports in this file:
from pathlib import Path
from typing import List
from build_helpers.build_helpers import find, find_version, matches
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: build_helpers/build_helpers.py
# def find(
# root: Path,
# include_files: List[str],
# include_dirs: List[str],
# excludes: List[str],
# rbase: Optional[Path] = None,
# scan_exclude: Optional[List[str]] = None,
# ) -> List[Path]:
# if rbase is None:
# rbase = Path()
# if scan_exclude is None:
# scan_exclude = []
# files = []
# scan_root = root / rbase
# for entry in scan_root.iterdir():
# path = rbase / entry.name
# if matches(scan_exclude, path):
# continue
#
# if entry.is_dir():
# if matches(include_dirs, path):
# if not matches(excludes, path):
# files.append(path)
# else:
# ret = find(
# root=root,
# include_files=include_files,
# include_dirs=include_dirs,
# excludes=excludes,
# rbase=path,
# scan_exclude=scan_exclude,
# )
# files.extend(ret)
# else:
# if matches(include_files, path) and not matches(excludes, path):
# files.append(path)
#
# return files
#
# def find_version(*file_paths: str) -> str:
# root = Path(__file__).parent.parent.absolute()
# with codecs.open(root / Path(*file_paths), "r") as fp: # type: ignore
# version_file = fp.read()
# version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
# if version_match:
# return version_match.group(1)
# raise RuntimeError("Unable to find version string.") # pragma: no cover
#
# def matches(patterns: List[str], path: Path) -> bool:
# string = str(path).replace(os.sep, "/") # for Windows
# for pattern in patterns:
# if re.match(pattern, string):
# return True
# return False
. Output only the next line. | ret = matches(patterns, query) |
Given snippet: <|code_start|> FULL_KEY=full_key,
VALUE=value,
VALUE_TYPE=type_str(type(value), include_module_name=True),
KEY_TYPE=f"{type(key).__name__}",
)
if ref_type not in (None, Any):
template = dedent(
"""\
$MSG
full_key: $FULL_KEY
reference_type=$REF_TYPE
object_type=$OBJECT_TYPE"""
)
else:
template = dedent(
"""\
$MSG
full_key: $FULL_KEY
object_type=$OBJECT_TYPE"""
)
s = string.Template(template=template)
message = s.substitute(
REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key
)
exception_type = type(cause) if type_override is None else type_override
if exception_type == TypeError:
exception_type = ConfigTypeError
elif exception_type == IndexError:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import os
import re
import string
import sys
import warnings
import yaml
import dataclasses
import attr
import typing # lgtm [py/import-and-import-from]
from contextlib import contextmanager
from enum import Enum
from textwrap import dedent
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union,
get_type_hints,
)
from .errors import (
ConfigIndexError,
ConfigTypeError,
ConfigValueError,
GrammarParseError,
OmegaConfBaseException,
ValidationError,
)
from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse
from importlib import import_module
from .base import Container, Node
from omegaconf.omegaconf import _maybe_wrap
from omegaconf.omegaconf import OmegaConf, _maybe_wrap
from omegaconf import MISSING
from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap
from omegaconf.base import Node
from omegaconf.base import Node
from omegaconf import Node
from omegaconf import Node
from .base import Container
from omegaconf import DictKeyType
from .base import Container
from .nodes import ValueNode
from omegaconf import Container, Node
from omegaconf import OmegaConf
from omegaconf.base import Node
from omegaconf import OmegaConf
and context:
# Path: omegaconf/errors.py
# class ConfigIndexError(OmegaConfBaseException, IndexError):
# """
# Thrown from a config object when a regular access would have caused an IndexError.
# """
#
# class ConfigTypeError(OmegaConfBaseException, TypeError):
# """
# Thrown from a config object when a regular access would have caused a TypeError.
# """
#
# class ConfigValueError(OmegaConfBaseException, ValueError):
# """
# Thrown from a config object when a regular access would have caused a ValueError.
# """
#
# class GrammarParseError(OmegaConfBaseException):
# """
# Thrown when failing to parse an expression according to the ANTLR grammar.
# """
#
# class OmegaConfBaseException(Exception):
# # would ideally be typed Optional[Node]
# parent_node: Any
# child_node: Any
# key: Any
# full_key: Optional[str]
# value: Any
# msg: Optional[str]
# cause: Optional[Exception]
# object_type: Optional[Type[Any]]
# object_type_str: Optional[str]
# ref_type: Optional[Type[Any]]
# ref_type_str: Optional[str]
#
# _initialized: bool = False
#
# def __init__(self, *_args: Any, **_kwargs: Any) -> None:
# self.parent_node = None
# self.child_node = None
# self.key = None
# self.full_key = None
# self.value = None
# self.msg = None
# self.object_type = None
# self.ref_type = None
#
# class ValidationError(OmegaConfBaseException, ValueError):
# """
# Thrown when a value fails validation
# """
#
# Path: omegaconf/grammar_parser.py
# SIMPLE_INTERPOLATION_PATTERN = re.compile(
# f"({_outer})?({_inter}({_outer})?)+$", flags=re.ASCII
# )
#
# def parse(
# value: str, parser_rule: str = "configValue", lexer_mode: str = "DEFAULT_MODE"
# ) -> ParserRuleContext:
# """
# Parse interpolated string `value` (and return the parse tree).
# """
# l_mode = getattr(OmegaConfGrammarLexer, lexer_mode)
# istream = InputStream(value)
#
# cached = getattr(_grammar_cache, "data", None)
# if cached is None:
# error_listener = OmegaConfErrorListener()
# lexer = OmegaConfGrammarLexer(istream)
# lexer.removeErrorListeners()
# lexer.addErrorListener(error_listener)
# lexer.mode(l_mode)
# token_stream = CommonTokenStream(lexer)
# parser = OmegaConfGrammarParser(token_stream)
# parser.removeErrorListeners()
# parser.addErrorListener(error_listener)
#
# # The two lines below could be enabled in the future if we decide to switch
# # to SLL prediction mode. Warning though, it has not been fully tested yet!
# # from antlr4 import PredictionMode
# # parser._interp.predictionMode = PredictionMode.SLL
#
# # Note that although the input stream `istream` is implicitly cached within
# # the lexer, it will be replaced by a new input next time the lexer is re-used.
# _grammar_cache.data = lexer, token_stream, parser
#
# else:
# lexer, token_stream, parser = cached
# # Replace the old input stream with the new one.
# lexer.inputStream = istream
# # Initialize the lexer / token stream / parser to process the new input.
# lexer.mode(l_mode)
# token_stream.setTokenSource(lexer)
# parser.reset()
#
# try:
# return getattr(parser, parser_rule)()
# except Exception as exc:
# if type(exc) is Exception and str(exc) == "Empty Stack":
# # This exception is raised by antlr when trying to pop a mode while
# # no mode has been pushed. We convert it into an `GrammarParseError`
# # to facilitate exception handling from the caller.
# raise GrammarParseError("Empty Stack")
# else:
# raise
which might include code, classes, or functions. Output only the next line. | exception_type = ConfigIndexError |
Given the code snippet: <|code_start|> OBJECT_TYPE=object_type_str,
KEY=key,
FULL_KEY=full_key,
VALUE=value,
VALUE_TYPE=type_str(type(value), include_module_name=True),
KEY_TYPE=f"{type(key).__name__}",
)
if ref_type not in (None, Any):
template = dedent(
"""\
$MSG
full_key: $FULL_KEY
reference_type=$REF_TYPE
object_type=$OBJECT_TYPE"""
)
else:
template = dedent(
"""\
$MSG
full_key: $FULL_KEY
object_type=$OBJECT_TYPE"""
)
s = string.Template(template=template)
message = s.substitute(
REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key
)
exception_type = type(cause) if type_override is None else type_override
if exception_type == TypeError:
<|code_end|>
, generate the next line using the imports in this file:
import copy
import os
import re
import string
import sys
import warnings
import yaml
import dataclasses
import attr
import typing # lgtm [py/import-and-import-from]
from contextlib import contextmanager
from enum import Enum
from textwrap import dedent
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union,
get_type_hints,
)
from .errors import (
ConfigIndexError,
ConfigTypeError,
ConfigValueError,
GrammarParseError,
OmegaConfBaseException,
ValidationError,
)
from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse
from importlib import import_module
from .base import Container, Node
from omegaconf.omegaconf import _maybe_wrap
from omegaconf.omegaconf import OmegaConf, _maybe_wrap
from omegaconf import MISSING
from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap
from omegaconf.base import Node
from omegaconf.base import Node
from omegaconf import Node
from omegaconf import Node
from .base import Container
from omegaconf import DictKeyType
from .base import Container
from .nodes import ValueNode
from omegaconf import Container, Node
from omegaconf import OmegaConf
from omegaconf.base import Node
from omegaconf import OmegaConf
and context (functions, classes, or occasionally code) from other files:
# Path: omegaconf/errors.py
# class ConfigIndexError(OmegaConfBaseException, IndexError):
# """
# Thrown from a config object when a regular access would have caused an IndexError.
# """
#
# class ConfigTypeError(OmegaConfBaseException, TypeError):
# """
# Thrown from a config object when a regular access would have caused a TypeError.
# """
#
# class ConfigValueError(OmegaConfBaseException, ValueError):
# """
# Thrown from a config object when a regular access would have caused a ValueError.
# """
#
# class GrammarParseError(OmegaConfBaseException):
# """
# Thrown when failing to parse an expression according to the ANTLR grammar.
# """
#
# class OmegaConfBaseException(Exception):
# # would ideally be typed Optional[Node]
# parent_node: Any
# child_node: Any
# key: Any
# full_key: Optional[str]
# value: Any
# msg: Optional[str]
# cause: Optional[Exception]
# object_type: Optional[Type[Any]]
# object_type_str: Optional[str]
# ref_type: Optional[Type[Any]]
# ref_type_str: Optional[str]
#
# _initialized: bool = False
#
# def __init__(self, *_args: Any, **_kwargs: Any) -> None:
# self.parent_node = None
# self.child_node = None
# self.key = None
# self.full_key = None
# self.value = None
# self.msg = None
# self.object_type = None
# self.ref_type = None
#
# class ValidationError(OmegaConfBaseException, ValueError):
# """
# Thrown when a value fails validation
# """
#
# Path: omegaconf/grammar_parser.py
# SIMPLE_INTERPOLATION_PATTERN = re.compile(
# f"({_outer})?({_inter}({_outer})?)+$", flags=re.ASCII
# )
#
# def parse(
# value: str, parser_rule: str = "configValue", lexer_mode: str = "DEFAULT_MODE"
# ) -> ParserRuleContext:
# """
# Parse interpolated string `value` (and return the parse tree).
# """
# l_mode = getattr(OmegaConfGrammarLexer, lexer_mode)
# istream = InputStream(value)
#
# cached = getattr(_grammar_cache, "data", None)
# if cached is None:
# error_listener = OmegaConfErrorListener()
# lexer = OmegaConfGrammarLexer(istream)
# lexer.removeErrorListeners()
# lexer.addErrorListener(error_listener)
# lexer.mode(l_mode)
# token_stream = CommonTokenStream(lexer)
# parser = OmegaConfGrammarParser(token_stream)
# parser.removeErrorListeners()
# parser.addErrorListener(error_listener)
#
# # The two lines below could be enabled in the future if we decide to switch
# # to SLL prediction mode. Warning though, it has not been fully tested yet!
# # from antlr4 import PredictionMode
# # parser._interp.predictionMode = PredictionMode.SLL
#
# # Note that although the input stream `istream` is implicitly cached within
# # the lexer, it will be replaced by a new input next time the lexer is re-used.
# _grammar_cache.data = lexer, token_stream, parser
#
# else:
# lexer, token_stream, parser = cached
# # Replace the old input stream with the new one.
# lexer.inputStream = istream
# # Initialize the lexer / token stream / parser to process the new input.
# lexer.mode(l_mode)
# token_stream.setTokenSource(lexer)
# parser.reset()
#
# try:
# return getattr(parser, parser_rule)()
# except Exception as exc:
# if type(exc) is Exception and str(exc) == "Empty Stack":
# # This exception is raised by antlr when trying to pop a mode while
# # no mode has been pushed. We convert it into an `GrammarParseError`
# # to facilitate exception handling from the caller.
# raise GrammarParseError("Empty Stack")
# else:
# raise
. Output only the next line. | exception_type = ConfigTypeError |
Given snippet: <|code_start|> return None
def get_attr_class_field_names(obj: Any) -> List[str]:
is_type = isinstance(obj, type)
obj_type = obj if is_type else type(obj)
return list(attr.fields_dict(obj_type))
def get_attr_data(obj: Any, allow_objects: Optional[bool] = None) -> Dict[str, Any]:
flags = {"allow_objects": allow_objects} if allow_objects is not None else {}
d = {}
is_type = isinstance(obj, type)
obj_type = obj if is_type else type(obj)
dummy_parent = OmegaConf.create({}, flags=flags)
dummy_parent._metadata.object_type = obj_type
for name, attrib in attr.fields_dict(obj_type).items():
is_optional, type_ = _resolve_optional(attrib.type)
type_ = _resolve_forward(type_, obj.__module__)
if not is_type:
value = getattr(obj, name)
else:
value = attrib.default
if value == attr.NOTHING:
value = MISSING
if _is_union(type_):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import os
import re
import string
import sys
import warnings
import yaml
import dataclasses
import attr
import typing # lgtm [py/import-and-import-from]
from contextlib import contextmanager
from enum import Enum
from textwrap import dedent
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union,
get_type_hints,
)
from .errors import (
ConfigIndexError,
ConfigTypeError,
ConfigValueError,
GrammarParseError,
OmegaConfBaseException,
ValidationError,
)
from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse
from importlib import import_module
from .base import Container, Node
from omegaconf.omegaconf import _maybe_wrap
from omegaconf.omegaconf import OmegaConf, _maybe_wrap
from omegaconf import MISSING
from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap
from omegaconf.base import Node
from omegaconf.base import Node
from omegaconf import Node
from omegaconf import Node
from .base import Container
from omegaconf import DictKeyType
from .base import Container
from .nodes import ValueNode
from omegaconf import Container, Node
from omegaconf import OmegaConf
from omegaconf.base import Node
from omegaconf import OmegaConf
and context:
# Path: omegaconf/errors.py
# class ConfigIndexError(OmegaConfBaseException, IndexError):
# """
# Thrown from a config object when a regular access would have caused an IndexError.
# """
#
# class ConfigTypeError(OmegaConfBaseException, TypeError):
# """
# Thrown from a config object when a regular access would have caused a TypeError.
# """
#
# class ConfigValueError(OmegaConfBaseException, ValueError):
# """
# Thrown from a config object when a regular access would have caused a ValueError.
# """
#
# class GrammarParseError(OmegaConfBaseException):
# """
# Thrown when failing to parse an expression according to the ANTLR grammar.
# """
#
# class OmegaConfBaseException(Exception):
# # would ideally be typed Optional[Node]
# parent_node: Any
# child_node: Any
# key: Any
# full_key: Optional[str]
# value: Any
# msg: Optional[str]
# cause: Optional[Exception]
# object_type: Optional[Type[Any]]
# object_type_str: Optional[str]
# ref_type: Optional[Type[Any]]
# ref_type_str: Optional[str]
#
# _initialized: bool = False
#
# def __init__(self, *_args: Any, **_kwargs: Any) -> None:
# self.parent_node = None
# self.child_node = None
# self.key = None
# self.full_key = None
# self.value = None
# self.msg = None
# self.object_type = None
# self.ref_type = None
#
# class ValidationError(OmegaConfBaseException, ValueError):
# """
# Thrown when a value fails validation
# """
#
# Path: omegaconf/grammar_parser.py
# SIMPLE_INTERPOLATION_PATTERN = re.compile(
# f"({_outer})?({_inter}({_outer})?)+$", flags=re.ASCII
# )
#
# def parse(
# value: str, parser_rule: str = "configValue", lexer_mode: str = "DEFAULT_MODE"
# ) -> ParserRuleContext:
# """
# Parse interpolated string `value` (and return the parse tree).
# """
# l_mode = getattr(OmegaConfGrammarLexer, lexer_mode)
# istream = InputStream(value)
#
# cached = getattr(_grammar_cache, "data", None)
# if cached is None:
# error_listener = OmegaConfErrorListener()
# lexer = OmegaConfGrammarLexer(istream)
# lexer.removeErrorListeners()
# lexer.addErrorListener(error_listener)
# lexer.mode(l_mode)
# token_stream = CommonTokenStream(lexer)
# parser = OmegaConfGrammarParser(token_stream)
# parser.removeErrorListeners()
# parser.addErrorListener(error_listener)
#
# # The two lines below could be enabled in the future if we decide to switch
# # to SLL prediction mode. Warning though, it has not been fully tested yet!
# # from antlr4 import PredictionMode
# # parser._interp.predictionMode = PredictionMode.SLL
#
# # Note that although the input stream `istream` is implicitly cached within
# # the lexer, it will be replaced by a new input next time the lexer is re-used.
# _grammar_cache.data = lexer, token_stream, parser
#
# else:
# lexer, token_stream, parser = cached
# # Replace the old input stream with the new one.
# lexer.inputStream = istream
# # Initialize the lexer / token stream / parser to process the new input.
# lexer.mode(l_mode)
# token_stream.setTokenSource(lexer)
# parser.reset()
#
# try:
# return getattr(parser, parser_rule)()
# except Exception as exc:
# if type(exc) is Exception and str(exc) == "Empty Stack":
# # This exception is raised by antlr when trying to pop a mode while
# # no mode has been pushed. We convert it into an `GrammarParseError`
# # to facilitate exception handling from the caller.
# raise GrammarParseError("Empty Stack")
# else:
# raise
which might include code, classes, or functions. Output only the next line. | e = ConfigValueError( |
Based on the snippet: <|code_start|>
d = {}
is_type = isinstance(obj, type)
obj_type = obj if is_type else type(obj)
dummy_parent = OmegaConf.create({}, flags=flags)
dummy_parent._metadata.object_type = obj_type
for name, attrib in attr.fields_dict(obj_type).items():
is_optional, type_ = _resolve_optional(attrib.type)
type_ = _resolve_forward(type_, obj.__module__)
if not is_type:
value = getattr(obj, name)
else:
value = attrib.default
if value == attr.NOTHING:
value = MISSING
if _is_union(type_):
e = ConfigValueError(
f"Union types are not supported:\n{name}: {type_str(type_)}"
)
format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e))
try:
d[name] = _maybe_wrap(
ref_type=type_,
is_optional=is_optional,
key=name,
value=value,
parent=dummy_parent,
)
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
import os
import re
import string
import sys
import warnings
import yaml
import dataclasses
import attr
import typing # lgtm [py/import-and-import-from]
from contextlib import contextmanager
from enum import Enum
from textwrap import dedent
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union,
get_type_hints,
)
from .errors import (
ConfigIndexError,
ConfigTypeError,
ConfigValueError,
GrammarParseError,
OmegaConfBaseException,
ValidationError,
)
from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse
from importlib import import_module
from .base import Container, Node
from omegaconf.omegaconf import _maybe_wrap
from omegaconf.omegaconf import OmegaConf, _maybe_wrap
from omegaconf import MISSING
from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap
from omegaconf.base import Node
from omegaconf.base import Node
from omegaconf import Node
from omegaconf import Node
from .base import Container
from omegaconf import DictKeyType
from .base import Container
from .nodes import ValueNode
from omegaconf import Container, Node
from omegaconf import OmegaConf
from omegaconf.base import Node
from omegaconf import OmegaConf
and context (classes, functions, sometimes code) from other files:
# Path: omegaconf/errors.py
# class ConfigIndexError(OmegaConfBaseException, IndexError):
# """
# Thrown from a config object when a regular access would have caused an IndexError.
# """
#
# class ConfigTypeError(OmegaConfBaseException, TypeError):
# """
# Thrown from a config object when a regular access would have caused a TypeError.
# """
#
# class ConfigValueError(OmegaConfBaseException, ValueError):
# """
# Thrown from a config object when a regular access would have caused a ValueError.
# """
#
# class GrammarParseError(OmegaConfBaseException):
# """
# Thrown when failing to parse an expression according to the ANTLR grammar.
# """
#
# class OmegaConfBaseException(Exception):
# # would ideally be typed Optional[Node]
# parent_node: Any
# child_node: Any
# key: Any
# full_key: Optional[str]
# value: Any
# msg: Optional[str]
# cause: Optional[Exception]
# object_type: Optional[Type[Any]]
# object_type_str: Optional[str]
# ref_type: Optional[Type[Any]]
# ref_type_str: Optional[str]
#
# _initialized: bool = False
#
# def __init__(self, *_args: Any, **_kwargs: Any) -> None:
# self.parent_node = None
# self.child_node = None
# self.key = None
# self.full_key = None
# self.value = None
# self.msg = None
# self.object_type = None
# self.ref_type = None
#
# class ValidationError(OmegaConfBaseException, ValueError):
# """
# Thrown when a value fails validation
# """
#
# Path: omegaconf/grammar_parser.py
# SIMPLE_INTERPOLATION_PATTERN = re.compile(
# f"({_outer})?({_inter}({_outer})?)+$", flags=re.ASCII
# )
#
# def parse(
# value: str, parser_rule: str = "configValue", lexer_mode: str = "DEFAULT_MODE"
# ) -> ParserRuleContext:
# """
# Parse interpolated string `value` (and return the parse tree).
# """
# l_mode = getattr(OmegaConfGrammarLexer, lexer_mode)
# istream = InputStream(value)
#
# cached = getattr(_grammar_cache, "data", None)
# if cached is None:
# error_listener = OmegaConfErrorListener()
# lexer = OmegaConfGrammarLexer(istream)
# lexer.removeErrorListeners()
# lexer.addErrorListener(error_listener)
# lexer.mode(l_mode)
# token_stream = CommonTokenStream(lexer)
# parser = OmegaConfGrammarParser(token_stream)
# parser.removeErrorListeners()
# parser.addErrorListener(error_listener)
#
# # The two lines below could be enabled in the future if we decide to switch
# # to SLL prediction mode. Warning though, it has not been fully tested yet!
# # from antlr4 import PredictionMode
# # parser._interp.predictionMode = PredictionMode.SLL
#
# # Note that although the input stream `istream` is implicitly cached within
# # the lexer, it will be replaced by a new input next time the lexer is re-used.
# _grammar_cache.data = lexer, token_stream, parser
#
# else:
# lexer, token_stream, parser = cached
# # Replace the old input stream with the new one.
# lexer.inputStream = istream
# # Initialize the lexer / token stream / parser to process the new input.
# lexer.mode(l_mode)
# token_stream.setTokenSource(lexer)
# parser.reset()
#
# try:
# return getattr(parser, parser_rule)()
# except Exception as exc:
# if type(exc) is Exception and str(exc) == "Empty Stack":
# # This exception is raised by antlr when trying to pop a mode while
# # no mode has been pushed. We convert it into an `GrammarParseError`
# # to facilitate exception handling from the caller.
# raise GrammarParseError("Empty Stack")
# else:
# raise
. Output only the next line. | except (ValidationError, GrammarParseError) as ex: |
Based on the snippet: <|code_start|> return ref_type
else:
return Any # type: ignore
def _raise(ex: Exception, cause: Exception) -> None:
# Set the environment variable OC_CAUSE=1 to get a stacktrace that includes the
# causing exception.
env_var = os.environ["OC_CAUSE"] if "OC_CAUSE" in os.environ else None
debugging = sys.gettrace() is not None
full_backtrace = (debugging and not env_var == "0") or (env_var == "1")
if full_backtrace:
ex.__cause__ = cause
else:
ex.__cause__ = None
raise ex.with_traceback(sys.exc_info()[2]) # set env var OC_CAUSE=1 for full trace
def format_and_raise(
node: Any,
key: Any,
value: Any,
msg: str,
cause: Exception,
type_override: Any = None,
) -> None:
if isinstance(cause, AssertionError):
raise
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
import os
import re
import string
import sys
import warnings
import yaml
import dataclasses
import attr
import typing # lgtm [py/import-and-import-from]
from contextlib import contextmanager
from enum import Enum
from textwrap import dedent
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union,
get_type_hints,
)
from .errors import (
ConfigIndexError,
ConfigTypeError,
ConfigValueError,
GrammarParseError,
OmegaConfBaseException,
ValidationError,
)
from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse
from importlib import import_module
from .base import Container, Node
from omegaconf.omegaconf import _maybe_wrap
from omegaconf.omegaconf import OmegaConf, _maybe_wrap
from omegaconf import MISSING
from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap
from omegaconf.base import Node
from omegaconf.base import Node
from omegaconf import Node
from omegaconf import Node
from .base import Container
from omegaconf import DictKeyType
from .base import Container
from .nodes import ValueNode
from omegaconf import Container, Node
from omegaconf import OmegaConf
from omegaconf.base import Node
from omegaconf import OmegaConf
and context (classes, functions, sometimes code) from other files:
# Path: omegaconf/errors.py
# class ConfigIndexError(OmegaConfBaseException, IndexError):
# """
# Thrown from a config object when a regular access would have caused an IndexError.
# """
#
# class ConfigTypeError(OmegaConfBaseException, TypeError):
# """
# Thrown from a config object when a regular access would have caused a TypeError.
# """
#
# class ConfigValueError(OmegaConfBaseException, ValueError):
# """
# Thrown from a config object when a regular access would have caused a ValueError.
# """
#
# class GrammarParseError(OmegaConfBaseException):
# """
# Thrown when failing to parse an expression according to the ANTLR grammar.
# """
#
# class OmegaConfBaseException(Exception):
# # would ideally be typed Optional[Node]
# parent_node: Any
# child_node: Any
# key: Any
# full_key: Optional[str]
# value: Any
# msg: Optional[str]
# cause: Optional[Exception]
# object_type: Optional[Type[Any]]
# object_type_str: Optional[str]
# ref_type: Optional[Type[Any]]
# ref_type_str: Optional[str]
#
# _initialized: bool = False
#
# def __init__(self, *_args: Any, **_kwargs: Any) -> None:
# self.parent_node = None
# self.child_node = None
# self.key = None
# self.full_key = None
# self.value = None
# self.msg = None
# self.object_type = None
# self.ref_type = None
#
# class ValidationError(OmegaConfBaseException, ValueError):
# """
# Thrown when a value fails validation
# """
#
# Path: omegaconf/grammar_parser.py
# SIMPLE_INTERPOLATION_PATTERN = re.compile(
# f"({_outer})?({_inter}({_outer})?)+$", flags=re.ASCII
# )
#
# def parse(
# value: str, parser_rule: str = "configValue", lexer_mode: str = "DEFAULT_MODE"
# ) -> ParserRuleContext:
# """
# Parse interpolated string `value` (and return the parse tree).
# """
# l_mode = getattr(OmegaConfGrammarLexer, lexer_mode)
# istream = InputStream(value)
#
# cached = getattr(_grammar_cache, "data", None)
# if cached is None:
# error_listener = OmegaConfErrorListener()
# lexer = OmegaConfGrammarLexer(istream)
# lexer.removeErrorListeners()
# lexer.addErrorListener(error_listener)
# lexer.mode(l_mode)
# token_stream = CommonTokenStream(lexer)
# parser = OmegaConfGrammarParser(token_stream)
# parser.removeErrorListeners()
# parser.addErrorListener(error_listener)
#
# # The two lines below could be enabled in the future if we decide to switch
# # to SLL prediction mode. Warning though, it has not been fully tested yet!
# # from antlr4 import PredictionMode
# # parser._interp.predictionMode = PredictionMode.SLL
#
# # Note that although the input stream `istream` is implicitly cached within
# # the lexer, it will be replaced by a new input next time the lexer is re-used.
# _grammar_cache.data = lexer, token_stream, parser
#
# else:
# lexer, token_stream, parser = cached
# # Replace the old input stream with the new one.
# lexer.inputStream = istream
# # Initialize the lexer / token stream / parser to process the new input.
# lexer.mode(l_mode)
# token_stream.setTokenSource(lexer)
# parser.reset()
#
# try:
# return getattr(parser, parser_rule)()
# except Exception as exc:
# if type(exc) is Exception and str(exc) == "Empty Stack":
# # This exception is raised by antlr when trying to pop a mode while
# # no mode has been pushed. We convert it into an `GrammarParseError`
# # to facilitate exception handling from the caller.
# raise GrammarParseError("Empty Stack")
# else:
# raise
. Output only the next line. | if isinstance(cause, OmegaConfBaseException) and cause._initialized: |
Using the snippet: <|code_start|>
is_type = isinstance(obj, type)
obj_type = obj if is_type else type(obj)
subclasses_dict = is_dict_subclass(obj_type)
if subclasses_dict:
warnings.warn(
f"Class `{obj_type.__name__}` subclasses `Dict`."
+ " Subclassing `Dict` in Structured Config classes is deprecated,"
+ " see github.com/omry/omegaconf/issues/663",
UserWarning,
stacklevel=9,
)
if is_type:
return None
elif subclasses_dict:
dict_subclass_data = {}
key_type, element_type = get_dict_key_value_types(obj_type)
for name, value in obj.items():
is_optional, type_ = _resolve_optional(element_type)
type_ = _resolve_forward(type_, obj.__module__)
try:
dict_subclass_data[name] = _maybe_wrap(
ref_type=type_,
is_optional=is_optional,
key=name,
value=value,
parent=parent,
)
<|code_end|>
, determine the next line of code. You have imports:
import copy
import os
import re
import string
import sys
import warnings
import yaml
import dataclasses
import attr
import typing # lgtm [py/import-and-import-from]
from contextlib import contextmanager
from enum import Enum
from textwrap import dedent
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union,
get_type_hints,
)
from .errors import (
ConfigIndexError,
ConfigTypeError,
ConfigValueError,
GrammarParseError,
OmegaConfBaseException,
ValidationError,
)
from .grammar_parser import SIMPLE_INTERPOLATION_PATTERN, parse
from importlib import import_module
from .base import Container, Node
from omegaconf.omegaconf import _maybe_wrap
from omegaconf.omegaconf import OmegaConf, _maybe_wrap
from omegaconf import MISSING
from omegaconf.omegaconf import MISSING, OmegaConf, _maybe_wrap
from omegaconf.base import Node
from omegaconf.base import Node
from omegaconf import Node
from omegaconf import Node
from .base import Container
from omegaconf import DictKeyType
from .base import Container
from .nodes import ValueNode
from omegaconf import Container, Node
from omegaconf import OmegaConf
from omegaconf.base import Node
from omegaconf import OmegaConf
and context (class names, function names, or code) available:
# Path: omegaconf/errors.py
# class ConfigIndexError(OmegaConfBaseException, IndexError):
# """
# Thrown from a config object when a regular access would have caused an IndexError.
# """
#
# class ConfigTypeError(OmegaConfBaseException, TypeError):
# """
# Thrown from a config object when a regular access would have caused a TypeError.
# """
#
# class ConfigValueError(OmegaConfBaseException, ValueError):
# """
# Thrown from a config object when a regular access would have caused a ValueError.
# """
#
# class GrammarParseError(OmegaConfBaseException):
# """
# Thrown when failing to parse an expression according to the ANTLR grammar.
# """
#
# class OmegaConfBaseException(Exception):
# # would ideally be typed Optional[Node]
# parent_node: Any
# child_node: Any
# key: Any
# full_key: Optional[str]
# value: Any
# msg: Optional[str]
# cause: Optional[Exception]
# object_type: Optional[Type[Any]]
# object_type_str: Optional[str]
# ref_type: Optional[Type[Any]]
# ref_type_str: Optional[str]
#
# _initialized: bool = False
#
# def __init__(self, *_args: Any, **_kwargs: Any) -> None:
# self.parent_node = None
# self.child_node = None
# self.key = None
# self.full_key = None
# self.value = None
# self.msg = None
# self.object_type = None
# self.ref_type = None
#
# class ValidationError(OmegaConfBaseException, ValueError):
# """
# Thrown when a value fails validation
# """
#
# Path: omegaconf/grammar_parser.py
# SIMPLE_INTERPOLATION_PATTERN = re.compile(
# f"({_outer})?({_inter}({_outer})?)+$", flags=re.ASCII
# )
#
# def parse(
# value: str, parser_rule: str = "configValue", lexer_mode: str = "DEFAULT_MODE"
# ) -> ParserRuleContext:
# """
# Parse interpolated string `value` (and return the parse tree).
# """
# l_mode = getattr(OmegaConfGrammarLexer, lexer_mode)
# istream = InputStream(value)
#
# cached = getattr(_grammar_cache, "data", None)
# if cached is None:
# error_listener = OmegaConfErrorListener()
# lexer = OmegaConfGrammarLexer(istream)
# lexer.removeErrorListeners()
# lexer.addErrorListener(error_listener)
# lexer.mode(l_mode)
# token_stream = CommonTokenStream(lexer)
# parser = OmegaConfGrammarParser(token_stream)
# parser.removeErrorListeners()
# parser.addErrorListener(error_listener)
#
# # The two lines below could be enabled in the future if we decide to switch
# # to SLL prediction mode. Warning though, it has not been fully tested yet!
# # from antlr4 import PredictionMode
# # parser._interp.predictionMode = PredictionMode.SLL
#
# # Note that although the input stream `istream` is implicitly cached within
# # the lexer, it will be replaced by a new input next time the lexer is re-used.
# _grammar_cache.data = lexer, token_stream, parser
#
# else:
# lexer, token_stream, parser = cached
# # Replace the old input stream with the new one.
# lexer.inputStream = istream
# # Initialize the lexer / token stream / parser to process the new input.
# lexer.mode(l_mode)
# token_stream.setTokenSource(lexer)
# parser.reset()
#
# try:
# return getattr(parser, parser_rule)()
# except Exception as exc:
# if type(exc) is Exception and str(exc) == "Empty Stack":
# # This exception is raised by antlr when trying to pop a mode while
# # no mode has been pushed. We convert it into an `GrammarParseError`
# # to facilitate exception handling from the caller.
# raise GrammarParseError("Empty Stack")
# else:
# raise
. Output only the next line. | except ValidationError as ex: |
Based on the snippet: <|code_start|>
class CommentInline(GenericTabularInline):
model = Comment
readonly_fields = ["user", "created_at"]
def __init__(self, *args, **kwargs):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib.contenttypes.admin import GenericTabularInline
from .forms import CommentInlineForm, CommentInlineFormset
from .models import Comment
and context (classes, functions, sometimes code) from other files:
# Path: django_sonic_screwdriver/apps/admin_comments/forms.py
# class CommentInlineForm(forms.ModelForm):
# def __init__(self, *args, **kwargs):
# super(CommentInlineForm, self).__init__(*args, **kwargs)
# instance = getattr(self, "instance", None)
#
# self.fields["comment"].widget.attrs["rows"] = 3
#
# if instance and instance.pk:
# line_height = len(instance.comment.split("\n"))
# self.fields["comment"].widget.attrs["rows"] = line_height
# self.fields["comment"].widget.attrs["readonly"] = True
# self.fields["comment"].widget.attrs["border"] = 0
#
# class Meta:
# model = Comment
# exclude = []
#
# class Media:
# css = {"all": ("css/admin_comments.css",)}
#
# class CommentInlineFormset(BaseGenericInlineFormSet):
# def save_new(self, form, commit=True):
# setattr(form.instance, "user", self.current_user)
# return super(CommentInlineFormset, self).save_new(form, commit=True)
#
# Path: django_sonic_screwdriver/apps/admin_comments/models.py
# class Comment(BaseModel):
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE,
# verbose_name=_("User"),
# blank=False,
# null=True,
# help_text=_("The user is the creator of the comment."),
# )
#
# comment = models.TextField(
# verbose_name=_("Comment"),
# blank=False,
# null=True,
# help_text=_("The comment itself."),
# )
#
# object_id = models.CharField(
# max_length=36,
# verbose_name=_("Object ID"),
# blank=True,
# null=True,
# help_text=_("ID of the related object."),
# )
#
# content_object = GenericForeignKey(
# ct_field="content_type", fk_field="object_id", for_concrete_model=True
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# verbose_name=_("Content type"),
# blank=False,
# null=True,
# help_text=_("Related content type."),
# )
#
# class Meta:
# verbose_name = _("Comment")
# verbose_name_plural = _("Comments")
#
# def __str__(self):
# return f"{self.content_type} - {self.object_id}"
. Output only the next line. | self.form = CommentInlineForm |
Given the following code snippet before the placeholder: <|code_start|>
class CommentInline(GenericTabularInline):
model = Comment
readonly_fields = ["user", "created_at"]
def __init__(self, *args, **kwargs):
self.form = CommentInlineForm
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib.contenttypes.admin import GenericTabularInline
from .forms import CommentInlineForm, CommentInlineFormset
from .models import Comment
and context including class names, function names, and sometimes code from other files:
# Path: django_sonic_screwdriver/apps/admin_comments/forms.py
# class CommentInlineForm(forms.ModelForm):
# def __init__(self, *args, **kwargs):
# super(CommentInlineForm, self).__init__(*args, **kwargs)
# instance = getattr(self, "instance", None)
#
# self.fields["comment"].widget.attrs["rows"] = 3
#
# if instance and instance.pk:
# line_height = len(instance.comment.split("\n"))
# self.fields["comment"].widget.attrs["rows"] = line_height
# self.fields["comment"].widget.attrs["readonly"] = True
# self.fields["comment"].widget.attrs["border"] = 0
#
# class Meta:
# model = Comment
# exclude = []
#
# class Media:
# css = {"all": ("css/admin_comments.css",)}
#
# class CommentInlineFormset(BaseGenericInlineFormSet):
# def save_new(self, form, commit=True):
# setattr(form.instance, "user", self.current_user)
# return super(CommentInlineFormset, self).save_new(form, commit=True)
#
# Path: django_sonic_screwdriver/apps/admin_comments/models.py
# class Comment(BaseModel):
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE,
# verbose_name=_("User"),
# blank=False,
# null=True,
# help_text=_("The user is the creator of the comment."),
# )
#
# comment = models.TextField(
# verbose_name=_("Comment"),
# blank=False,
# null=True,
# help_text=_("The comment itself."),
# )
#
# object_id = models.CharField(
# max_length=36,
# verbose_name=_("Object ID"),
# blank=True,
# null=True,
# help_text=_("ID of the related object."),
# )
#
# content_object = GenericForeignKey(
# ct_field="content_type", fk_field="object_id", for_concrete_model=True
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# verbose_name=_("Content type"),
# blank=False,
# null=True,
# help_text=_("Related content type."),
# )
#
# class Meta:
# verbose_name = _("Comment")
# verbose_name_plural = _("Comments")
#
# def __str__(self):
# return f"{self.content_type} - {self.object_id}"
. Output only the next line. | self.formset = CommentInlineFormset |
Continue the code snippet: <|code_start|>
def handler(exception, context):
data = dict()
# 401 Handler
if isinstance(exception, exceptions.NotAuthenticated):
exception = UnauthorizedException()
# 429 Handler
if isinstance(exception, exceptions.Throttled):
exception = TooManyRequestsException()
if isinstance(exception, exceptions.ValidationError):
# Convert the inconsistent Django error format into a consistent one.
all_errors = []
for key, err_details in exception.get_full_details().items():
for ed in err_details:
all_errors.append(
{
"message": ed["message"],
"code": ed["code"].value
<|code_end|>
. Use current file imports:
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions, status
from rest_framework.views import set_rollback, Response
from .models import ErrorCodes
and context (classes, functions, or code) from other files:
# Path: django_sonic_screwdriver/models.py
# class ErrorCodes(Enum):
# def __str__(self):
# return str(self.value)
. Output only the next line. | if isinstance(ed["code"], ErrorCodes) |
Here is a snippet: <|code_start|>
def git_available(func):
"""
Check, if a git repository exists in the given folder.
"""
def inner(*args):
<|code_end|>
. Write the next line using the current file imports:
import os
from subprocess import call
from django_sonic_screwdriver.settings import api_settings
from django_sonic_screwdriver.utils import shell
and context from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
, which may include functions, classes, or code. Output only the next line. | os.chdir(api_settings.GIT_DIR) |
Continue the code snippet: <|code_start|>
def git_available(func):
"""
Check, if a git repository exists in the given folder.
"""
def inner(*args):
os.chdir(api_settings.GIT_DIR)
if call(["git", "rev-parse"]) == 0:
return func(*args)
<|code_end|>
. Use current file imports:
import os
from subprocess import call
from django_sonic_screwdriver.settings import api_settings
from django_sonic_screwdriver.utils import shell
and context (classes, functions, or code) from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
. Output only the next line. | shell.fail("There is no git repository!") |
Continue the code snippet: <|code_start|>
class HelperTest(TestCase):
def test_underscorize_with_simple_dict(self):
data = {"test": "test", "ANewTest": "42", 2: "bla"}
<|code_end|>
. Use current file imports:
from django.http import QueryDict
from django.test import TestCase
from django_sonic_screwdriver.helper import underscoreize
and context (classes, functions, or code) from other files:
# Path: django_sonic_screwdriver/helper.py
# def underscoreize(data):
# """
# Underscoring data.
# """
# if isinstance(data, dict):
# new_dict = {}
# for key, value in get_iterable(data):
# if isinstance(key, str):
# new_key = camel_to_underscore(key)
# else:
# new_key = key
# new_dict[new_key] = underscoreize(value)
#
# if isinstance(data, QueryDict):
# new_query = QueryDict(mutable=True)
# for key, value in new_dict.items():
# new_query.setlist(key, value)
# return new_query
# return new_dict
# if is_iterable(data) and not isinstance(data, (str, File)):
# return [underscoreize(item) for item in data]
#
# return data
. Output only the next line. | data = underscoreize(data) |
Predict the next line for this snippet: <|code_start|>
# more then one options are not enabled per default
if counter >= 3:
# TODO: Raise Error!
exit(
"It is not recommended to use more then one parameter. "
"Use -f to force your command."
)
if options["major"]:
version.set_major()
if options["minor"]:
version.set_minor()
if options["patch"]:
version.set_patch()
if options["dev"]:
version.set_patch(version.DEV)
if options["alpha"]:
version.set_patch(version.ALPHA)
if options["beta"]:
version.set_patch(version.BETA)
if options["rc"]:
version.set_patch(version.RC)
<|code_end|>
with the help of current file imports:
from django.core.management.base import BaseCommand
from django_sonic_screwdriver.settings import api_settings
from django_sonic_screwdriver.version import version
from django_sonic_screwdriver.git import git
and context from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/version.py
# RELEASE_TAGS = {
# # pre-release
# "ALPHA": "a",
# "BETA": "b",
# "RC": "rc",
# # dev-release
# "DEV": "dev",
# # post-release
# }
# RELEASE_SEPARATORS = {"DOT": ".", "MINUS": "-", "UNDERSCORE": "_"}
# class Version:
# def get_version():
# def set_version(old_version, new_version):
# def get_patch_version(version):
# def get_current_RELEASE_SEPARATOR(patch):
# def get_current_pre_release_tag(patch):
# def set_major(self):
# def set_minor(self):
# def set_patch(self, pre_release_tag=""):
# def __init__(self, release_tags=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/git/git.py
# GIT_OPTIONS = {
# "DEVELOPMENT": "development",
# "STAGING": "staging",
# "PRODUCTION": "production",
# }
# class Git:
# def create_git_version_tag(deploy_tag):
# def get_current_branch():
# def get_latest_tag():
# def check_existence_of_staging_tag_in_remote_repo():
# def __debug(command, dry=False):
# def __git_tag(git_tag):
# def __git_tag_gpg(git_tag):
# def __git_tag_push():
# def __git_tag_delete(git_tag):
# def __git_push(self):
# def tag(self, deploy_tag=""):
# def push_tags(self):
# def tag_delete(self, tag):
, which may contain function names, class names, or code. Output only the next line. | if api_settings.PATCH_AUTO_TAG: |
Given the code snippet: <|code_start|> )
parser.add_argument(
"--force", "-f", action="store_true", dest="force", default=False, help=""
)
def handle(self, *args, **options):
"""
Check, how much options are true.
If option '--force', '-f' is set this part will be skipped.
"""
if not options["force"]:
counter = 0
for key in options:
if options[key]:
counter += 1
# If no options are set, do a normal patch
if counter == 1:
options["patch"] = True
# more then one options are not enabled per default
if counter >= 3:
# TODO: Raise Error!
exit(
"It is not recommended to use more then one parameter. "
"Use -f to force your command."
)
if options["major"]:
<|code_end|>
, generate the next line using the imports in this file:
from django.core.management.base import BaseCommand
from django_sonic_screwdriver.settings import api_settings
from django_sonic_screwdriver.version import version
from django_sonic_screwdriver.git import git
and context (functions, classes, or occasionally code) from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/version.py
# RELEASE_TAGS = {
# # pre-release
# "ALPHA": "a",
# "BETA": "b",
# "RC": "rc",
# # dev-release
# "DEV": "dev",
# # post-release
# }
# RELEASE_SEPARATORS = {"DOT": ".", "MINUS": "-", "UNDERSCORE": "_"}
# class Version:
# def get_version():
# def set_version(old_version, new_version):
# def get_patch_version(version):
# def get_current_RELEASE_SEPARATOR(patch):
# def get_current_pre_release_tag(patch):
# def set_major(self):
# def set_minor(self):
# def set_patch(self, pre_release_tag=""):
# def __init__(self, release_tags=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/git/git.py
# GIT_OPTIONS = {
# "DEVELOPMENT": "development",
# "STAGING": "staging",
# "PRODUCTION": "production",
# }
# class Git:
# def create_git_version_tag(deploy_tag):
# def get_current_branch():
# def get_latest_tag():
# def check_existence_of_staging_tag_in_remote_repo():
# def __debug(command, dry=False):
# def __git_tag(git_tag):
# def __git_tag_gpg(git_tag):
# def __git_tag_push():
# def __git_tag_delete(git_tag):
# def __git_push(self):
# def tag(self, deploy_tag=""):
# def push_tags(self):
# def tag_delete(self, tag):
. Output only the next line. | version.set_major() |
Next line prediction: <|code_start|> # more then one options are not enabled per default
if counter >= 3:
# TODO: Raise Error!
exit(
"It is not recommended to use more then one parameter. "
"Use -f to force your command."
)
if options["major"]:
version.set_major()
if options["minor"]:
version.set_minor()
if options["patch"]:
version.set_patch()
if options["dev"]:
version.set_patch(version.DEV)
if options["alpha"]:
version.set_patch(version.ALPHA)
if options["beta"]:
version.set_patch(version.BETA)
if options["rc"]:
version.set_patch(version.RC)
if api_settings.PATCH_AUTO_TAG:
<|code_end|>
. Use current file imports:
(from django.core.management.base import BaseCommand
from django_sonic_screwdriver.settings import api_settings
from django_sonic_screwdriver.version import version
from django_sonic_screwdriver.git import git)
and context including class names, function names, or small code snippets from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/version.py
# RELEASE_TAGS = {
# # pre-release
# "ALPHA": "a",
# "BETA": "b",
# "RC": "rc",
# # dev-release
# "DEV": "dev",
# # post-release
# }
# RELEASE_SEPARATORS = {"DOT": ".", "MINUS": "-", "UNDERSCORE": "_"}
# class Version:
# def get_version():
# def set_version(old_version, new_version):
# def get_patch_version(version):
# def get_current_RELEASE_SEPARATOR(patch):
# def get_current_pre_release_tag(patch):
# def set_major(self):
# def set_minor(self):
# def set_patch(self, pre_release_tag=""):
# def __init__(self, release_tags=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/git/git.py
# GIT_OPTIONS = {
# "DEVELOPMENT": "development",
# "STAGING": "staging",
# "PRODUCTION": "production",
# }
# class Git:
# def create_git_version_tag(deploy_tag):
# def get_current_branch():
# def get_latest_tag():
# def check_existence_of_staging_tag_in_remote_repo():
# def __debug(command, dry=False):
# def __git_tag(git_tag):
# def __git_tag_gpg(git_tag):
# def __git_tag_push():
# def __git_tag_delete(git_tag):
# def __git_push(self):
# def tag(self, deploy_tag=""):
# def push_tags(self):
# def tag_delete(self, tag):
. Output only the next line. | git.tag() |
Predict the next line after this snippet: <|code_start|>
class Command(BaseCommand):
args = "tag"
help = "Remove last or given tag."
def handle(self, *args, **options):
if args:
shell.warn("Do you want to remove tag " + str(args[0]) + "? (Y/n)")
confirmation = input()
if confirmation != "n":
<|code_end|>
using the current file's imports:
from django.core.management.base import BaseCommand
from django_sonic_screwdriver.git import git
from django_sonic_screwdriver.utils.shell import shell
and any relevant context from other files:
# Path: django_sonic_screwdriver/git/git.py
# GIT_OPTIONS = {
# "DEVELOPMENT": "development",
# "STAGING": "staging",
# "PRODUCTION": "production",
# }
# class Git:
# def create_git_version_tag(deploy_tag):
# def get_current_branch():
# def get_latest_tag():
# def check_existence_of_staging_tag_in_remote_repo():
# def __debug(command, dry=False):
# def __git_tag(git_tag):
# def __git_tag_gpg(git_tag):
# def __git_tag_push():
# def __git_tag_delete(git_tag):
# def __git_push(self):
# def tag(self, deploy_tag=""):
# def push_tags(self):
# def tag_delete(self, tag):
#
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
. Output only the next line. | git.tag_delete(str(args[0])) |
Here is a snippet: <|code_start|>
class Command(BaseCommand):
args = "tag"
help = "Remove last or given tag."
def handle(self, *args, **options):
if args:
<|code_end|>
. Write the next line using the current file imports:
from django.core.management.base import BaseCommand
from django_sonic_screwdriver.git import git
from django_sonic_screwdriver.utils.shell import shell
and context from other files:
# Path: django_sonic_screwdriver/git/git.py
# GIT_OPTIONS = {
# "DEVELOPMENT": "development",
# "STAGING": "staging",
# "PRODUCTION": "production",
# }
# class Git:
# def create_git_version_tag(deploy_tag):
# def get_current_branch():
# def get_latest_tag():
# def check_existence_of_staging_tag_in_remote_repo():
# def __debug(command, dry=False):
# def __git_tag(git_tag):
# def __git_tag_gpg(git_tag):
# def __git_tag_push():
# def __git_tag_delete(git_tag):
# def __git_push(self):
# def tag(self, deploy_tag=""):
# def push_tags(self):
# def tag_delete(self, tag):
#
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
, which may include functions, classes, or code. Output only the next line. | shell.warn("Do you want to remove tag " + str(args[0]) + "? (Y/n)") |
Next line prediction: <|code_start|> return current_branch[2:][: (current_branch.__len__() - 5)]
@staticmethod
@git_available
def get_latest_tag():
latest_tag_hash = str(
check_output(["git", "rev-list", "--tags", "--max-count=1"])
)
latest_tag = str(
check_output(
[
"git",
"describe",
"--tags",
latest_tag_hash[2:][: (latest_tag_hash.__len__() - 5)],
]
)
)
return latest_tag[2:][: (latest_tag.__len__() - 5)]
@staticmethod
@git_available
def check_existence_of_staging_tag_in_remote_repo():
"""
This method will check, if the given tag exists as a staging
tag in the remote repository.
The intention is, that every tag, which should be deployed
on a production environment, has to be deployed on a staging environment before.
"""
<|code_end|>
. Use current file imports:
(from subprocess import call, check_output
from django_sonic_screwdriver.settings import api_settings
from django_sonic_screwdriver.version import version
from django_sonic_screwdriver.utils import shell
from django_sonic_screwdriver.git.decorators import git_available)
and context including class names, function names, or small code snippets from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/version.py
# RELEASE_TAGS = {
# # pre-release
# "ALPHA": "a",
# "BETA": "b",
# "RC": "rc",
# # dev-release
# "DEV": "dev",
# # post-release
# }
# RELEASE_SEPARATORS = {"DOT": ".", "MINUS": "-", "UNDERSCORE": "_"}
# class Version:
# def get_version():
# def set_version(old_version, new_version):
# def get_patch_version(version):
# def get_current_RELEASE_SEPARATOR(patch):
# def get_current_pre_release_tag(patch):
# def set_major(self):
# def set_minor(self):
# def set_patch(self, pre_release_tag=""):
# def __init__(self, release_tags=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
#
# Path: django_sonic_screwdriver/git/decorators.py
# def git_available(func):
# """
# Check, if a git repository exists in the given folder.
# """
#
# def inner(*args):
#
# os.chdir(api_settings.GIT_DIR)
#
# if call(["git", "rev-parse"]) == 0:
# return func(*args)
#
# shell.fail("There is no git repository!")
# return exit(1)
#
# return inner
. Output only the next line. | staging_tag = Git.create_git_version_tag(api_settings.GIT_STAGING_PRE_TAG) |
Given snippet: <|code_start|>
GIT_OPTIONS = {
"DEVELOPMENT": "development",
"STAGING": "staging",
"PRODUCTION": "production",
}
class Git:
@staticmethod
def create_git_version_tag(deploy_tag):
if deploy_tag != "":
deploy_tag += "-"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from subprocess import call, check_output
from django_sonic_screwdriver.settings import api_settings
from django_sonic_screwdriver.version import version
from django_sonic_screwdriver.utils import shell
from django_sonic_screwdriver.git.decorators import git_available
and context:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/version.py
# RELEASE_TAGS = {
# # pre-release
# "ALPHA": "a",
# "BETA": "b",
# "RC": "rc",
# # dev-release
# "DEV": "dev",
# # post-release
# }
# RELEASE_SEPARATORS = {"DOT": ".", "MINUS": "-", "UNDERSCORE": "_"}
# class Version:
# def get_version():
# def set_version(old_version, new_version):
# def get_patch_version(version):
# def get_current_RELEASE_SEPARATOR(patch):
# def get_current_pre_release_tag(patch):
# def set_major(self):
# def set_minor(self):
# def set_patch(self, pre_release_tag=""):
# def __init__(self, release_tags=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
#
# Path: django_sonic_screwdriver/git/decorators.py
# def git_available(func):
# """
# Check, if a git repository exists in the given folder.
# """
#
# def inner(*args):
#
# os.chdir(api_settings.GIT_DIR)
#
# if call(["git", "rev-parse"]) == 0:
# return func(*args)
#
# shell.fail("There is no git repository!")
# return exit(1)
#
# return inner
which might include code, classes, or functions. Output only the next line. | return str(deploy_tag + "v" + version.get_version()) |
Given the code snippet: <|code_start|> """
This method will check, if the given tag exists as a staging
tag in the remote repository.
The intention is, that every tag, which should be deployed
on a production environment, has to be deployed on a staging environment before.
"""
staging_tag = Git.create_git_version_tag(api_settings.GIT_STAGING_PRE_TAG)
command_git = "git ls-remote -t"
command_awk = "awk '{print $2}'"
command_cut_1 = "cut -d '/' -f 3"
command_cut_2 = "cut -d '^' -f 1"
command_sort = "sort -b -t . -k 1,1nr -k 2,2nr -k 3,3r -k 4,4r -k 5,5r"
command_uniq = "uniq"
command = (
command_git
+ " | "
+ command_awk
+ " | "
+ command_cut_1
+ " | "
+ command_cut_2
+ " | "
+ command_sort
+ " | "
+ command_uniq
)
<|code_end|>
, generate the next line using the imports in this file:
from subprocess import call, check_output
from django_sonic_screwdriver.settings import api_settings
from django_sonic_screwdriver.version import version
from django_sonic_screwdriver.utils import shell
from django_sonic_screwdriver.git.decorators import git_available
and context (functions, classes, or occasionally code) from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/version.py
# RELEASE_TAGS = {
# # pre-release
# "ALPHA": "a",
# "BETA": "b",
# "RC": "rc",
# # dev-release
# "DEV": "dev",
# # post-release
# }
# RELEASE_SEPARATORS = {"DOT": ".", "MINUS": "-", "UNDERSCORE": "_"}
# class Version:
# def get_version():
# def set_version(old_version, new_version):
# def get_patch_version(version):
# def get_current_RELEASE_SEPARATOR(patch):
# def get_current_pre_release_tag(patch):
# def set_major(self):
# def set_minor(self):
# def set_patch(self, pre_release_tag=""):
# def __init__(self, release_tags=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
#
# Path: django_sonic_screwdriver/git/decorators.py
# def git_available(func):
# """
# Check, if a git repository exists in the given folder.
# """
#
# def inner(*args):
#
# os.chdir(api_settings.GIT_DIR)
#
# if call(["git", "rev-parse"]) == 0:
# return func(*args)
#
# shell.fail("There is no git repository!")
# return exit(1)
#
# return inner
. Output only the next line. | list_of_tags = str(check_output(command, shell=True)) |
Predict the next line after this snippet: <|code_start|>
GIT_OPTIONS = {
"DEVELOPMENT": "development",
"STAGING": "staging",
"PRODUCTION": "production",
}
class Git:
@staticmethod
def create_git_version_tag(deploy_tag):
if deploy_tag != "":
deploy_tag += "-"
return str(deploy_tag + "v" + version.get_version())
@staticmethod
<|code_end|>
using the current file's imports:
from subprocess import call, check_output
from django_sonic_screwdriver.settings import api_settings
from django_sonic_screwdriver.version import version
from django_sonic_screwdriver.utils import shell
from django_sonic_screwdriver.git.decorators import git_available
and any relevant context from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/version.py
# RELEASE_TAGS = {
# # pre-release
# "ALPHA": "a",
# "BETA": "b",
# "RC": "rc",
# # dev-release
# "DEV": "dev",
# # post-release
# }
# RELEASE_SEPARATORS = {"DOT": ".", "MINUS": "-", "UNDERSCORE": "_"}
# class Version:
# def get_version():
# def set_version(old_version, new_version):
# def get_patch_version(version):
# def get_current_RELEASE_SEPARATOR(patch):
# def get_current_pre_release_tag(patch):
# def set_major(self):
# def set_minor(self):
# def set_patch(self, pre_release_tag=""):
# def __init__(self, release_tags=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
#
# Path: django_sonic_screwdriver/git/decorators.py
# def git_available(func):
# """
# Check, if a git repository exists in the given folder.
# """
#
# def inner(*args):
#
# os.chdir(api_settings.GIT_DIR)
#
# if call(["git", "rev-parse"]) == 0:
# return func(*args)
#
# shell.fail("There is no git repository!")
# return exit(1)
#
# return inner
. Output only the next line. | @git_available |
Next line prediction: <|code_start|>
class Command(BaseCommand):
help = "Push your tagged project."
def handle(self, *args, **options):
<|code_end|>
. Use current file imports:
(from django.core.management.base import BaseCommand
from django_sonic_screwdriver.git import git)
and context including class names, function names, or small code snippets from other files:
# Path: django_sonic_screwdriver/git/git.py
# GIT_OPTIONS = {
# "DEVELOPMENT": "development",
# "STAGING": "staging",
# "PRODUCTION": "production",
# }
# class Git:
# def create_git_version_tag(deploy_tag):
# def get_current_branch():
# def get_latest_tag():
# def check_existence_of_staging_tag_in_remote_repo():
# def __debug(command, dry=False):
# def __git_tag(git_tag):
# def __git_tag_gpg(git_tag):
# def __git_tag_push():
# def __git_tag_delete(git_tag):
# def __git_push(self):
# def tag(self, deploy_tag=""):
# def push_tags(self):
# def tag_delete(self, tag):
. Output only the next line. | git.push_tags() |
Predict the next line for this snippet: <|code_start|> default=False,
help="Do not export project with wheel.",
)
parser.add_argument(
"--upload",
"-u",
action="store_true",
dest="upload",
default=False,
help="Upload Project.",
)
def handle(self, *args, **options):
clean_dist_dir()
export = ["python", "setup.py", "sdist"]
if options["nowheel"]:
call(export)
else:
export.append("bdist_wheel")
call(export)
if options["upload"]:
export.append("upload")
call(export)
def clean_dist_dir():
<|code_end|>
with the help of current file imports:
import os
import shutil
from django.core.management.base import BaseCommand
from subprocess import call
from django_sonic_screwdriver.utils.shell import shell
and context from other files:
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
, which may contain function names, class names, or code. Output only the next line. | shell.warn("Do you want to cleanup dist directory before? (Y/n)") |
Given the following code snippet before the placeholder: <|code_start|> """
Code to be executed for each request/response after
the view is called.
:param request:
:param response:
:return:
"""
return request, response
def __user_ban_exists(self, request):
"""
Get the user and try to find a ban for the user.
:param: request
"""
if not isinstance(request.user, AnonymousUser):
return (
UserBan.objects.filter(banned_user=request.user)
.filter(Q(end_date__gte=timezone.now()) | Q(end_date__exact=None))
.exists()
)
def __ip_ban_exists(self, request):
"""
Get the ip_address of the request and try to find a ban
with this ip.
:param: request
"""
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from django.http import HttpResponseForbidden
from django.utils import timezone
from django_sonic_screwdriver.settings import api_settings
from .models import UserBan, IPBan
and context including class names, function names, and sometimes code from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/apps/ban/models.py
# class UserBan(Ban):
# banned_user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE,
# verbose_name=_("User"),
# related_name="banned_user",
# blank=False,
# null=True,
# help_text="This is the banned user or the receiver of the ban.",
# )
#
# class Meta:
# verbose_name = _("User Ban")
# verbose_name_plural = _("User Bans")
#
# def __str__(self):
# return self.banned_user.get_username()
#
# class IPBan(Ban):
# ip = models.GenericIPAddressField(
# verbose_name=_("IP"),
# blank=False,
# null=True,
# help_text=_(
# "This is the banned ip. Every request from this IP will result in 403."
# ),
# )
#
# class Meta:
# verbose_name = _("IP Ban")
# verbose_name_plural = _("IP Bans")
#
# def __str__(self):
# return str(self.ip)
. Output only the next line. | ip_address = request.META.get(api_settings.BAN_REMOTE_ADDR_HEADER) |
Continue the code snippet: <|code_start|> """
Code to be executed for each request before
the view (and later middleware) are called.
:param request:
:return:
"""
if self.__user_ban_exists(request) or self.__ip_ban_exists(request):
return self.bans_found_action()
return request
def _after_view(self, request, response):
"""
Code to be executed for each request/response after
the view is called.
:param request:
:param response:
:return:
"""
return request, response
def __user_ban_exists(self, request):
"""
Get the user and try to find a ban for the user.
:param: request
"""
if not isinstance(request.user, AnonymousUser):
return (
<|code_end|>
. Use current file imports:
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from django.http import HttpResponseForbidden
from django.utils import timezone
from django_sonic_screwdriver.settings import api_settings
from .models import UserBan, IPBan
and context (classes, functions, or code) from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/apps/ban/models.py
# class UserBan(Ban):
# banned_user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE,
# verbose_name=_("User"),
# related_name="banned_user",
# blank=False,
# null=True,
# help_text="This is the banned user or the receiver of the ban.",
# )
#
# class Meta:
# verbose_name = _("User Ban")
# verbose_name_plural = _("User Bans")
#
# def __str__(self):
# return self.banned_user.get_username()
#
# class IPBan(Ban):
# ip = models.GenericIPAddressField(
# verbose_name=_("IP"),
# blank=False,
# null=True,
# help_text=_(
# "This is the banned ip. Every request from this IP will result in 403."
# ),
# )
#
# class Meta:
# verbose_name = _("IP Ban")
# verbose_name_plural = _("IP Bans")
#
# def __str__(self):
# return str(self.ip)
. Output only the next line. | UserBan.objects.filter(banned_user=request.user) |
Next line prediction: <|code_start|> the view is called.
:param request:
:param response:
:return:
"""
return request, response
def __user_ban_exists(self, request):
"""
Get the user and try to find a ban for the user.
:param: request
"""
if not isinstance(request.user, AnonymousUser):
return (
UserBan.objects.filter(banned_user=request.user)
.filter(Q(end_date__gte=timezone.now()) | Q(end_date__exact=None))
.exists()
)
def __ip_ban_exists(self, request):
"""
Get the ip_address of the request and try to find a ban
with this ip.
:param: request
"""
ip_address = request.META.get(api_settings.BAN_REMOTE_ADDR_HEADER)
return (
<|code_end|>
. Use current file imports:
(from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from django.http import HttpResponseForbidden
from django.utils import timezone
from django_sonic_screwdriver.settings import api_settings
from .models import UserBan, IPBan)
and context including class names, function names, or small code snippets from other files:
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
#
# Path: django_sonic_screwdriver/apps/ban/models.py
# class UserBan(Ban):
# banned_user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE,
# verbose_name=_("User"),
# related_name="banned_user",
# blank=False,
# null=True,
# help_text="This is the banned user or the receiver of the ban.",
# )
#
# class Meta:
# verbose_name = _("User Ban")
# verbose_name_plural = _("User Bans")
#
# def __str__(self):
# return self.banned_user.get_username()
#
# class IPBan(Ban):
# ip = models.GenericIPAddressField(
# verbose_name=_("IP"),
# blank=False,
# null=True,
# help_text=_(
# "This is the banned ip. Every request from this IP will result in 403."
# ),
# )
#
# class Meta:
# verbose_name = _("IP Ban")
# verbose_name_plural = _("IP Bans")
#
# def __str__(self):
# return str(self.ip)
. Output only the next line. | IPBan.objects.filter(ip=ip_address) |
Continue the code snippet: <|code_start|>
RELEASE_TAGS = {
# pre-release
"ALPHA": "a",
"BETA": "b",
"RC": "rc",
# dev-release
"DEV": "dev",
# post-release
}
RELEASE_SEPARATORS = {"DOT": ".", "MINUS": "-", "UNDERSCORE": "_"}
class Version:
@staticmethod
def get_version():
"""
Return version from setup.py
"""
with open(
os.path.join(os.path.abspath(api_settings.VERSION_FILE))
) as version_desc:
version_file = version_desc.read()
try:
return re.search(r"version=['\"]([^'\"]+)['\"]", version_file).group(1)
except FileNotFoundError: # pragma: no cover
<|code_end|>
. Use current file imports:
import os
import re
import fileinput
from django_sonic_screwdriver.utils import shell
from django_sonic_screwdriver.settings import api_settings
and context (classes, functions, or code) from other files:
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
#
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
. Output only the next line. | shell.fail("File not found!") |
Next line prediction: <|code_start|>
RELEASE_TAGS = {
# pre-release
"ALPHA": "a",
"BETA": "b",
"RC": "rc",
# dev-release
"DEV": "dev",
# post-release
}
RELEASE_SEPARATORS = {"DOT": ".", "MINUS": "-", "UNDERSCORE": "_"}
class Version:
@staticmethod
def get_version():
"""
Return version from setup.py
"""
with open(
<|code_end|>
. Use current file imports:
(import os
import re
import fileinput
from django_sonic_screwdriver.utils import shell
from django_sonic_screwdriver.settings import api_settings)
and context including class names, function names, or small code snippets from other files:
# Path: django_sonic_screwdriver/utils/shell.py
# ANSCI_ESCAPE = re.compile(r"\x1b[^m]*m")
# STDERR_WRITER = getwriter("utf-8")(stderr.buffer)
# STDOUT_WRITER = getwriter("utf-8")(stdout.buffer)
# __HEADER = "\033[95m"
# __OK_BLUE = "\033[94m"
# __OK_GREEN = "\033[92m"
# __WARNING = "\033[93m"
# __FAIL = "\033[91m"
# __ENDC = "\033[0m"
# __BOLD = "\033[1m"
# __UNDERLINE = "\033[4m"
# def ansi_clean(string):
# def write_to_stream(stream, msg):
# def msg(self, msg, append_new_line=True):
# def success(self, msg, append_new_line=True):
# def warn(self, msg, append_new_line=True):
# def fail(self, msg, append_new_line=True):
# def debug(self, msg, append_new_line=True):
# def __text(self, msg, color):
# def __out(self, msg, color=None, append_new_line=False):
# class Shell:
#
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
. Output only the next line. | os.path.join(os.path.abspath(api_settings.VERSION_FILE)) |
Predict the next line for this snippet: <|code_start|>
class CommentTest(TestCase):
def test_str_repr(self):
content_type = ContentType.objects.first()
<|code_end|>
with the help of current file imports:
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from django_sonic_screwdriver.apps.admin_comments.models import Comment
and context from other files:
# Path: django_sonic_screwdriver/apps/admin_comments/models.py
# class Comment(BaseModel):
# user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE,
# verbose_name=_("User"),
# blank=False,
# null=True,
# help_text=_("The user is the creator of the comment."),
# )
#
# comment = models.TextField(
# verbose_name=_("Comment"),
# blank=False,
# null=True,
# help_text=_("The comment itself."),
# )
#
# object_id = models.CharField(
# max_length=36,
# verbose_name=_("Object ID"),
# blank=True,
# null=True,
# help_text=_("ID of the related object."),
# )
#
# content_object = GenericForeignKey(
# ct_field="content_type", fk_field="object_id", for_concrete_model=True
# )
#
# content_type = models.ForeignKey(
# ContentType,
# on_delete=models.CASCADE,
# verbose_name=_("Content type"),
# blank=False,
# null=True,
# help_text=_("Related content type."),
# )
#
# class Meta:
# verbose_name = _("Comment")
# verbose_name_plural = _("Comments")
#
# def __str__(self):
# return f"{self.content_type} - {self.object_id}"
, which may contain function names, class names, or code. Output only the next line. | comment = Comment.objects.create( |
Predict the next line after this snippet: <|code_start|> else:
return group[1].upper()
def camelize(data):
# Handle lazy translated strings.
if isinstance(data, Promise):
data = force_text(data)
if isinstance(data, dict):
new_dict = collections.OrderedDict()
for key, value in data.items():
if isinstance(key, Promise):
key = force_text(key)
if isinstance(key, str) and "_" in key and key[0] != "_":
new_key = re.sub(camelize_re, underscore_to_camel, key)
else:
new_key = key
new_dict[new_key] = camelize(value)
return new_dict
if is_iterable(data) and not isinstance(data, str):
return [camelize(item) for item in data]
return data
def underscoreize(data):
"""
Underscoring data.
"""
if isinstance(data, dict):
new_dict = {}
<|code_end|>
using the current file's imports:
import collections
import re
from django.core.files import File
from django.http import QueryDict
from django.utils.encoding import force_text
from django.utils.functional import Promise
from .iterables import get_iterable, is_iterable
and any relevant context from other files:
# Path: django_sonic_screwdriver/iterables.py
# def get_iterable(data):
# """
# Returns iterable data.
# """
# if isinstance(data, QueryDict):
# return data.lists()
# else:
# return data.items()
#
# def is_iterable(obj):
# """
# Check if obj is iterable.
# """
# try:
# iter(obj)
# except TypeError:
# return False
# else:
# return True
. Output only the next line. | for key, value in get_iterable(data): |
Next line prediction: <|code_start|> underscore_re = re.compile(r"([a-z]|[0-9]+[a-z]?|[A-Z]?)([A-Z])")
return underscore_re.sub(r"\1_\2", name).lower()
def underscore_to_camel(match):
"""
Cast sample_data to sampleData.
"""
group = match.group()
if len(group) == 3:
return group[0] + group[2].upper()
else:
return group[1].upper()
def camelize(data):
# Handle lazy translated strings.
if isinstance(data, Promise):
data = force_text(data)
if isinstance(data, dict):
new_dict = collections.OrderedDict()
for key, value in data.items():
if isinstance(key, Promise):
key = force_text(key)
if isinstance(key, str) and "_" in key and key[0] != "_":
new_key = re.sub(camelize_re, underscore_to_camel, key)
else:
new_key = key
new_dict[new_key] = camelize(value)
return new_dict
<|code_end|>
. Use current file imports:
(import collections
import re
from django.core.files import File
from django.http import QueryDict
from django.utils.encoding import force_text
from django.utils.functional import Promise
from .iterables import get_iterable, is_iterable)
and context including class names, function names, or small code snippets from other files:
# Path: django_sonic_screwdriver/iterables.py
# def get_iterable(data):
# """
# Returns iterable data.
# """
# if isinstance(data, QueryDict):
# return data.lists()
# else:
# return data.items()
#
# def is_iterable(obj):
# """
# Check if obj is iterable.
# """
# try:
# iter(obj)
# except TypeError:
# return False
# else:
# return True
. Output only the next line. | if is_iterable(data) and not isinstance(data, str): |
Based on the snippet: <|code_start|>
class BanManager(BaseManager):
def create_for_user(self, banned_user, end_date=None, *args, **kwargs):
"""
Creates a ban for an user.
The default ban time is 1 hour.
"""
kwargs["banned_user"] = banned_user
kwargs["end_date"] = end_date if end_date else self.__get_default_end_date()
return super(BanManager, self).create(*args, **kwargs)
def create_for_ip(self, ip, end_date=None, *args, **kwargs):
"""
Creates a ban for an ip.
The default ban time is 1 hour.
"""
kwargs["ip"] = ip
kwargs["end_date"] = end_date if end_date else self.__get_default_end_date()
return super(BanManager, self).create(*args, **kwargs)
@staticmethod
def __get_default_end_date():
return timezone.now() + timezone.timedelta(
seconds=api_settings.BAN_DEFAULT_END_TIME
)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django_sonic_screwdriver.models import BaseModel, BaseManager
from django_sonic_screwdriver.settings import api_settings
and context (classes, functions, sometimes code) from other files:
# Path: django_sonic_screwdriver/models.py
# class BaseModel(models.Model):
# created_at = models.DateTimeField(
# verbose_name=_("Created at"),
# auto_now_add=True,
# blank=False,
# null=False,
# help_text=_("Model was created at this time."),
# )
#
# updated_at = models.DateTimeField(
# verbose_name=_("Updated at"),
# auto_now=True,
# blank=False,
# null=False,
# help_text=_("Model was updated at this time."),
# )
#
# objects = BaseManager()
#
# class Meta:
# abstract = True
#
# class BaseManager(models.Manager):
# def get_or_404(self, *args, **kwargs):
# """
# Returns instance or raises 404.
# """
# try:
# instance = super(BaseManager, self).get(*args, **kwargs)
# except self.model.DoesNotExist:
# from .exceptions import NotFoundException
#
# raise NotFoundException
# return instance
#
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
. Output only the next line. | class Ban(BaseModel): |
Continue the code snippet: <|code_start|>
class BanManager(BaseManager):
def create_for_user(self, banned_user, end_date=None, *args, **kwargs):
"""
Creates a ban for an user.
The default ban time is 1 hour.
"""
kwargs["banned_user"] = banned_user
kwargs["end_date"] = end_date if end_date else self.__get_default_end_date()
return super(BanManager, self).create(*args, **kwargs)
def create_for_ip(self, ip, end_date=None, *args, **kwargs):
"""
Creates a ban for an ip.
The default ban time is 1 hour.
"""
kwargs["ip"] = ip
kwargs["end_date"] = end_date if end_date else self.__get_default_end_date()
return super(BanManager, self).create(*args, **kwargs)
@staticmethod
def __get_default_end_date():
return timezone.now() + timezone.timedelta(
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django_sonic_screwdriver.models import BaseModel, BaseManager
from django_sonic_screwdriver.settings import api_settings
and context (classes, functions, or code) from other files:
# Path: django_sonic_screwdriver/models.py
# class BaseModel(models.Model):
# created_at = models.DateTimeField(
# verbose_name=_("Created at"),
# auto_now_add=True,
# blank=False,
# null=False,
# help_text=_("Model was created at this time."),
# )
#
# updated_at = models.DateTimeField(
# verbose_name=_("Updated at"),
# auto_now=True,
# blank=False,
# null=False,
# help_text=_("Model was updated at this time."),
# )
#
# objects = BaseManager()
#
# class Meta:
# abstract = True
#
# class BaseManager(models.Manager):
# def get_or_404(self, *args, **kwargs):
# """
# Returns instance or raises 404.
# """
# try:
# instance = super(BaseManager, self).get(*args, **kwargs)
# except self.model.DoesNotExist:
# from .exceptions import NotFoundException
#
# raise NotFoundException
# return instance
#
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
. Output only the next line. | seconds=api_settings.BAN_DEFAULT_END_TIME |
Next line prediction: <|code_start|>
class IterablesTest(TestCase):
def test_count(self):
data = {"key": "value"}
<|code_end|>
. Use current file imports:
(from collections.abc import Iterable
from django.http import QueryDict
from django.test import TestCase
from django_sonic_screwdriver.iterables import count, get_iterable, is_iterable)
and context including class names, function names, or small code snippets from other files:
# Path: django_sonic_screwdriver/iterables.py
# def count(iterable):
# """
# Counts the numbers of elements of the iterable.
# """
# if hasattr(iterable, "__len__"):
# return len(iterable)
#
# d = collections.deque(enumerate(iterable, 1), maxlen=1)
# return d[0][0] if d else 0
#
# def get_iterable(data):
# """
# Returns iterable data.
# """
# if isinstance(data, QueryDict):
# return data.lists()
# else:
# return data.items()
#
# def is_iterable(obj):
# """
# Check if obj is iterable.
# """
# try:
# iter(obj)
# except TypeError:
# return False
# else:
# return True
. Output only the next line. | self.assertEqual(count(data), 1) |
Given the code snippet: <|code_start|>
class IterablesTest(TestCase):
def test_count(self):
data = {"key": "value"}
self.assertEqual(count(data), 1)
self.assertEqual(count(iter(data)), 1)
with self.assertRaises(TypeError):
self.assertEqual(count(1), 0)
def test_get_iterable(self):
data = {"key": "value"}
<|code_end|>
, generate the next line using the imports in this file:
from collections.abc import Iterable
from django.http import QueryDict
from django.test import TestCase
from django_sonic_screwdriver.iterables import count, get_iterable, is_iterable
and context (functions, classes, or occasionally code) from other files:
# Path: django_sonic_screwdriver/iterables.py
# def count(iterable):
# """
# Counts the numbers of elements of the iterable.
# """
# if hasattr(iterable, "__len__"):
# return len(iterable)
#
# d = collections.deque(enumerate(iterable, 1), maxlen=1)
# return d[0][0] if d else 0
#
# def get_iterable(data):
# """
# Returns iterable data.
# """
# if isinstance(data, QueryDict):
# return data.lists()
# else:
# return data.items()
#
# def is_iterable(obj):
# """
# Check if obj is iterable.
# """
# try:
# iter(obj)
# except TypeError:
# return False
# else:
# return True
. Output only the next line. | self.assertEqual(get_iterable(data), data.items()) |
Here is a snippet: <|code_start|>
class IterablesTest(TestCase):
def test_count(self):
data = {"key": "value"}
self.assertEqual(count(data), 1)
self.assertEqual(count(iter(data)), 1)
with self.assertRaises(TypeError):
self.assertEqual(count(1), 0)
def test_get_iterable(self):
data = {"key": "value"}
self.assertEqual(get_iterable(data), data.items())
data = QueryDict("AParam=1&AnotherParam=2&c=3")
self.assertTrue(isinstance(get_iterable(data), Iterable))
def test_is_iterable(self):
<|code_end|>
. Write the next line using the current file imports:
from collections.abc import Iterable
from django.http import QueryDict
from django.test import TestCase
from django_sonic_screwdriver.iterables import count, get_iterable, is_iterable
and context from other files:
# Path: django_sonic_screwdriver/iterables.py
# def count(iterable):
# """
# Counts the numbers of elements of the iterable.
# """
# if hasattr(iterable, "__len__"):
# return len(iterable)
#
# d = collections.deque(enumerate(iterable, 1), maxlen=1)
# return d[0][0] if d else 0
#
# def get_iterable(data):
# """
# Returns iterable data.
# """
# if isinstance(data, QueryDict):
# return data.lists()
# else:
# return data.items()
#
# def is_iterable(obj):
# """
# Check if obj is iterable.
# """
# try:
# iter(obj)
# except TypeError:
# return False
# else:
# return True
, which may include functions, classes, or code. Output only the next line. | self.assertTrue(is_iterable({})) |
Using the snippet: <|code_start|>
User = get_user_model()
class AppBanTest(TestCase):
def test_user_ban_create(self):
user = User.objects.create(username="test", password="123")
<|code_end|>
, determine the next line of code. You have imports:
from django.test import TestCase
from django.contrib.auth import get_user_model
from django_sonic_screwdriver.apps.ban.models import UserBan, IPBan
and context (class names, function names, or code) available:
# Path: django_sonic_screwdriver/apps/ban/models.py
# class UserBan(Ban):
# banned_user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE,
# verbose_name=_("User"),
# related_name="banned_user",
# blank=False,
# null=True,
# help_text="This is the banned user or the receiver of the ban.",
# )
#
# class Meta:
# verbose_name = _("User Ban")
# verbose_name_plural = _("User Bans")
#
# def __str__(self):
# return self.banned_user.get_username()
#
# class IPBan(Ban):
# ip = models.GenericIPAddressField(
# verbose_name=_("IP"),
# blank=False,
# null=True,
# help_text=_(
# "This is the banned ip. Every request from this IP will result in 403."
# ),
# )
#
# class Meta:
# verbose_name = _("IP Ban")
# verbose_name_plural = _("IP Bans")
#
# def __str__(self):
# return str(self.ip)
. Output only the next line. | UserBan.objects.create(banned_user=user) |
Based on the snippet: <|code_start|>
User = get_user_model()
class AppBanTest(TestCase):
def test_user_ban_create(self):
user = User.objects.create(username="test", password="123")
UserBan.objects.create(banned_user=user)
self.assertEqual(UserBan.objects.count(), 1)
def test_banned_user_will_receive_403(self):
user = User.objects.create(username="test", password="123")
self.client.force_login(user)
res = self.client.get("/home/")
self.assertEqual(res.status_code, 200)
UserBan.objects.create_for_user(banned_user=user)
res = self.client.get("/home/")
self.assertEqual(res.status_code, 403)
def test_banned_ip_will_receive_403(self):
user = User.objects.create(username="test", password="123")
self.client.force_login(user)
res = self.client.get("/home/", REMOTE_ADDR="127.0.0.1")
self.assertEqual(res.status_code, 200)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase
from django.contrib.auth import get_user_model
from django_sonic_screwdriver.apps.ban.models import UserBan, IPBan
and context (classes, functions, sometimes code) from other files:
# Path: django_sonic_screwdriver/apps/ban/models.py
# class UserBan(Ban):
# banned_user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE,
# verbose_name=_("User"),
# related_name="banned_user",
# blank=False,
# null=True,
# help_text="This is the banned user or the receiver of the ban.",
# )
#
# class Meta:
# verbose_name = _("User Ban")
# verbose_name_plural = _("User Bans")
#
# def __str__(self):
# return self.banned_user.get_username()
#
# class IPBan(Ban):
# ip = models.GenericIPAddressField(
# verbose_name=_("IP"),
# blank=False,
# null=True,
# help_text=_(
# "This is the banned ip. Every request from this IP will result in 403."
# ),
# )
#
# class Meta:
# verbose_name = _("IP Ban")
# verbose_name_plural = _("IP Bans")
#
# def __str__(self):
# return str(self.ip)
. Output only the next line. | IPBan.objects.create_for_ip(ip="127.0.0.1") |
Next line prediction: <|code_start|>
@admin.register(UserBan)
class UserBanAdmin(BaseModelAdmin): # pragma: no cover
fieldsets = (
(_("Ban"), {"fields": ("banned_user", "end_date")}),
) + BaseModelAdmin.fieldsets
<|code_end|>
. Use current file imports:
(from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django_sonic_screwdriver.admin import BaseModelAdmin
from .models import UserBan, IPBan)
and context including class names, function names, or small code snippets from other files:
# Path: django_sonic_screwdriver/admin.py
# class BaseModelAdmin(admin.ModelAdmin):
# """
# Base Model Admin
# Describes the default values of nearly every Model.
#
# Note: Model must inherit BaseGameModel!
# """
#
# fieldsets = ((_("Created and Updated"), {"fields": ("created_at", "updated_at")}),)
# readonly_fields = ("created_at", "updated_at")
# list_display = ("__str__", "created_at", "updated_at")
#
# def get_ordering(self, request):
# return ["-created_at"]
#
# Path: django_sonic_screwdriver/apps/ban/models.py
# class UserBan(Ban):
# banned_user = models.ForeignKey(
# settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE,
# verbose_name=_("User"),
# related_name="banned_user",
# blank=False,
# null=True,
# help_text="This is the banned user or the receiver of the ban.",
# )
#
# class Meta:
# verbose_name = _("User Ban")
# verbose_name_plural = _("User Bans")
#
# def __str__(self):
# return self.banned_user.get_username()
#
# class IPBan(Ban):
# ip = models.GenericIPAddressField(
# verbose_name=_("IP"),
# blank=False,
# null=True,
# help_text=_(
# "This is the banned ip. Every request from this IP will result in 403."
# ),
# )
#
# class Meta:
# verbose_name = _("IP Ban")
# verbose_name_plural = _("IP Bans")
#
# def __str__(self):
# return str(self.ip)
. Output only the next line. | @admin.register(IPBan) |
Given the code snippet: <|code_start|> parser.add_argument(
"--production",
action="store_true",
dest="production",
default=False,
help="Create a production tag (e.g. activate-v1.2.3)",
)
parser.add_argument(
"--push", action="store_true", dest="push", default=False, help="Push tags"
)
def handle(self, *args, **options):
"""
:param args:
:param options:
:return:
"""
counter = 0
tag_succeed = 1
for key in options:
if options[key]:
counter += 1
# If no options are set, do a normal patch
if counter == 1:
options["default"] = True
if options["default"]:
<|code_end|>
, generate the next line using the imports in this file:
from django.core.management.base import BaseCommand
from django_sonic_screwdriver.git import git
from django_sonic_screwdriver.settings import api_settings
and context (functions, classes, or occasionally code) from other files:
# Path: django_sonic_screwdriver/git/git.py
# GIT_OPTIONS = {
# "DEVELOPMENT": "development",
# "STAGING": "staging",
# "PRODUCTION": "production",
# }
# class Git:
# def create_git_version_tag(deploy_tag):
# def get_current_branch():
# def get_latest_tag():
# def check_existence_of_staging_tag_in_remote_repo():
# def __debug(command, dry=False):
# def __git_tag(git_tag):
# def __git_tag_gpg(git_tag):
# def __git_tag_push():
# def __git_tag_delete(git_tag):
# def __git_push(self):
# def tag(self, deploy_tag=""):
# def push_tags(self):
# def tag_delete(self, tag):
#
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
. Output only the next line. | tag_succeed = git.tag() |
Predict the next line for this snippet: <|code_start|> dest="production",
default=False,
help="Create a production tag (e.g. activate-v1.2.3)",
)
parser.add_argument(
"--push", action="store_true", dest="push", default=False, help="Push tags"
)
def handle(self, *args, **options):
"""
:param args:
:param options:
:return:
"""
counter = 0
tag_succeed = 1
for key in options:
if options[key]:
counter += 1
# If no options are set, do a normal patch
if counter == 1:
options["default"] = True
if options["default"]:
tag_succeed = git.tag()
if options["staging"]:
<|code_end|>
with the help of current file imports:
from django.core.management.base import BaseCommand
from django_sonic_screwdriver.git import git
from django_sonic_screwdriver.settings import api_settings
and context from other files:
# Path: django_sonic_screwdriver/git/git.py
# GIT_OPTIONS = {
# "DEVELOPMENT": "development",
# "STAGING": "staging",
# "PRODUCTION": "production",
# }
# class Git:
# def create_git_version_tag(deploy_tag):
# def get_current_branch():
# def get_latest_tag():
# def check_existence_of_staging_tag_in_remote_repo():
# def __debug(command, dry=False):
# def __git_tag(git_tag):
# def __git_tag_gpg(git_tag):
# def __git_tag_push():
# def __git_tag_delete(git_tag):
# def __git_push(self):
# def tag(self, deploy_tag=""):
# def push_tags(self):
# def tag_delete(self, tag):
#
# Path: django_sonic_screwdriver/settings.py
# USER_SETTINGS = getattr(settings, "SONIC_SCREWDRIVER", None)
# DEFAULTS = {
# "DEBUG": False,
# # Returns file where the version number is located
# "VERSION_FILE": "setup.py",
# "RELEASE_SEPARATOR": "",
# "PATCH_AUTO_TAG": False,
# # Git
# "GIT_DIR": settings.BASE_DIR,
# # Git Tagging
# "GIT_TAG_AUTO_TAG_PUSH": False,
# "GIT_STAGING_PRE_TAG": "staging",
# "GIT_ACTIVATE_PRE_TAG": "activate",
# "SECURE_TAGGING": True,
# # App Ban
# "BAN_REMOTE_ADDR_HEADER": "REMOTE_ADDR",
# "BAN_DEFAULT_END_TIME": 60 * 60,
# }
# class APISettings(object):
# def __init__(self, user_settings=None, defaults=None):
# def __getattr__(self, attr):
, which may contain function names, class names, or code. Output only the next line. | tag_succeed = git.tag(api_settings.GIT_STAGING_PRE_TAG) |
Given the code snippet: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
, generate the next line using the imports in this file:
import sys
import lasagne.layers.pool as __cloned
from .base import bayes as __bayes
and context (functions, classes, or occasionally code) from other files:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
. Output only the next line. | setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name))) |
Continue the code snippet: <|code_start|>
__all__ = [
'InputLayer'
]
<|code_end|>
. Use current file imports:
from lasagne.layers import InputLayer as _InputLayer
from .base import bayes as _bayes
from theano.compile import SharedVariable
import numpy as np
and context (classes, functions, or code) from other files:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
. Output only the next line. | @_bayes |
Given snippet: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import lasagne.layers.local as __cloned
from .base import bayes as __bayes
and context:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
which might include code, classes, or functions. Output only the next line. | setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name))) |
Here is a snippet: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
. Write the next line using the current file imports:
import sys
import lasagne.layers.shape as __cloned
from .base import bayes as __bayes
and context from other files:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
, which may include functions, classes, or code. Output only the next line. | setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name))) |
Using the snippet: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
, determine the next line of code. You have imports:
import sys
import lasagne.layers.dnn as __cloned
from .base import bayes as __bayes
and context (class names, function names, or code) available:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
. Output only the next line. | setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name))) |
Continue the code snippet: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
. Use current file imports:
import sys
import lasagne.layers.conv as __cloned
from .base import bayes as __bayes
and context (classes, functions, or code) from other files:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
. Output only the next line. | setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name))) |
Given snippet: <|code_start|>exclude = {
'__iter__'
}
mth_template = """\
def {0}{signature}:
'''{doc}'''
return SpecVar{inner_signature}
"""
meths = []
globs = dict(BaseSpec=BaseSpec, copy=copy)
for key, mth in _tensor_py_operators.__dict__.items():
if callable(mth):
if six.PY3:
argspec = inspect.getfullargspec(mth)
keywords = argspec.varkw
else:
argspec = inspect.getargspec(mth)
keywords = argspec.keywords
signature = inspect.formatargspec(*argspec)
inner_signature = inspect.formatargspec(
args=['mth{0}'.format(key)] + argspec.args,
varargs=argspec.varargs,
varkw=keywords,
defaults=argspec.args[1:],
formatvalue=lambda value: '=' + str(value)
)
meths.append(mth_template.format(
key, signature=signature, inner_signature=inner_signature, doc=mth.__doc__))
globs['mth{0}'.format(key)] = mth
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import six
import copy
import itertools
import functools
import inspect
import pymc3 as pm
from theano import theano
from theano.tensor.basic import _tensor_py_operators
from lasagne import init
from gelato._compile import define
and context:
# Path: gelato/_compile.py
# def define(name, template, namespace, frame_offset=1):
# try:
# exec_(template, namespace)
# except SyntaxError as e:
# raise SyntaxError(str(e) + ':\n' + template)
# result = namespace[name]
# frm = inspect.stack()[frame_offset]
# mod = inspect.getmodule(frm[0])
# result.__name__ = name
# if mod is None:
# result.__module__ = '__main__'
# else:
# result.__module__ = mod.__name__
# return result
which might include code, classes, or functions. Output only the next line. | SpecVar = define('SpecVar', head + '\n'.join(meths), globs, 1) |
Predict the next line for this snippet: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
with the help of current file imports:
import sys
import lasagne.layers.embedding as __cloned
from .base import bayes as __bayes
and context from other files:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
, which may contain function names, class names, or code. Output only the next line. | setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name))) |
Next line prediction: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
. Use current file imports:
(import sys
import lasagne.layers.recurrent as __cloned
from .base import bayes as __bayes)
and context including class names, function names, or small code snippets from other files:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
. Output only the next line. | setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name))) |
Predict the next line for this snippet: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
with the help of current file imports:
import sys
import lasagne.layers.special as __cloned
from .base import bayes as __bayes
and context from other files:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
, which may contain function names, class names, or code. Output only the next line. | setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name))) |
Predict the next line after this snippet: <|code_start|>
__all__ = [
'PosteriorLayer',
'SamplingLayer'
]
<|code_end|>
using the current file's imports:
from .base import Layer
and any relevant context from other files:
# Path: gelato/layers/base.py
# class LayerModelMeta(pm.model.InitContextMeta):
# class BayesianAnalog(layercls, pm.Model):
# def __init__(cls, what, bases, dic):
# def fget(self):
# def fset(self, value):
# def wrap_init(__init__):
# def wrapped(self, *args, **kwargs):
# def wrap_new(__new__):
# def wrapped(_cls_, *args, **kwargs):
# def add_param(self, spec, shape, name=None, **tags):
# def wrap_getitem(__getitem__):
# def wrapped(self, item):
# def __repr__(self):
# def __subclasshook__(cls, C):
# def bayes(layercls, stack=1):
. Output only the next line. | class PosteriorLayer(Layer): |
Continue the code snippet: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
. Use current file imports:
import sys
import lasagne.layers.cuda_convnet as __cloned
from .base import bayes
and context (classes, functions, or code) from other files:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
. Output only the next line. | setattr(__module, obj_name, bayes(getattr(__cloned, obj_name))) |
Next line prediction: <|code_start|>__module = sys.modules[__name__]
del sys
__all__ = []
for obj_name in __cloned.__all__:
try:
<|code_end|>
. Use current file imports:
(import sys
import lasagne.layers.merge as __cloned
from .base import bayes as __bayes)
and context including class names, function names, or small code snippets from other files:
# Path: gelato/layers/base.py
# def bayes(layercls, stack=1):
# try:
# issubcls = issubclass(layercls, lasagne.layers.base.Layer)
# except TypeError:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
# if issubcls:
# if type(layercls) is LayerModelMeta:
# raise TypeError('{} is already bayesian'
# .format(layercls))
# else:
# @six.add_metaclass(LayerModelMeta)
# class BayesianAnalog(layercls, pm.Model):
# pass
# frm = inspect.stack()[stack]
# mod = inspect.getmodule(frm[0])
# if mod is None:
# modname = '__main__'
# else:
# modname = mod.__name__
# BayesianAnalog.__module__ = modname
# BayesianAnalog.__doc__ = layercls.__doc__
# BayesianAnalog.__name__ = layercls.__name__
# return BayesianAnalog
# else:
# raise TypeError('{} needs to be a Layer subclass'
# .format(layercls))
. Output only the next line. | setattr(__module, obj_name, __bayes(getattr(__cloned, obj_name))) |
Based on the snippet: <|code_start|>
def test_stats_layers():
intercept = .2
slope = 2
<|code_end|>
, predict the immediate next line with the help of imports:
from theano import theano
from .datasets import generate_linear_regression
from gelato.layers import *
import pymc3 as pm
and context (classes, functions, sometimes code) from other files:
# Path: gelato/tests/datasets.py
# def generate_linear_regression(intercept, slope, sd=.2, size=700):
# x = np.random.uniform(-10, 10, size)
# y = intercept + x * slope
# return x, y + np.random.normal(size=size, scale=sd)
. Output only the next line. | x_, _ = generate_linear_regression(intercept, slope) |
Given snippet: <|code_start|> name = kwargs.get('name')
self._fingerprint = hashable(self.parent)
pm.Model.__init__(self, name)
__init__(self, *args, **kwargs)
return wrapped
# wrap new for new class
def wrap_new(__new__):
@functools.wraps(__new__)
def wrapped(_cls_, *args, **kwargs):
parent = kwargs.get('model', None)
if parent is None and not issubclass(_cls_, lasagne.layers.InputLayer):
incoming = kwargs.get('incoming',
kwargs.get('incomings',
args[1]))
parent = find_parent(incoming)
kwargs['model'] = parent
instance = __new__(_cls_, *args, **kwargs)
return instance
return classmethod(wrapped)
cls.__init__ = wrap_init(cls.__init__)
cls.__new__ = wrap_new(cls.__new__)
def add_param(self, spec, shape, name=None, **tags):
if tags.get('trainable', True):
if tags.get('regularizable', True):
if not isinstance(spec, DistSpec):
# here spec is like test value
# passed to pymc3 distribution
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import functools
import inspect
import six
import lasagne.layers.base
import pymc3 as pm
from pymc3.memoize import hashable
from gelato.specs.dist import get_default_spec, FlatSpec
from gelato.specs.base import DistSpec
from gelato.layers.helper import find_parent
and context:
# Path: gelato/specs/dist.py
# def get_default_spec(testval=None):
# # to avoid init collision
# cp = copy.deepcopy(_default_spec)
# if testval is None and cp.testval is None:
# cp.testval = get_default_testval()
# elif testval is not None:
# cp.testval = testval
# else:
# pass
# return cp
#
# class FlatSpec(PartialSpec):
# spec = pm.Flat
# __doc__ = """Gelato DistSpec with {dist} prior\n\n{doc}""".format(
# dist=spec.__name__,
# doc=spec.__doc__
# )
#
# def __init__(self):
# super(FlatSpec, self).__init__(testval=init.Uniform(1))
#
# Path: gelato/specs/base.py
# class DistSpec(SpecVar):
# """Spec based on pymc3 distributions
#
# All specs support lazy evaluation, see Usage
#
# Parameters
# ----------
# distcls : pymc3.Distribution
# args : args for `distcls`
# kwargs : kwargs for `distcls`
#
# Usage
# -----
# >>> spec = DistSpec(Normal, mu=0, sd=DistSpec(Lognormal, 0, 1))
# >>> spec += (NormalSpec() + LaplaceSpec()) / 100 - NormalSpec()
# >>> with Model():
# ... prior_expr = spec((10, 10), name='silly_prior')
#
# """
# def __init__(self, distcls, *args, **kwargs):
# if not isinstance(distcls, type) and issubclass(distcls, pm.Distribution):
# raise ValueError('We can deal with pymc3 '
# 'distributions only, got {!r} instead'
# .format(distcls))
# self.testval = kwargs.pop('testval', None)
# self.tag = kwargs.get('tag', 'default')
# self.args = args
# self.kwargs = kwargs
# self.distcls = distcls
#
# def __call__(self, shape, name=None, memo=None):
# memo, shape = self._prepare(memo, shape)
# if name is None:
# name = self.auto()
# shape, tag = self._get_shape(shape)
# if id(self) ^ hash(tag) in memo:
# return memo[id(self) ^ hash(tag)]
# model = pm.modelcontext(None)
# called_args = self._call_args(self.args, name, shape, memo)
# called_kwargs = self._call_kwargs(self.kwargs, name, shape, memo)
# called_kwargs.update(shape=shape['default'])
# val = model.Var(
# name, self.distcls.dist(
# *called_args,
# dtype=theano.config.floatX,
# **called_kwargs
# ),
# )
# if self.testval is None:
# val.tag.test_value = get_default_testval()(shape['default']).astype(val.dtype)
# elif isinstance(self.testval, str) and self.testval == 'random':
# val.tag.test_value = val.random(size=shape['default']).astype(val.dtype)
# else:
# val.tag.test_value = self.testval(shape['default']).astype(val.dtype)
# memo[id(self) ^ hash(tag)] = val
# return memo[id(self) ^ hash(tag)]
#
# def __repr__(self):
# if self._shape != -1:
# sh = '; '+str(self._shape)
# else:
# sh = ''
# template = '<{cls}: {args!r}; {kwargs!r}'+sh+'>'
# return template.format(cls=self.distcls.__name__,
# args=self.args,
# kwargs=self.kwargs)
which might include code, classes, or functions. Output only the next line. | spec = getattr(self, 'default_spec', get_default_spec(spec)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.