Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def tearDownModule():
close_webdriver()
CURDIR = path.dirname(path.abspath(__file__))
ROOTDIR = path.dirname(path.dirname(CURDIR))
ENV = os.environ.copy()
ENV['PYTHONPATH'] = ROOTDIR
src_base = '''
import sys # noqa: F401
import asyncio
from wdom.tag import H1
<|code_end|>
, generate the next line using the imports in this file:
import sys
import os
import asyncio
import subprocess
import unittest
from os import path
from tempfile import NamedTemporaryFile
from selenium.common.exceptions import NoSuchElementException
from syncer import sync
from ..base import TestCase
from .base import free_port, browser_implict_wait
from .base import get_webdriver, close_webdriver
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
#
# Path: tests/test_selenium/base.py
# def _get_chromedriver_path() -> str:
# def get_chrome_options() -> webdriver.ChromeOptions:
# def start_webdriver() -> None:
# def close_webdriver() -> None:
# def get_webdriver() -> WebDriver:
# def _clear() -> None:
# def start_remote_browser() -> None:
# def start_browser() -> None:
# def close_remote_browser() -> None:
# def get_remote_browser() -> WebDriver:
# def __init__(self, conn: Connection) -> None:
# def set_element_by_id(self, id: int) -> Union[bool, str]:
# def quit(self) -> str:
# def close(self) -> str:
# def _execute_method(self, method: str, args: Iterable[str]) -> None:
# def run(self) -> None: # noqa: C901
# def wait_for() -> str:
# async def wait_coro() -> str:
# def _get_properties(cls: type) -> Set[str]:
# def __getattr__(self, attr: str) -> Connection:
# def wrapper(*args: str) -> str:
# def start(self) -> None:
# def tearDown(self) -> None:
# def port(self) -> Optional[str]:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def _set_element(self, node: Element) -> Union[bool, str]:
# def set_element(self, node: Element, timeout: float = None) -> bool:
# def setUpClass(cls) -> None: # noqa: D102
# def tearDownClass(cls) -> None: # noqa: D102
# def start(self) -> None:
# def start_server(port: int) -> None:
# def tearDown(self) -> None:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def send_keys(self, element: Element, keys: str) -> None:
# class BrowserController:
# class Controller:
# class ProcessController(Controller):
# class RemoteBrowserController(Controller):
# class RemoteElementController(Controller):
# class TimeoutError(Exception):
# class RemoteBrowserTestCase:
# class WebDriverTestCase:
#
# Path: tests/test_selenium/base.py
# def get_webdriver() -> WebDriver:
# """Return WebDriver of current process.
#
# If it is not started yet, start and return it.
# """
# if globals().get('local_webdriver') is None:
# start_webdriver()
# return local_webdriver
#
# def close_webdriver() -> None:
# """Close WebDriver."""
# global local_webdriver
# if local_webdriver is not None:
# local_webdriver.close()
# local_webdriver = None
. Output only the next line. | from wdom.document import get_document |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def tearDownModule():
close_webdriver()
CURDIR = path.dirname(path.abspath(__file__))
ROOTDIR = path.dirname(path.dirname(CURDIR))
ENV = os.environ.copy()
ENV['PYTHONPATH'] = ROOTDIR
src_base = '''
import sys # noqa: F401
import asyncio
from wdom.tag import H1
from wdom.document import get_document
from wdom import server
loop = asyncio.get_event_loop()
doc = get_document()
<|code_end|>
. Write the next line using the current file imports:
import sys
import os
import asyncio
import subprocess
import unittest
from os import path
from tempfile import NamedTemporaryFile
from selenium.common.exceptions import NoSuchElementException
from syncer import sync
from ..base import TestCase
from .base import free_port, browser_implict_wait
from .base import get_webdriver, close_webdriver
and context from other files:
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
#
# Path: tests/test_selenium/base.py
# def _get_chromedriver_path() -> str:
# def get_chrome_options() -> webdriver.ChromeOptions:
# def start_webdriver() -> None:
# def close_webdriver() -> None:
# def get_webdriver() -> WebDriver:
# def _clear() -> None:
# def start_remote_browser() -> None:
# def start_browser() -> None:
# def close_remote_browser() -> None:
# def get_remote_browser() -> WebDriver:
# def __init__(self, conn: Connection) -> None:
# def set_element_by_id(self, id: int) -> Union[bool, str]:
# def quit(self) -> str:
# def close(self) -> str:
# def _execute_method(self, method: str, args: Iterable[str]) -> None:
# def run(self) -> None: # noqa: C901
# def wait_for() -> str:
# async def wait_coro() -> str:
# def _get_properties(cls: type) -> Set[str]:
# def __getattr__(self, attr: str) -> Connection:
# def wrapper(*args: str) -> str:
# def start(self) -> None:
# def tearDown(self) -> None:
# def port(self) -> Optional[str]:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def _set_element(self, node: Element) -> Union[bool, str]:
# def set_element(self, node: Element, timeout: float = None) -> bool:
# def setUpClass(cls) -> None: # noqa: D102
# def tearDownClass(cls) -> None: # noqa: D102
# def start(self) -> None:
# def start_server(port: int) -> None:
# def tearDown(self) -> None:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def send_keys(self, element: Element, keys: str) -> None:
# class BrowserController:
# class Controller:
# class ProcessController(Controller):
# class RemoteBrowserController(Controller):
# class RemoteElementController(Controller):
# class TimeoutError(Exception):
# class RemoteBrowserTestCase:
# class WebDriverTestCase:
#
# Path: tests/test_selenium/base.py
# def get_webdriver() -> WebDriver:
# """Return WebDriver of current process.
#
# If it is not started yet, start and return it.
# """
# if globals().get('local_webdriver') is None:
# start_webdriver()
# return local_webdriver
#
# def close_webdriver() -> None:
# """Close WebDriver."""
# global local_webdriver
# if local_webdriver is not None:
# local_webdriver.close()
# local_webdriver = None
, which may include functions, classes, or code. Output only the next line. | doc.body.appendChild(H1('FIRST', id='h1')) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def tearDownModule():
close_webdriver()
CURDIR = path.dirname(path.abspath(__file__))
ROOTDIR = path.dirname(path.dirname(CURDIR))
ENV = os.environ.copy()
ENV['PYTHONPATH'] = ROOTDIR
src_base = '''
import sys # noqa: F401
import asyncio
from wdom.tag import H1
from wdom.document import get_document
<|code_end|>
with the help of current file imports:
import sys
import os
import asyncio
import subprocess
import unittest
from os import path
from tempfile import NamedTemporaryFile
from selenium.common.exceptions import NoSuchElementException
from syncer import sync
from ..base import TestCase
from .base import free_port, browser_implict_wait
from .base import get_webdriver, close_webdriver
and context from other files:
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
#
# Path: tests/test_selenium/base.py
# def _get_chromedriver_path() -> str:
# def get_chrome_options() -> webdriver.ChromeOptions:
# def start_webdriver() -> None:
# def close_webdriver() -> None:
# def get_webdriver() -> WebDriver:
# def _clear() -> None:
# def start_remote_browser() -> None:
# def start_browser() -> None:
# def close_remote_browser() -> None:
# def get_remote_browser() -> WebDriver:
# def __init__(self, conn: Connection) -> None:
# def set_element_by_id(self, id: int) -> Union[bool, str]:
# def quit(self) -> str:
# def close(self) -> str:
# def _execute_method(self, method: str, args: Iterable[str]) -> None:
# def run(self) -> None: # noqa: C901
# def wait_for() -> str:
# async def wait_coro() -> str:
# def _get_properties(cls: type) -> Set[str]:
# def __getattr__(self, attr: str) -> Connection:
# def wrapper(*args: str) -> str:
# def start(self) -> None:
# def tearDown(self) -> None:
# def port(self) -> Optional[str]:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def _set_element(self, node: Element) -> Union[bool, str]:
# def set_element(self, node: Element, timeout: float = None) -> bool:
# def setUpClass(cls) -> None: # noqa: D102
# def tearDownClass(cls) -> None: # noqa: D102
# def start(self) -> None:
# def start_server(port: int) -> None:
# def tearDown(self) -> None:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def send_keys(self, element: Element, keys: str) -> None:
# class BrowserController:
# class Controller:
# class ProcessController(Controller):
# class RemoteBrowserController(Controller):
# class RemoteElementController(Controller):
# class TimeoutError(Exception):
# class RemoteBrowserTestCase:
# class WebDriverTestCase:
#
# Path: tests/test_selenium/base.py
# def get_webdriver() -> WebDriver:
# """Return WebDriver of current process.
#
# If it is not started yet, start and return it.
# """
# if globals().get('local_webdriver') is None:
# start_webdriver()
# return local_webdriver
#
# def close_webdriver() -> None:
# """Close WebDriver."""
# global local_webdriver
# if local_webdriver is not None:
# local_webdriver.close()
# local_webdriver = None
, which may contain function names, class names, or code. Output only the next line. | from wdom import server |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def tearDownModule():
close_webdriver()
CURDIR = path.dirname(path.abspath(__file__))
ROOTDIR = path.dirname(path.dirname(CURDIR))
ENV = os.environ.copy()
ENV['PYTHONPATH'] = ROOTDIR
src_base = '''
<|code_end|>
. Use current file imports:
(import sys
import os
import asyncio
import subprocess
import unittest
from os import path
from tempfile import NamedTemporaryFile
from selenium.common.exceptions import NoSuchElementException
from syncer import sync
from ..base import TestCase
from .base import free_port, browser_implict_wait
from .base import get_webdriver, close_webdriver)
and context including class names, function names, or small code snippets from other files:
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
#
# Path: tests/test_selenium/base.py
# def _get_chromedriver_path() -> str:
# def get_chrome_options() -> webdriver.ChromeOptions:
# def start_webdriver() -> None:
# def close_webdriver() -> None:
# def get_webdriver() -> WebDriver:
# def _clear() -> None:
# def start_remote_browser() -> None:
# def start_browser() -> None:
# def close_remote_browser() -> None:
# def get_remote_browser() -> WebDriver:
# def __init__(self, conn: Connection) -> None:
# def set_element_by_id(self, id: int) -> Union[bool, str]:
# def quit(self) -> str:
# def close(self) -> str:
# def _execute_method(self, method: str, args: Iterable[str]) -> None:
# def run(self) -> None: # noqa: C901
# def wait_for() -> str:
# async def wait_coro() -> str:
# def _get_properties(cls: type) -> Set[str]:
# def __getattr__(self, attr: str) -> Connection:
# def wrapper(*args: str) -> str:
# def start(self) -> None:
# def tearDown(self) -> None:
# def port(self) -> Optional[str]:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def _set_element(self, node: Element) -> Union[bool, str]:
# def set_element(self, node: Element, timeout: float = None) -> bool:
# def setUpClass(cls) -> None: # noqa: D102
# def tearDownClass(cls) -> None: # noqa: D102
# def start(self) -> None:
# def start_server(port: int) -> None:
# def tearDown(self) -> None:
# def wait(self, timeout: float = None, times: int = 1) -> None:
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# def send_keys(self, element: Element, keys: str) -> None:
# class BrowserController:
# class Controller:
# class ProcessController(Controller):
# class RemoteBrowserController(Controller):
# class RemoteElementController(Controller):
# class TimeoutError(Exception):
# class RemoteBrowserTestCase:
# class WebDriverTestCase:
#
# Path: tests/test_selenium/base.py
# def get_webdriver() -> WebDriver:
# """Return WebDriver of current process.
#
# If it is not started yet, start and return it.
# """
# if globals().get('local_webdriver') is None:
# start_webdriver()
# return local_webdriver
#
# def close_webdriver() -> None:
# """Close WebDriver."""
# global local_webdriver
# if local_webdriver is not None:
# local_webdriver.close()
# local_webdriver = None
. Output only the next line. | import sys # noqa: F401 |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# flake8: noqa
name = 'Milligram'
project_url = 'http://milligram.github.io/'
project_repository = 'https://github.com/milligram/milligram'
license = 'MIT License'
license_url = 'https://github.com/milligram/milligram/blob/master/license'
css_files = [
'//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic',
'//cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css',
'//cdnjs.cloudflare.com/ajax/libs/milligram/1.1.0/milligram.min.css'
<|code_end|>
using the current file's imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and any relevant context from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | ] |
Based on the snippet: <|code_start|>Col12 = NewTag('Col12', 'div', Col12, class_='col-auto col-sm-auto col-md-auto col-lg-auto col-xl-auto')
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
InfoButton,
WarningButton,
DangerButton,
ErrorButton,
LinkButton,
FormGroup,
Input,
TextInput,
Textarea,
Select,
Table,
Container,
Wrapper,
Row,
Col1,
Col2,
Col3,
Col4,
Col5,
Col6,
Col7,
Col8,
<|code_end|>
, predict the immediate next line with the help of imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (classes, functions, sometimes code) from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | Col9, |
Given the code snippet: <|code_start|> ('wdom', 'element'),
('wdom.examples', 'data_binding'),
('wdom.examples', 'drag'),
('wdom.examples', 'rev_text'),
('wdom.examples', 'theming'),
('wdom', 'event'),
('wdom', 'node'),
('wdom', 'options'),
('wdom', 'parser'),
('wdom', 'server'),
('wdom.server', 'base'),
('wdom.server', 'handler'),
('wdom.server', '_tornado'),
('wdom', 'tag'),
('wdom', 'themes'),
('wdom.themes', 'default'),
('wdom.themes', 'bootstrap3'),
('wdom', 'util'),
('wdom', 'web_node'),
('wdom', 'window'),
]
class TestImportModules(TestCase):
@parameterized.expand(cases)
def test_import(self, from_, import_):
cmd = 'from {0} import {1}\nlist(vars({1}).items())'
proc = subprocess.run(
[sys.executable, '-c', cmd.format(from_, import_)],
stdout=subprocess.PIPE,
<|code_end|>
, generate the next line using the imports in this file:
import sys
import subprocess
from os import path
from parameterized import parameterized
from .base import TestCase
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
. Output only the next line. | stderr=subprocess.STDOUT, |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# flake8: noqa
name = 'MUI'
project_url = 'https://www.muicss.com/'
project_repository = 'https://github.com/muicss/mui'
license = 'MIT License'
license_url = 'https://github.com/muicss/mui/blob/master/LICENSE.txt'
css_files = [
'//cdn.muicss.com/mui-0.5.1/css/mui.min.css',
<|code_end|>
using the current file's imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and any relevant context from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | ] |
Predict the next line after this snippet: <|code_start|>
css_files = [
'//cdn.jsdelivr.net/picnicss/5.1.0/picnic.min.css',
]
Button = NewTag('Button', bases=Button)
DefaultButton = NewTag('DefaultButton', 'button', Button, is_='default-button')
PrimaryButton = NewTag('PrimaryButton', 'button', Button, is_='primary-button')
SecondaryButton = NewTag('SecondaryButton', 'button', Button, is_='secondary-button')
SuccessButton = NewTag('SuccessButton', 'button', Button, class_='success', is_='success-button')
InfoButton = NewTag('InfoButton', 'button', Button, is_='info-button')
WarningButton = NewTag('WarningButton', 'button', Button, class_='warning', is_='warning-button')
DangerButton = NewTag('DangerButton', 'button', Button, class_='error', is_='danger-button')
ErrorButton = NewTag('ErrorButton', 'button', Button, class_='error', is_='error-button')
LinkButton = NewTag('LinkButton', 'button', Button, class_='pseudo', is_='link-button')
Row = NewTag('Row', 'div', Row, class_='row')
Col1 = NewTag('Col1', 'div', Col1)
Col2 = NewTag('Col2', 'div', Col2)
Col3 = NewTag('Col3', 'div', Col3, class_='fourth')
Col4 = NewTag('Col4', 'div', Col4, class_='third')
Col5 = NewTag('Col5', 'div', Col5)
Col6 = NewTag('Col6', 'div', Col6, class_='half')
Col7 = NewTag('Col7', 'div', Col7)
Col8 = NewTag('Col8', 'div', Col8, class_='two-third')
Col9 = NewTag('Col9', 'div', Col9, class_='three-fourth')
Col10 = NewTag('Col10', 'div', Col10)
Col11 = NewTag('Col11', 'div', Col11)
Col12 = NewTag('Col12', 'div', Col12)
<|code_end|>
using the current file's imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and any relevant context from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | extended_classes = [ |
Given the following code snippet before the placeholder: <|code_start|>
class MyButton(Button):
class_ = 'btn'
print(MyButton().html_noid)
# <button class="btn"></button>
# This is almost same as:
class MyButton2(Button):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setAttribute('class', 'btn')
<|code_end|>
, predict the next line using imports from the current file:
from wdom.tag import Button
and context including class names, function names, and sometimes code from other files:
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
. Output only the next line. | ... |
Continue the code snippet: <|code_start|>Select = NewTag('Select', 'select', Select, class_='form-select')
Table = NewTag('Table', 'table', Table, class_='table')
Container = NewTag('Container', 'div', Container, class_='grid grid-fluid')
Wrapper = NewTag('Wrapper', 'div', Wrapper, class_='grid grid-fluid')
Row = NewTag('Row', 'div', Row, class_='row')
Col1 = NewTag('Col1', 'div', Col1, class_='col-1')
Col2 = NewTag('Col2', 'div', Col2, class_='col-2')
Col3 = NewTag('Col3', 'div', Col3, class_='col-3')
Col4 = NewTag('Col4', 'div', Col4, class_='col-4')
Col5 = NewTag('Col5', 'div', Col5, class_='col-5')
Col6 = NewTag('Col6', 'div', Col6, class_='col-6')
Col7 = NewTag('Col7', 'div', Col7, class_='col-7')
Col8 = NewTag('Col8', 'div', Col8, class_='col-8')
Col9 = NewTag('Col9', 'div', Col9, class_='col-9')
Col10 = NewTag('Col10', 'div', Col10, class_='col-10')
Col11 = NewTag('Col11', 'div', Col11, class_='col-11')
Col12 = NewTag('Col12', 'div', Col12, class_='col-12')
extended_classes = [
PrimaryButton,
SuccessButton,
InfoButton,
WarningButton,
DangerButton,
Button,
DefaultButton,
SecondaryButton,
<|code_end|>
. Use current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (classes, functions, or code) from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | LinkButton, |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# flake8: noqa
name = 'Bootstrap3'
project_url = 'http://getbootstrap.com/'
project_repository = 'https://github.com/twbs/bootstrap'
license = 'MIT License'
<|code_end|>
, predict the immediate next line with the help of imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (classes, functions, sometimes code) from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | license_url = 'https://github.com/twbs/bootstrap/blob/master/LICENSE' |
Given snippet: <|code_start|>
ul = Ul()
li1 = Li('item1')
li2 = Li('item2')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from wdom.tag import Ul, Li
and context:
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
which might include code, classes, or functions. Output only the next line. | ... |
Using the snippet: <|code_start|>
ul = Ul()
li1 = Li('item1')
li2 = Li('item2')
...
ul.appendChild(li1)
ul.appendChild(li2)
...
print(ul.html_noid)
# by append
ul2 = Ul()
ul2.append(Li('item1'), Li('item2'))
<|code_end|>
, determine the next line of code. You have imports:
from wdom.tag import Ul, Li
and context (class names, function names, or code) available:
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
. Output only the next line. | print(ul2.html_noid) |
Continue the code snippet: <|code_start|>
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
InfoButton,
WarningButton,
DangerButton,
ErrorButton,
LinkButton,
FormGroup,
Input,
TextInput,
Textarea,
Select,
Table,
Container,
Wrapper,
Row,
Col1,
Col2,
Col3,
Col4,
Col5,
Col6,
Col7,
Col8,
Col9,
<|code_end|>
. Use current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (classes, functions, or code) from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | Col10, |
Given the following code snippet before the placeholder: <|code_start|>
# Making new class easily
MyButton = NewTagClass('MyButton', 'button', Button, class_='btn')
DefaultButton = NewTagClass('DefaultButton', 'button', MyButton, class_='btn-default')
print(MyButton().html_noid)
<|code_end|>
, predict the next line using imports from the current file:
from wdom.tag import Button, NewTagClass
and context including class names, function names, and sometimes code from other files:
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
. Output only the next line. | print(DefaultButton().html_noid) |
Predict the next line after this snippet: <|code_start|>
# Making new class easily
MyButton = NewTagClass('MyButton', 'button', Button, class_='btn')
DefaultButton = NewTagClass('DefaultButton', 'button', MyButton, class_='btn-default')
print(MyButton().html_noid)
<|code_end|>
using the current file's imports:
from wdom.tag import Button, NewTagClass
and any relevant context from other files:
# Path: wdom/tag.py
# class Tag(WdomElement):
# class NestedTag(Tag):
# class Input(Tag, HTMLInputElement):
# class Textarea(Tag, HTMLTextAreaElement): # noqa: D204
# class Script(Tag, HTMLScriptElement): # noqa: D204
# class RawHtmlNode(Tag):
# def __init__(self, *args: Any, attrs: Dict[str, _AttrValueType] = None,
# **kwargs: Any) -> None:
# def _clone_node(self) -> 'Tag':
# def type(self) -> _AttrValueType: # noqa: D102
# def type(self, val: str) -> None: # noqa: D102
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def appendChild(self, child: Node) -> Node: # noqa: D102
# def insertBefore(self, child: Node, ref_node: Node) -> Node: # noqa: D102
# def removeChild(self, child: Node) -> Node: # noqa: D102
# def replaceChild(self, new_child: Node, old_child: Node
# ) -> Node: # noqa: D102
# def childNodes(self) -> NodeList: # noqa: D102
# def empty(self) -> None: # noqa: D102
# def textContent(self, text: str) -> None: # type: ignore
# def html(self) -> str:
# def innerHTML(self) -> str:
# def innerHTML(self, html: str) -> None:
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def value(self) -> str:
# def value(self, value: str) -> None:
# def __init__(self, *args: Any, type: str = 'text/javascript',
# **kwargs: Any) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# H1 = NewTagClass('H1')
# H2 = NewTagClass('H2')
# H3 = NewTagClass('H3')
# H4 = NewTagClass('H4')
# H5 = NewTagClass('H5')
# H6 = NewTagClass('H6')
# P = NewTagClass('P')
# A = NewTagClass('A', 'a', (Tag, HTMLAnchorElement))
# U = NewTagClass('U')
. Output only the next line. | print(DefaultButton().html_noid) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# flake8: noqa
name = 'Pure'
project_url = 'http://purecss.io/'
project_repository = 'https://github.com/yahoo/pure/'
license = 'BSD License'
license_url = 'https://github.com/yahoo/pure/blob/master/LICENSE.md'
<|code_end|>
, predict the next line using imports from the current file:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context including class names, function names, and sometimes code from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | css_files = [ |
Using the snippet: <|code_start|>Input = NewTag('Input', 'input', Input)
TextInput = NewTag('TextInput', 'input', TextInput)
Textarea = NewTag('Textarea', 'textarea', Textarea)
Select = NewTag('Select', 'ul', Ul, class_='dropdown-menu')
Option = NewTag('Option', 'li', Li)
Table = NewTag('Table', 'table', Table, class_='ink-table')
Container = NewTag('Container', 'div', Container, class_='ink-grid')
Wrapper = NewTag('Wrapper', 'div', Wrapper, class_='ink-grid')
Row = NewTag('Row', 'div', Row, class_='column-group')
Col1 = NewTag('Col1', 'div', Col1, class_='all-10')
Col2 = NewTag('Col2', 'div', Col2, class_='all-15')
Col3 = NewTag('Col3', 'div', Col3, class_='all-25')
Col4 = NewTag('Col4', 'div', Col4, class_='all-33')
Col5 = NewTag('Col5', 'div', Col5, class_='all-40')
Col6 = NewTag('Col6', 'div', Col6, class_='all-50')
Col7 = NewTag('Col7', 'div', Col7, class_='all-60')
Col8 = NewTag('Col8', 'div', Col8, class_='all-66')
Col9 = NewTag('Col9', 'div', Col9, class_='all-75')
Col10 = NewTag('Col10', 'div', Col10, class_='all-85')
Col11 = NewTag('Col11', 'div', Col11, class_='all-90')
Col12 = NewTag('Col12', 'div', Col12, class_='all-100')
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
<|code_end|>
, determine the next line of code. You have imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (class names, function names, or code) available:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | InfoButton, |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class TestInitialize(unittest.TestCase):
def test_initialize(self):
old_doc = get_document()
old_app_tornado = _tornado.get_app()
reset()
self.assertIsNot(old_doc, get_document())
<|code_end|>
with the help of current file imports:
import unittest
from wdom.util import reset
from wdom.document import get_document
from wdom.server import _tornado
and context from other files:
# Path: wdom/util.py
# def reset() -> None:
# """Reset all wdom objects.
#
# This function clear all connections, elements, and resistered custom
# elements. This function also makes new document/application and set them.
# """
# from wdom.document import get_new_document, set_document
# from wdom.element import Element
# from wdom.server import _tornado
# from wdom.window import customElements
#
# set_document(get_new_document())
# _tornado.connections.clear()
# _tornado.set_application(_tornado.Application())
# Element._elements_with_id.clear()
# Element._element_buffer.clear()
# customElements.reset()
#
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
, which may contain function names, class names, or code. Output only the next line. | self.assertIsNot(old_app_tornado, _tornado.get_app()) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class TestInitialize(unittest.TestCase):
def test_initialize(self):
old_doc = get_document()
<|code_end|>
. Use current file imports:
import unittest
from wdom.util import reset
from wdom.document import get_document
from wdom.server import _tornado
and context (classes, functions, or code) from other files:
# Path: wdom/util.py
# def reset() -> None:
# """Reset all wdom objects.
#
# This function clear all connections, elements, and resistered custom
# elements. This function also makes new document/application and set them.
# """
# from wdom.document import get_new_document, set_document
# from wdom.element import Element
# from wdom.server import _tornado
# from wdom.window import customElements
#
# set_document(get_new_document())
# _tornado.connections.clear()
# _tornado.set_application(_tornado.Application())
# Element._elements_with_id.clear()
# Element._element_buffer.clear()
# customElements.reset()
#
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
. Output only the next line. | old_app_tornado = _tornado.get_app() |
Predict the next line for this snippet: <|code_start|> self.wd = get_webdriver()
self.port = free_port()
time.sleep(0.01)
cmd = [sys.executable, '-m', self.module, '--port', str(self.port)]
self.proc = subprocess.Popen(cmd, env=os.environ,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
self.url = 'http://localhost:{}'.format(self.port)
time.sleep(1)
self.wd.get(self.url)
def tearDown(self):
self.proc.terminate()
self.proc.wait()
super().tearDown()
class TestReverseText(BaseTestCase, TestCase):
module = 'wdom.examples.rev_text'
def test_revtext(self):
text = 'Click!'
h1 = self.wd.find_element_by_tag_name('h1')
self.assertEqual(h1.text, text)
time.sleep(0.5)
h1.click()
time.sleep(0.5)
self.assertEqual(h1.text, text[::-1])
h1.click()
<|code_end|>
with the help of current file imports:
import sys
import os
import subprocess
import time
import unittest
from selenium.webdriver.common.utils import free_port
from ..base import TestCase
from .base import close_webdriver, get_webdriver
and context from other files:
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
#
# Path: tests/test_selenium/base.py
# def close_webdriver() -> None:
# """Close WebDriver."""
# global local_webdriver
# if local_webdriver is not None:
# local_webdriver.close()
# local_webdriver = None
#
# def get_webdriver() -> WebDriver:
# """Return WebDriver of current process.
#
# If it is not started yet, start and return it.
# """
# if globals().get('local_webdriver') is None:
# start_webdriver()
# return local_webdriver
, which may contain function names, class names, or code. Output only the next line. | time.sleep(0.5) |
Next line prediction: <|code_start|> text = 'Click!'
h1 = self.wd.find_element_by_tag_name('h1')
self.assertEqual(h1.text, text)
time.sleep(0.5)
h1.click()
time.sleep(0.5)
self.assertEqual(h1.text, text[::-1])
h1.click()
time.sleep(0.5)
self.assertEqual(h1.text, text)
class TestDataBinding(BaseTestCase, TestCase):
module = 'wdom.examples.data_binding'
def test_revtext(self):
h1 = self.wd.find_element_by_tag_name('h1')
input = self.wd.find_element_by_tag_name('input')
time.sleep(0.5)
for k in 'test':
input.send_keys(k)
time.sleep(0.5)
self.assertEqual(h1.text, 'test')
class TestTimer(BaseTestCase, TestCase):
module = 'wdom.examples.timer'
def test_timer(self):
view = self.wd.find_element_by_tag_name('h1')
<|code_end|>
. Use current file imports:
(import sys
import os
import subprocess
import time
import unittest
from selenium.webdriver.common.utils import free_port
from ..base import TestCase
from .base import close_webdriver, get_webdriver)
and context including class names, function names, or small code snippets from other files:
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
#
# Path: tests/test_selenium/base.py
# def close_webdriver() -> None:
# """Close WebDriver."""
# global local_webdriver
# if local_webdriver is not None:
# local_webdriver.close()
# local_webdriver = None
#
# def get_webdriver() -> WebDriver:
# """Return WebDriver of current process.
#
# If it is not started yet, start and return it.
# """
# if globals().get('local_webdriver') is None:
# start_webdriver()
# return local_webdriver
. Output only the next line. | start_btn = self.wd.find_element_by_id('start_btn') |
Here is a snippet: <|code_start|> def tearDown(self):
self.proc.terminate()
self.proc.wait()
super().tearDown()
class TestReverseText(BaseTestCase, TestCase):
module = 'wdom.examples.rev_text'
def test_revtext(self):
text = 'Click!'
h1 = self.wd.find_element_by_tag_name('h1')
self.assertEqual(h1.text, text)
time.sleep(0.5)
h1.click()
time.sleep(0.5)
self.assertEqual(h1.text, text[::-1])
h1.click()
time.sleep(0.5)
self.assertEqual(h1.text, text)
class TestDataBinding(BaseTestCase, TestCase):
module = 'wdom.examples.data_binding'
def test_revtext(self):
h1 = self.wd.find_element_by_tag_name('h1')
input = self.wd.find_element_by_tag_name('input')
time.sleep(0.5)
for k in 'test':
<|code_end|>
. Write the next line using the current file imports:
import sys
import os
import subprocess
import time
import unittest
from selenium.webdriver.common.utils import free_port
from ..base import TestCase
from .base import close_webdriver, get_webdriver
and context from other files:
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
#
# Path: tests/test_selenium/base.py
# def close_webdriver() -> None:
# """Close WebDriver."""
# global local_webdriver
# if local_webdriver is not None:
# local_webdriver.close()
# local_webdriver = None
#
# def get_webdriver() -> WebDriver:
# """Return WebDriver of current process.
#
# If it is not started yet, start and return it.
# """
# if globals().get('local_webdriver') is None:
# start_webdriver()
# return local_webdriver
, which may include functions, classes, or code. Output only the next line. | input.send_keys(k) |
Continue the code snippet: <|code_start|>
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
InfoButton,
WarningButton,
DangerButton,
ErrorButton,
LinkButton,
FormGroup,
Select,
Table,
Container,
Wrapper,
Row,
Col,
Col1,
Col2,
Col3,
Col4,
Col5,
Col6,
Col7,
Col8,
Col9,
Col10,
Col11,
<|code_end|>
. Use current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (classes, functions, or code) from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | Col12, |
Predict the next line after this snippet: <|code_start|>
DefaultButton = NewTag('DefaultButton', 'button', Button, class_='bg-white')
PrimaryButton = NewTag('PrimaryButton', 'button', Button, class_='bg-blue')
SecondaryButton = NewTag('SecondaryButton', 'button', Button, class_='bg-grey')
SuccessButton = NewTag('SuccessButton', 'button', Button, class_='bg-light-blue')
InfoButton = NewTag('InfoButton', 'button', Button, class_='bg-green')
WarningButton = NewTag('WarningButton', 'button', Button, class_='bg-orange')
DangerButton = NewTag('DangerButton', 'button', Button, class_='bg-red')
ErrorButton = NewTag('ErrorButton', 'button', Button, class_='bg-red')
LinkButton = NewTag('LinkButton', 'button', Button, class_='bg-cyan')
Row = NewTag('Row', 'div', Row, class_='row')
Col1 = NewTag('Col1', 'div', Col1, class_='col-1')
Col2 = NewTag('Col2', 'div', Col2, class_='col-2')
Col3 = NewTag('Col3', 'div', Col3, class_='col-3')
Col4 = NewTag('Col4', 'div', Col4, class_='col-4')
Col5 = NewTag('Col5', 'div', Col5, class_='col-5')
Col6 = NewTag('Col6', 'div', Col6, class_='col-6')
Col7 = NewTag('Col7', 'div', Col7, class_='col-7')
Col8 = NewTag('Col8', 'div', Col8, class_='col-8')
Col9 = NewTag('Col9', 'div', Col9, class_='col-9')
Col10 = NewTag('Col10', 'div', Col10, class_='col-10')
Col11 = NewTag('Col11', 'div', Col11, class_='col-11')
Col12 = NewTag('Col12', 'div', Col12, class_='col-12')
extended_classes = [
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
<|code_end|>
using the current file's imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and any relevant context from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | InfoButton, |
Given snippet: <|code_start|>Col12 = NewTag('Col12', 'div', Col12, class_='mdl-cell mdl-cell--12-col')
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
InfoButton,
WarningButton,
DangerButton,
ErrorButton,
LinkButton,
FormGroup,
Input,
Label,
Textarea,
Select,
Table,
Th,
Td,
H1,
H2,
H3,
H4,
H5,
H6,
Row,
Col,
Col1,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
which might include code, classes, or functions. Output only the next line. | Col2, |
Next line prediction: <|code_start|> self.win = self.doc.defaultView
self.conn_mock = MagicMock()
_tornado.connections.append(self.conn_mock)
def tearDown(self):
_tornado.connections.remove(self.conn_mock)
def test_custom_elements_registory(self):
self.assertIs(self.win.customElements, customElements)
def test_document(self):
self.assertIs(self.win.document, self.doc)
self.assertIs(self.win, self.doc.defaultView)
def test_wdom_id(self):
self.assertEqual(self.win.wdom_id, 'window')
def test_add_eventlistener(self):
mock = MagicMock(_is_coroutine=False)
self.win.js_exec = MagicMock(_is_coroutine=False)
self.win.addEventListener('click', mock)
self.win.js_exec.assert_called_once_with('addEventListener', 'click')
msg = {
'type': 'click',
'currentTarget': {'id': 'window'},
'target': {'id': 'window'},
}
e = event_handler(msg)
mock.assert_called_once_with(e)
<|code_end|>
. Use current file imports:
(from time import sleep
from unittest.mock import MagicMock
from wdom.document import get_document
from wdom.server import _tornado
from wdom.server.handler import event_handler
from wdom.window import customElements
from .base import TestCase)
and context including class names, function names, or small code snippets from other files:
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# Path: wdom/server/_tornado.py
# def is_connected() -> bool:
# def get(self) -> None:
# def open(self) -> None:
# def on_message(self, message: str) -> None:
# async def terminate(self) -> None:
# def on_close(self) -> None:
# def set_extra_headers(self, path: str) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def log_request(self, handler: web.RequestHandler) -> None:
# def add_static_path(self, prefix: str, path: str) -> None:
# def add_favicon_path(self, path: str) -> None:
# def get_app(*args: Any, **kwargs: Any) -> Application:
# def set_application(app: Application) -> None:
# def start_server(app: web.Application = None, port: int = None,
# address: str = None, **kwargs: Any) -> HTTPServer:
# def stop_server(server: HTTPServer) -> None:
# class MainHandler(web.RequestHandler):
# class WSHandler(websocket.WebSocketHandler):
# class StaticFileHandlerNoCache(web.StaticFileHandler):
# class Application(web.Application):
#
# Path: wdom/server/handler.py
# def event_handler(msg: EventMsgDict) -> Event:
# """Handle events emitted on browser."""
# e = create_event_from_msg(msg)
# if e.currentTarget is None:
# if e.type not in ['mount', 'unmount']:
# id = msg['currentTarget']['id']
# logger.warning('No such element: wdom_id={}'.format(id))
# return e
# e.currentTarget.on_event_pre(e)
# e.currentTarget.dispatchEvent(e)
# return e
#
# Path: wdom/window.py
# @property
# def customElements(self) -> CustomElementsRegistry:
# """Return customElementsRegistry object."""
# return self._custom_elements
#
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
. Output only the next line. | def test_add_event_handler_doc(self): |
Given snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class TestWindow(TestCase):
def setUp(self):
super().setUp()
self.doc = get_document()
self.win = self.doc.defaultView
self.conn_mock = MagicMock()
_tornado.connections.append(self.conn_mock)
def tearDown(self):
_tornado.connections.remove(self.conn_mock)
def test_custom_elements_registory(self):
self.assertIs(self.win.customElements, customElements)
def test_document(self):
self.assertIs(self.win.document, self.doc)
self.assertIs(self.win, self.doc.defaultView)
def test_wdom_id(self):
self.assertEqual(self.win.wdom_id, 'window')
def test_add_eventlistener(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from time import sleep
from unittest.mock import MagicMock
from wdom.document import get_document
from wdom.server import _tornado
from wdom.server.handler import event_handler
from wdom.window import customElements
from .base import TestCase
and context:
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# Path: wdom/server/_tornado.py
# def is_connected() -> bool:
# def get(self) -> None:
# def open(self) -> None:
# def on_message(self, message: str) -> None:
# async def terminate(self) -> None:
# def on_close(self) -> None:
# def set_extra_headers(self, path: str) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def log_request(self, handler: web.RequestHandler) -> None:
# def add_static_path(self, prefix: str, path: str) -> None:
# def add_favicon_path(self, path: str) -> None:
# def get_app(*args: Any, **kwargs: Any) -> Application:
# def set_application(app: Application) -> None:
# def start_server(app: web.Application = None, port: int = None,
# address: str = None, **kwargs: Any) -> HTTPServer:
# def stop_server(server: HTTPServer) -> None:
# class MainHandler(web.RequestHandler):
# class WSHandler(websocket.WebSocketHandler):
# class StaticFileHandlerNoCache(web.StaticFileHandler):
# class Application(web.Application):
#
# Path: wdom/server/handler.py
# def event_handler(msg: EventMsgDict) -> Event:
# """Handle events emitted on browser."""
# e = create_event_from_msg(msg)
# if e.currentTarget is None:
# if e.type not in ['mount', 'unmount']:
# id = msg['currentTarget']['id']
# logger.warning('No such element: wdom_id={}'.format(id))
# return e
# e.currentTarget.on_event_pre(e)
# e.currentTarget.dispatchEvent(e)
# return e
#
# Path: wdom/window.py
# @property
# def customElements(self) -> CustomElementsRegistry:
# """Return customElementsRegistry object."""
# return self._custom_elements
#
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
which might include code, classes, or functions. Output only the next line. | mock = MagicMock(_is_coroutine=False) |
Based on the snippet: <|code_start|>
class TestWindow(TestCase):
def setUp(self):
super().setUp()
self.doc = get_document()
self.win = self.doc.defaultView
self.conn_mock = MagicMock()
_tornado.connections.append(self.conn_mock)
def tearDown(self):
_tornado.connections.remove(self.conn_mock)
def test_custom_elements_registory(self):
self.assertIs(self.win.customElements, customElements)
def test_document(self):
self.assertIs(self.win.document, self.doc)
self.assertIs(self.win, self.doc.defaultView)
def test_wdom_id(self):
self.assertEqual(self.win.wdom_id, 'window')
def test_add_eventlistener(self):
mock = MagicMock(_is_coroutine=False)
self.win.js_exec = MagicMock(_is_coroutine=False)
self.win.addEventListener('click', mock)
<|code_end|>
, predict the immediate next line with the help of imports:
from time import sleep
from unittest.mock import MagicMock
from wdom.document import get_document
from wdom.server import _tornado
from wdom.server.handler import event_handler
from wdom.window import customElements
from .base import TestCase
and context (classes, functions, sometimes code) from other files:
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# Path: wdom/server/_tornado.py
# def is_connected() -> bool:
# def get(self) -> None:
# def open(self) -> None:
# def on_message(self, message: str) -> None:
# async def terminate(self) -> None:
# def on_close(self) -> None:
# def set_extra_headers(self, path: str) -> None:
# def __init__(self, *args: Any, **kwargs: Any) -> None:
# def log_request(self, handler: web.RequestHandler) -> None:
# def add_static_path(self, prefix: str, path: str) -> None:
# def add_favicon_path(self, path: str) -> None:
# def get_app(*args: Any, **kwargs: Any) -> Application:
# def set_application(app: Application) -> None:
# def start_server(app: web.Application = None, port: int = None,
# address: str = None, **kwargs: Any) -> HTTPServer:
# def stop_server(server: HTTPServer) -> None:
# class MainHandler(web.RequestHandler):
# class WSHandler(websocket.WebSocketHandler):
# class StaticFileHandlerNoCache(web.StaticFileHandler):
# class Application(web.Application):
#
# Path: wdom/server/handler.py
# def event_handler(msg: EventMsgDict) -> Event:
# """Handle events emitted on browser."""
# e = create_event_from_msg(msg)
# if e.currentTarget is None:
# if e.type not in ['mount', 'unmount']:
# id = msg['currentTarget']['id']
# logger.warning('No such element: wdom_id={}'.format(id))
# return e
# e.currentTarget.on_event_pre(e)
# e.currentTarget.dispatchEvent(e)
# return e
#
# Path: wdom/window.py
# @property
# def customElements(self) -> CustomElementsRegistry:
# """Return customElementsRegistry object."""
# return self._custom_elements
#
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
. Output only the next line. | self.win.js_exec.assert_called_once_with('addEventListener', 'click') |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def setUpModule():
suppress_logging()
class TestDataBinding(PyppeteerTestCase):
def get_elements(self):
root = data_binding.sample_app()
return root
@sync
<|code_end|>
. Use current file imports:
from syncer import sync
from wdom.util import suppress_logging
from .base import PyppeteerTestCase
from wdom.examples import data_binding
from wdom.examples import global_events
from wdom.examples import rev_text
from wdom.examples import timer
and context (classes, functions, or code) from other files:
# Path: wdom/util.py
# def suppress_logging() -> None:
# """Suppress log output to stdout.
#
# This function is intended to be used in test's setup. This function removes
# log handler of ``wdom`` logger and set NullHandler to suppress log.
# """
# from wdom import options
# options.root_logger.removeHandler(options._log_handler)
# options.root_logger.addHandler(logging.NullHandler())
#
# Path: tests/test_pyppeteer/base.py
# class PyppeteerTestCase(TestCase):
# if os.getenv('TRAVIS', False):
# wait_time = 0.1
# else:
# wait_time = 0.05
#
# @classmethod
# def setUpClass(cls):
# cls.browser = sync(launch(args=['--no-sandbox']))
# cls.page = sync(cls.browser.newPage())
#
# @classmethod
# def tearDownClass(cls):
# sync(cls.browser.close())
#
# def setUp(self):
# from syncer import sync
# super().setUp()
# self.doc = get_document()
# self.root = self.get_elements()
# self.doc.body.prepend(self.root)
# self.server = server.start_server(port=0)
# self.address = server_config['address']
# self.port = server_config['port']
# self.url = 'http://{}:{}'.format(self.address, self.port)
# sync(self.page.goto(self.url))
# self.element = sync(self.get_element_handle(self.root))
#
# def tearDown(self):
# server.stop_server(self.server)
# super().tearDown()
# import time
# time.sleep(0.01)
#
# def get_elements(self):
# raise NotImplementedError
#
# async def get_element_handle(self, elm):
# result = await self.page.querySelector(
# '[wdom_id="{}"]'.format(elm.wdom_id))
# return result
#
# async def get_text(self, elm=None):
# elm = elm or self.element
# result = await self.page.evaluate('(elm) => elm.textContent', elm)
# return result
#
# async def get_attribute(self, name, elm=None):
# elm = elm or self.element
# result = await self.page.evaluate(
# '(elm) => elm.getAttribute("{}")'.format(name), elm)
# return result
#
# async def wait(self, timeout=None):
# timeout = timeout or self.wait_time
# _t = timeout / 10
# for _ in range(10):
# await asyncio.sleep(_t)
#
# async def wait_for_element(self, elm):
# await self.page.waitForSelector(
# '[wdom_id="{}"]'.format(elm.wdom_id),
# {'timeout': 100},
# )
. Output only the next line. | async def test_app(self): |
Predict the next line after this snippet: <|code_start|>
h1 = H1(class_='title')
print(h1.html_noid) # <h1 class="title"></h1>
# this is equivalent to:
h1 = H1()
h1.setAttribute('class', 'title')
# also same as:
<|code_end|>
using the current file's imports:
from wdom.tag import H1
and any relevant context from other files:
# Path: wdom/tag.py
# H1 = NewTagClass('H1')
. Output only the next line. | h1.classList.add('title') |
Predict the next line after this snippet: <|code_start|>DefaultButton = NewTag('DefaultButton', 'button', Button, class_='hollow secondary', is_='default-button')
PrimaryButton = NewTag('PrimaryButton', 'button', Button, is_='primary-button')
SecondaryButton = NewTag('SecondaryButton', 'button', Button, class_='secondary', is_='secondary-button')
SuccessButton = NewTag('SuccessButton', 'button', Button, class_='success', is_='success-button')
InfoButton = NewTag('InfoButton', 'button', Button, class_='success hollow', is_='info-button')
WarningButton = NewTag('WarningButton', 'button', Button, class_='warning', is_='warning-button')
DangerButton = NewTag('DangerButton', 'button', Button, class_='alert', is_='danger-button')
ErrorButton = NewTag('ErrorButton', 'button', Button, class_='alert', is_='error-button')
LinkButton = NewTag('LinkButton', 'button', Button, class_='hollow', is_='link-button')
Row = NewTag('Row', 'div', Row, class_='row')
Col = NewTag('Col', 'div', Col, class_='columns')
Col1 = NewTag('Col1', 'div', Col, class_='small-1 medium-1 large-1', is_='col1')
Col2 = NewTag('Col2', 'div', Col, class_='small-2 medium-2 large-2', is_='col2')
Col3 = NewTag('Col3', 'div', Col, class_='small-3 medium-3 large-3', is_='col3')
Col4 = NewTag('Col4', 'div', Col, class_='small-4 medium-4 large-4', is_='col4')
Col5 = NewTag('Col5', 'div', Col, class_='small-5 medium-5 large-5', is_='col5')
Col6 = NewTag('Col6', 'div', Col, class_='small-6 medium-6 large-6', is_='col6')
Col7 = NewTag('Col7', 'div', Col, class_='small-7 medium-7 large-7', is_='col7')
Col8 = NewTag('Col8', 'div', Col, class_='small-8 medium-8 large-8', is_='col8')
Col9 = NewTag('Col9', 'div', Col, class_='small-9 medium-9 large-9', is_='col9')
Col10 = NewTag('Col10', 'div', Col, class_='small-10 medium-10 large-10', is_='col10')
Col11 = NewTag('Col11', 'div', Col, class_='small-11 medium-11 large-11', is_='col11')
Col12 = NewTag('Col12', 'div', Col, class_='small-12 medium-12 large-12', is_='col12')
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
<|code_end|>
using the current file's imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and any relevant context from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | SuccessButton, |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# flake8: noqa
name = 'Vital'
project_url = 'https://vitalcss.com/'
project_repository = 'https://github.com/doximity/vital'
<|code_end|>
. Use current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (classes, functions, or code) from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | license = 'Apache 2.0' |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# flake8: noqa
name = 'Semantic UI (Semantic)'
project_url = 'http://semantic-ui.com/'
project_repository = 'https://github.com/semantic-org/semantic-ui/'
license = 'MIT License'
license_url = 'https://github.com/Semantic-Org/Semantic-UI/blob/master/LICENSE.md'
css_files = [
'//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.css',
<|code_end|>
. Use current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (classes, functions, or code) from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | ] |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# flake8: noqa
name = 'Kube'
project_url = 'https://imperavi.com/kube/'
project_repository = 'https://github.com/imperavi/kube'
<|code_end|>
. Use current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context (classes, functions, or code) from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
. Output only the next line. | license = 'MIT License' |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def setUpModule():
suppress_logging()
def tearDownModule():
close_webdriver()
class SimpleTestCase(WebDriverTestCase, TestCase):
<|code_end|>
with the help of current file imports:
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.color import Color
from wdom.tag import H1
from wdom.document import get_document, set_app
from wdom.util import suppress_logging
from ..base import TestCase
from .base import WebDriverTestCase, close_webdriver
from wdom.examples.data_binding import sample_app
from wdom.examples.drag import sample_app
from wdom.examples.global_events import sample_page, set_app
from wdom.examples.rev_text import sample_app
from wdom.examples.timer import sample_app
and context from other files:
# Path: wdom/tag.py
# H1 = NewTagClass('H1')
#
# Path: wdom/document.py
# def get_document() -> Document:
# """Get current root document object.
#
# :rtype: Document
# """
# return rootDocument
#
# def set_app(app: Tag) -> None:
# """Set ``Tag`` as applicaion to the current root document.
#
# Equivalent to ``get_document().body.prepend(app)``.
# """
# document = get_document()
# document.body.prepend(app)
#
# Path: wdom/util.py
# def suppress_logging() -> None:
# """Suppress log output to stdout.
#
# This function is intended to be used in test's setup. This function removes
# log handler of ``wdom`` logger and set NullHandler to suppress log.
# """
# from wdom import options
# options.root_logger.removeHandler(options._log_handler)
# options.root_logger.addHandler(logging.NullHandler())
#
# Path: tests/base.py
# class TestCase(unittest.TestCase):
# """Base class for testing wdom modules.
#
# This class is a sub class of the ``unittest.TestCase``. After all test
# methods, reset wdom's global objects like document, application, and
# elements. If you use ``tearDown`` method, do not forget to call
# ``super().tearDown()``.
# """
#
# def setUp(self) -> None:
# """Reset WDOM states."""
# super().setUp()
# reset()
#
# def tearDown(self) -> None:
# """Reset WDOM states."""
# reset()
# super().tearDown()
#
# def assertIsTrue(self, bl: bool) -> None:
# """Check arg is exactly True, not truthy."""
# self.assertIs(bl, True)
#
# def assertIsFalse(self, bl: bool) -> None:
# """Check arg is exactly False, not falsy."""
# self.assertIs(bl, False)
#
# Path: tests/test_selenium/base.py
# class WebDriverTestCase:
# """Base class for testing UI on browser.
#
# This class starts up an HTTP server on a new subprocess.
#
# Subclasses should call ``start`` method after seting up your document.
# After ``start`` method called, the web server is running on the other
# process so you cannot make change on the document. If you need to change
# document after server started, please use ``RemoteBrowserTestCase`` class
# instead.
# """
#
# #: seconds to wait for by ``wait`` method.
# wait_time = 0.01
# #: secondes for deault timeout for ``wait_until`` method
# timeout = 1.0
#
# @classmethod
# def setUpClass(cls) -> None: # noqa: D102
# reset()
#
# @classmethod
# def tearDownClass(cls) -> None: # noqa: D102
# reset()
#
# def start(self) -> None:
# """Start server and web driver."""
# self.wd = get_webdriver()
#
# def start_server(port: int) -> None:
# from wdom import server
# server.start(port=port)
#
# self.address = 'localhost'
# self.port = free_port()
# self.url = 'http://{0}:{1}/'.format(self.address, self.port)
#
# self.server = Process(
# target=start_server,
# args=(self.port, )
# )
# self.server.start()
# self.wait(times=10)
# self.wd.get(self.url)
#
# def tearDown(self) -> None:
# """Terminate server subprocess."""
# self.server.terminate()
# sys.stdout.flush()
# sys.stderr.flush()
# self.wait(times=10)
# super().tearDown() # type: ignore
#
# def wait(self, timeout: float = None, times: int = 1) -> None:
# """Wait for ``timeout`` or ``self.wait_time``."""
# loop = asyncio.get_event_loop()
# for i in range(times):
# loop.run_until_complete(asyncio.sleep(timeout or self.wait_time))
#
# def wait_until(self, func: Callable[[], Any],
# timeout: float = None) -> None:
# """Wait until ``func`` returns True or exceeds timeout.
#
# ``func`` is called with no argument. Unit of ``timeout`` is second, and
# its default value is RemoteBrowserTestCase.timeout class variable
# (default: 1.0).
# """
# st = time.perf_counter()
# timeout = timeout or self.timeout
# while (time.perf_counter() - st) < timeout:
# if func():
# return
# self.wait()
# raise TimeoutError('{} did not return True until timeout'.format(func))
#
# def send_keys(self, element: Element, keys: str) -> None:
# """Send ``keys`` to ``element`` one-by-one.
#
# Safer than using ``element.send_keys`` method.
# """
# for k in keys:
# element.send_keys(k)
#
# def close_webdriver() -> None:
# """Close WebDriver."""
# global local_webdriver
# if local_webdriver is not None:
# local_webdriver.close()
# local_webdriver = None
, which may contain function names, class names, or code. Output only the next line. | def setUp(self): |
Here is a snippet: <|code_start|>Wrapper = NewTag('Wrapper', 'div', Wrapper, class_='container')
Row = NewTag('Row', 'div', Row, class_='row')
Col = NewTag('Col', 'div', Col, class_='col')
Col1 = NewTag('Col1', 'div', Col1, class_='col xs-1 sm-1 md-1 lg-1 xl-1')
Col2 = NewTag('Col2', 'div', Col2, class_='col xs-2 sm-2 md-2 lg-2 xl-2')
Col3 = NewTag('Col3', 'div', Col3, class_='col xs-3 sm-3 md-3 lg-3 xl-3')
Col4 = NewTag('Col4', 'div', Col4, class_='col xs-4 sm-4 md-4 lg-4 xl-4')
Col5 = NewTag('Col5', 'div', Col5, class_='col xs-5 sm-5 md-5 lg-5 xl-5')
Col6 = NewTag('Col6', 'div', Col6, class_='col xs-6 sm-6 md-6 lg-6 xl-6')
Col7 = NewTag('Col7', 'div', Col7, class_='col xs-7 sm-7 md-7 lg-7 xl-7')
Col8 = NewTag('Col8', 'div', Col8, class_='col xs-8 sm-8 md-8 lg-8 xl-8')
Col9 = NewTag('Col9', 'div', Col9, class_='col xs-9 sm-9 md-9 lg-9 xl-9')
Col10 = NewTag('Col10', 'div', Col10, class_='col xs-10 sm-10 md-10 lg-10 xl-10')
Col11 = NewTag('Col11', 'div', Col11, class_='col xs-11 sm-11 md-11 lg-11 xl-11')
Col12 = NewTag('Col12', 'div', Col12, class_='col xs-12 sm-12 md-12 lg-12 xl-12')
extended_classes = [
Button,
DefaultButton,
PrimaryButton,
SecondaryButton,
SuccessButton,
InfoButton,
WarningButton,
DangerButton,
ErrorButton,
LinkButton,
Input,
TextInput,
<|code_end|>
. Write the next line using the current file imports:
from wdom.tag import NewTagClass as NewTag
from wdom.themes import *
and context from other files:
# Path: wdom/tag.py
# def NewTagClass(class_name: str, tag: str = None,
# bases: Union[type, Iterable] = (Tag, ),
# **kwargs: Any) -> type:
# """Generate and return new ``Tag`` class.
#
# If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of
# the new class. ``bases`` should be a tuple of base classes. If it is empty,
# use ``Tag`` class for a base class. Other keyword arguments are used for
# class variables of the new class.
#
# Example::
#
# MyButton = NewTagClass('MyButton', 'button', (Button,),
# class_='btn', is_='my-button')
# my_button = MyButton('Click!')
# print(my_button.html)
#
# >>> <button class="btn" id="111111111" is="my-button">Click!</button>
# """
# if tag is None:
# tag = class_name.lower()
# if not isinstance(type, tuple):
# if isinstance(bases, Iterable):
# bases = tuple(bases)
# elif isinstance(bases, type):
# bases = (bases, )
# else:
# TypeError('Invalid base class: {}'.format(str(bases)))
# kwargs['tag'] = tag
# # Here not use type() function, since it does not support
# # metaclasss (__prepare__) properly.
# cls = new_class( # type: ignore
# class_name, bases, {}, lambda ns: ns.update(kwargs))
# return cls
, which may include functions, classes, or code. Output only the next line. | Textarea, |
Here is a snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-05-06 14:35:53
# @Author : moling (365024424@qq.com)
# @Link : http://www.qiangtaoli.com
# @Version : 0.1
_RE_EMAIL = re.compile(r'^[a-zA-Z0-9\.\-\_]+\@[a-zA-Z0-9\-\_]+(\.[a-zA-Z0-9\-\_]+){1,4}$')
_RE_SHA1 = re.compile(r'^[0-9a-f]{40}$')
# 网页翻页信息类
class Page(object):
def __init__(self, item_count, index=1, size=10):
self.last = item_count // size + (1 if item_count % size > 0 else 0) # 尾页
self.index = min(index, self.last) if item_count > 0 else 1 # 当前页
<|code_end|>
. Write the next line using the current file imports:
import re
from .errors import APIPermissionError, APIValueError
and context from other files:
# Path: www/app/frame/errors.py
# class APIPermissionError(APIError):
#
# '''
# Indicate the api has no permission.
# '''
#
# def __init__(self, message=''):
# super(APIPermissionError, self).__init__('permission:forbidden', 'permission', message)
#
# class APIValueError(APIError):
#
# '''
# Indicate the input value has error or invalid. The data specifies the error field of input form.
# '''
#
# def __init__(self, field, message=''):
# super(APIValueError, self).__init__('value:invalid', field, message)
, which may include functions, classes, or code. Output only the next line. | self.offset = size * (index - 1) # 数据库查询用,偏移N个元素 |
Given snippet: <|code_start|> elif isinstance(limit, tuple) and len(limit) == 2: # limit可以取2个参数,表示一个范围
sql.append('limit ?, ?')
args.extend(limit)
else:
raise ValueError('Invalid limit value: %s' % limit)
resultset = await select(' '.join(sql), args) # 调用前面定义的select函数,没有指定size,因此会fetchall
return [cls(**r) for r in resultset] # 返回结果,结果是list对象,里面的元素是dict类型的
# 根据列名和条件查看数据库有多少条信息
@classmethod
async def countRows(cls, selectField='*', where=None, args=None):
' find number by select and where. '
sql = ['select count(%s) _num_ from `%s`' % (selectField, cls.__table__)]
if where:
sql.append('where %s' % (where))
resultset = await select(' '.join(sql), args, 1) # size = 1
if not resultset:
return 0
return resultset[0].get('_num_', 0)
# 根据主键查找一个实例的信息
@classmethod
async def find(cls, pk):
' find object by primary key. '
resultset = await select('%s where `%s`= ?' % (cls.__select__, cls.__primary_key__), [pk], 1)
return cls(**resultset[0]) if resultset else None
# 把一个实例保存到数据库
async def save(self):
args = list(map(self.getValueOrDefault, self.__mappings__))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import aiomysql
from .fields import Field
and context:
# Path: www/app/frame/fields.py
# class Field(object):
#
# def __init__(self, name, column_type, primary_key, default):
# self.name = name
# self.column_type = column_type
# self.primary_key = primary_key
# self.default = default
#
# def __str__(self):
# return '<{0.__class__.__name__}, {0.column_type}: {0.name}>'.format(self)
which might include code, classes, or functions. Output only the next line. | rows = await execute(self.__insert__, args) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
from __future__ import unicode_literals
sys.path.append('..')
# Generic tests for ReflectRPC command-line utils
class CmdlineTests(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(CmdlineTests, self).__init__(*args, **kwargs)
self.cmdline_programs = ['rpcsh', 'rpcdoc', 'rpcgencode']
def test_cmdline_expect_connection_fails(self):
for cmd in self.cmdline_programs:
# connect although no server is running
try:
python = sys.executable
<|code_end|>
, predict the next line using imports from the current file:
from builtins import bytes, dict, list, int, float, str
from reflectrpc.testing import ServerRunner
import os
import sys
import unittest
import pexpect
and context including class names, function names, and sometimes code from other files:
# Path: reflectrpc/testing.py
# class ServerRunner(object):
# """
# Runs a server program in a subprocess and allows to stop it again
# """
# def __init__(self, path, port):
# self.directory = os.path.dirname(path)
# self.server_program = os.path.basename(path)
# self.host = 'localhost'
# self.port = port
# self.pid = None
# self.timeout = 5
#
# def run(self):
# # we don't fork before we know that the TCP port/UNIX socket is free
# if isinstance(self.port, int):
# wait_for_free_port(self.host, self.port, self.timeout)
# else:
# wait_for_unix_socket_gone(self.port, self.timeout)
#
# pid = os.fork()
#
# if not pid:
# # child
# os.chdir(self.directory)
#
# if self.server_program.endswith('.py'):
# python = sys.executable
# os.execl(python, python, self.server_program)
# else:
# os.execl(self.server_program, self.server_program)
# else:
# # parent
# self.pid = pid
#
# if isinstance(self.port, int):
# wait_for_tcp_port_in_use(self.host, self.port, self.timeout)
# else:
# wait_for_unix_socket_in_use(self.port, self.timeout)
#
# def stop(self):
# os.kill(self.pid, signal.SIGINT)
# os.waitpid(self.pid, 0)
#
# if isinstance(self.port, int):
# wait_for_free_port(self.host, self.port, self.timeout)
# else:
# wait_for_unix_socket_gone(self.port, self.timeout)
. Output only the next line. | outfile = '' |
Here is a snippet: <|code_start|>
statinfo = os.stat(filename)
self.assertGreater(statinfo.st_size, 0)
finally:
server.stop()
shutil.rmtree(dirname)
def test_rpcdoc_http_basic_auth(self):
try:
server = ServerRunner('../examples/serverhttp.py', 5500)
server.run()
python = sys.executable
dirname = tempfile.mkdtemp()
filename = os.path.join(dirname, 'doc.html')
child = pexpect.spawn('%s ../rpcdoc localhost 5500 %s --http --http-basic-user testuser' % (python, filename))
child.expect('Password: ')
child.sendline('123456')
child.read()
child.wait()
if child.status != 0:
self.fail('rpcdoc returned with a non-zero status code')
if not os.path.exists(filename):
self.fail("File '%s' was not created by rpcdoc" % (filename))
statinfo = os.stat(filename)
self.assertGreater(statinfo.st_size, 0)
<|code_end|>
. Write the next line using the current file imports:
from builtins import bytes, dict, list, int, float, str
from reflectrpc.testing import ServerRunner
import errno
import sys
import json
import os
import os.path
import pexpect
import shutil
import subprocess
import tempfile
import unittest
and context from other files:
# Path: reflectrpc/testing.py
# class ServerRunner(object):
# """
# Runs a server program in a subprocess and allows to stop it again
# """
# def __init__(self, path, port):
# self.directory = os.path.dirname(path)
# self.server_program = os.path.basename(path)
# self.host = 'localhost'
# self.port = port
# self.pid = None
# self.timeout = 5
#
# def run(self):
# # we don't fork before we know that the TCP port/UNIX socket is free
# if isinstance(self.port, int):
# wait_for_free_port(self.host, self.port, self.timeout)
# else:
# wait_for_unix_socket_gone(self.port, self.timeout)
#
# pid = os.fork()
#
# if not pid:
# # child
# os.chdir(self.directory)
#
# if self.server_program.endswith('.py'):
# python = sys.executable
# os.execl(python, python, self.server_program)
# else:
# os.execl(self.server_program, self.server_program)
# else:
# # parent
# self.pid = pid
#
# if isinstance(self.port, int):
# wait_for_tcp_port_in_use(self.host, self.port, self.timeout)
# else:
# wait_for_unix_socket_in_use(self.port, self.timeout)
#
# def stop(self):
# os.kill(self.pid, signal.SIGINT)
# os.waitpid(self.pid, 0)
#
# if isinstance(self.port, int):
# wait_for_free_port(self.host, self.port, self.timeout)
# else:
# wait_for_unix_socket_gone(self.port, self.timeout)
, which may include functions, classes, or code. Output only the next line. | finally: |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
from __future__ import unicode_literals
sys.path.append('..')
class RpcGenCodeTests(unittest.TestCase):
def test_basic_operation(self):
server = ServerRunner('../examples/server.py', 5500)
server.run()
python = sys.executable
cwd = os.getcwd()
try:
dirname = tempfile.mkdtemp()
<|code_end|>
, predict the next line using imports from the current file:
from builtins import bytes, dict, list, int, float, str
from reflectrpc.testing import ServerRunner
import errno
import sys
import json
import os
import os.path
import shutil
import subprocess
import tempfile
import unittest
and context including class names, function names, and sometimes code from other files:
# Path: reflectrpc/testing.py
# class ServerRunner(object):
# """
# Runs a server program in a subprocess and allows to stop it again
# """
# def __init__(self, path, port):
# self.directory = os.path.dirname(path)
# self.server_program = os.path.basename(path)
# self.host = 'localhost'
# self.port = port
# self.pid = None
# self.timeout = 5
#
# def run(self):
# # we don't fork before we know that the TCP port/UNIX socket is free
# if isinstance(self.port, int):
# wait_for_free_port(self.host, self.port, self.timeout)
# else:
# wait_for_unix_socket_gone(self.port, self.timeout)
#
# pid = os.fork()
#
# if not pid:
# # child
# os.chdir(self.directory)
#
# if self.server_program.endswith('.py'):
# python = sys.executable
# os.execl(python, python, self.server_program)
# else:
# os.execl(self.server_program, self.server_program)
# else:
# # parent
# self.pid = pid
#
# if isinstance(self.port, int):
# wait_for_tcp_port_in_use(self.host, self.port, self.timeout)
# else:
# wait_for_unix_socket_in_use(self.port, self.timeout)
#
# def stop(self):
# os.kill(self.pid, signal.SIGINT)
# os.waitpid(self.pid, 0)
#
# if isinstance(self.port, int):
# wait_for_free_port(self.host, self.port, self.timeout)
# else:
# wait_for_unix_socket_gone(self.port, self.timeout)
. Output only the next line. | packagedir = os.path.join(dirname, 'example') |
Predict the next line for this snippet: <|code_start|>from __future__ import unicode_literals
# The below compiled regex (`textplusstuff_re`) matches the following pattern:
# {% textplusstuff '%(content_type__app_label)s'
# ':%(content_type__model)s:%(pk)d'
# ':%(rendition_key)s:%(field)s' %}
# Example:
# {% textplusstuff 'carousel:carousel:4:full_width:content' %}
textplusstuff_re = re.compile(
"\{\%\s*textplusstuff\s*.*?"
"(?P<textplusstuff_token>[a-z-A-Z-0-9:_]+).*?\s*\%\}"
)
class TextPlusStuffLexer(object):
<|code_end|>
with the help of current file imports:
import re
from ..exceptions import MalformedToken
from .tokens import TextPlusStuffToken
and context from other files:
# Path: textplusstuff/exceptions.py
# class MalformedToken(Exception):
# pass
#
# Path: textplusstuff/parser/tokens.py
# class TextPlusStuffToken(object):
#
# def __init__(self, token_type, contents):
# # token_type must be MARKDOWN_FLAVORED_TEXT_TOKEN
# # or RICHTEXT_TOKEN.
# self.token_type, self.contents = token_type, contents
# self.lineno = None
#
# def __unicode__(self):
# return '<{token_type} token: "{content}...">'.format(
# token_type=self.token_type,
# content=self.contents[:10].replace('\n', '')
# )
, which may contain function names, class names, or code. Output only the next line. | def __init__(self, raw_val): |
Given snippet: <|code_start|>from __future__ import unicode_literals
try:
except ImportError:
class TextPlusStuffWidget(Textarea):
def render(self, name, value, attrs=None):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.forms.utils import flatatt
from django.forms.util import flatatt # Django 1.6.x
from django.forms.widgets import Textarea
from django.utils.encoding import force_text
from django.utils.html import format_html
from .datastructures import TextPlusStuff
and context:
# Path: textplusstuff/datastructures.py
# class TextPlusStuff(object):
#
# def __init__(self, raw_text, field=None):
# raw_text = raw_text or ""
# if not isinstance(raw_text, str):
# raise UnicodeError(
# (
# "TextPlusStuff can only be initialized with either "
# "unicode or UTF-8 strings."
# )
# )
# else:
# raw_text_processed = force_text(raw_text, errors='replace')
# self.raw_text = raw_text_processed
# # Initialize lexer
# lexer = TextPlusStuffLexer(raw_val=raw_text_processed)
# # Use the lexer to create tokens
# tokens = lexer.tokenize()
# # Pass tokens to parser and parse
# self.nodelist = TextPlusStuffParser(tokens=tokens).parse()
#
# def render(self, render_markdown_as, **kwargs):
# """
# Renders a TextPlusStuffField
# `render_markdown_as`: The format that markdown-flavored text should
# be transformed in. Options: `html`, `markdown`, `plain_text`
# """
# final_output = ""
# include_content_nodes = kwargs.pop('include_content_nodes', True)
# extra_context = kwargs.pop('extra_context', None)
# for node in self.nodelist:
# if isinstance(node, MarkdownFlavoredTextNode):
# final_output += node.render(render_as=render_markdown_as)
# elif isinstance(node, ModelStuffNode):
# if include_content_nodes is False:
# pass
# else:
# final_output += node.render(extra_context=extra_context)
# return final_output
#
# def as_html(self, **kwargs):
# """
# Renders a TextPlusStuffField as HTML.
# Optional keyword arguments:
# * `include_content_nodes`: Boolean signifying whether or not to render
# content nodes (i.e. ModelStuff tokens).
# Defaults to `True`.
# """
# return mark_safe(
# self.render(
# 'html',
# include_content_nodes=kwargs.pop(
# 'include_content_nodes', True
# ),
# extra_context=kwargs.pop('extra_context', None)
# )
# )
#
# def as_json(self, **kwargs):
# """
# Renders a TextPlusStuffField as a JSON object.
#
# * `render_markdown_as`: The format that markdown-flavored text should
# be transformed in. Options: `html` (default), `markdown`, `plain_text`.
# """
# final_output_as_html = ""
# final_output_as_markdown = ""
# include_content_nodes = kwargs.pop('include_content_nodes', True)
# extra_context = kwargs.pop('extra_context', None)
# convert_to_json_string = kwargs.pop('convert_to_json_string', False)
# model_stuff_node_counter = 0
# model_stuff_node_context_list = []
# for node in self.nodelist:
# if isinstance(node, MarkdownFlavoredTextNode):
# final_output_as_html += node.render(render_as='html')
# final_output_as_markdown += node.render(render_as='markdown')
# elif isinstance(node, ModelStuffNode):
# if include_content_nodes is True:
# final_output_as_markdown += "{{{{ NODE__{index} }}}}"\
# .format(
# index=model_stuff_node_counter
# )
# final_output_as_html += (
# '<span data-textplusstuff-contentnode-arrayindex='
# '"{index}"></span>'
# ).format(index=model_stuff_node_counter)
# model_stuff_node_context_list.append({
# 'model': '{}:{}'.format(
# node.node_mapping.get('content_type__app_label'),
# node.node_mapping.get('content_type__model')
# ),
# 'rendition': node.get_rendition().short_name,
# 'context': node.get_node_context(
# extra_context=extra_context
# )
# })
# model_stuff_node_counter += 1
# dict_to_return = {
# 'text_as_markdown': final_output_as_markdown,
# 'text_as_html': final_output_as_html,
# 'content_nodes': model_stuff_node_context_list
# }
#
# to_return = dict_to_return
# if convert_to_json_string is True:
# to_return = json.dumps(dict_to_return)
#
# return to_return
#
# def as_plaintext(self, **kwargs):
# """
# Renders a TextPlusStuffField as plain text (all markdown
# formatting removed).
#
# Content nodes (i.e. ModelStuff tokens) will not be rendered.
# """
# return self.render(
# 'plain_text',
# include_content_nodes=False
# )
#
# def as_markdown(self, **kwargs):
# """
# Renders a TextPlusStuffField as markdown.
#
# Content nodes (i.e. ModelStuff tokens) will not be rendered.
# """
# return self.render(
# 'markdown',
# include_content_nodes=False
# )
which might include code, classes, or functions. Output only the next line. | value = value or '' |
Predict the next line for this snippet: <|code_start|>from __future__ import unicode_literals
class TextPlusStuffRegisteredModelAdmin(admin.ModelAdmin):
change_form_template = 'textplusstuff/change_form_with_renditions.html'
def change_view(self, request, object_id, form_url='', extra_context=None):
obj = self.get_object(request, admin.utils.unquote(object_id))
rendition_dict = get_modelstuff_renditions(obj) or {}
rendition_list = [
rendition
for short_name, rendition in rendition_dict.items()
]
extra_context = extra_context or {}
if rendition_dict:
extra_context.update({
'textplusstuff_rendition_list': rendition_list
})
return super(TextPlusStuffRegisteredModelAdmin, self).change_view(
request, object_id, form_url=form_url, extra_context=extra_context
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from .models import TextPlusStuffDraft
from .registry import get_modelstuff_renditions
and context from other files:
# Path: textplusstuff/models.py
# class TextPlusStuffDraft(models.Model):
# """
# A simple model used to hold 'drafts' of TextPlusStuffField
# content.
# """
# title = models.CharField(
# _('Draft Title'),
# max_length=100
# )
# user = models.ForeignKey(
# 'auth.User',
# verbose_name=_('User'),
# help_text=_(
# 'The user who created this draft.'
# ),
# null=True,
# on_delete=models.SET_NULL,
# )
# date_created = models.DateTimeField(
# _('Date Created'),
# auto_now_add=True,
# help_text=_('The date this draft was originally created.')
# )
# date_modified = models.DateTimeField(
# _('Date Modified'),
# auto_now=True,
# help_text=_('The date this draft was updated.')
# )
# content = TextPlusStuffField(
# _('Content'),
# blank=True
# )
# content_ported = models.BooleanField(
# _('Content Ported'),
# default=False,
# help_text=_(
# 'Signifies whether or not this draft has been used to populate '
# 'a TextPlusStuffField on another model.'
# )
# )
#
# class Meta:
# verbose_name = _('Text Plus Stuff Draft')
# verbose_name_plural = _('Text Plus Stuff Drafts')
#
# Path: textplusstuff/registry.py
# def get_modelstuff_renditions(model_instance):
# """
# Build out a dict of the available MODELSTUFF renditions
# for a particular model instance
# """
# stuff_config, groups = stuff_registry._registry.get(
# model_instance._meta.model, (None, None)
# )
# if stuff_config is not None:
# return dict(
# (
# short_name,
# {
# 'verbose_name': rendition.verbose_name,
# 'description': rendition.description,
# 'token': (
# "{{% textplusstuff 'MODELSTUFF__{app}:{model}:"
# "{pk}:{rend}' %}}"
# ).format(
# app=model_instance._meta.app_label,
# model=model_instance._meta.model_name,
# pk=model_instance.pk,
# rend=short_name
# ),
# 'path_to_template': rendition.path_to_template,
# 'type': rendition.rendition_type
#
# }
# )
# for short_name, rendition in stuff_config._renditions.items()
# )
, which may contain function names, class names, or code. Output only the next line. | ) |
Predict the next line after this snippet: <|code_start|>
class RegisteredModelStuff(registry.ModelStuff):
# The queryset used to retrieve instances of TestModel
# within the front-end interface. For instance, you could
# exclude 'unpublished' instances or anything else you can
# query the ORM against
queryset = RegisteredModel.objects.all()
# What humans see when they see this stuff
# verbose_name = 'Registration Test Model'
# verbose_name_plural = 'Registration Test Models'
description = 'Add an Registration Test Model'
# The serializer we just defined, this is what provides the context/JSON
# payload for this Stuff
serializer_class = RegisteredModelSerializer
# All Stuff must have at least one rendition (specified in
# the `renditions` attribute below) which basically
# just points to a template and some human-readable metadata.
# At present there are only two options for setting rendition_type:
# either 'block' (the default) or inline. These will be used by
# the front-end editor when placing tokens.
renditions = [
registry.Rendition(
short_name='test_rendition',
verbose_name='Test Rendition',
description='Displays a Test Rendition rendered.',
<|code_end|>
using the current file's imports:
from textplusstuff import registry
from .models import RegisteredModel
from .serializers import RegisteredModelSerializer
and any relevant context from other files:
# Path: textplusstuff/registry.py
# class Rendition(object):
# class Stuff(object):
# class ModelStuff(Stuff):
# class ListSerializer(ModelSerializer):
# class Meta:
# class StuffRegistry(object):
# class ListStuffGroups(TextPlusStuffAPIViewMixIn, APIView):
# def __init__(self, short_name, verbose_name, description,
# path_to_template, rendition_type='block'):
# def get_context_data(self, **context):
# def render_as_html(self, context):
# def __init__(self, model):
# def _verify_rendition(self, rendition):
# def _verify_rendition_list_uniqueness(self, rendition_list):
# def _verify_and_build_initial_rendition_dict(self):
# def register_non_core_rendition(self, rendition):
# def get_list_serializer(self):
# def list_view(self):
# def detail_view(self):
# def get_url_name_key(self):
# def get_urls(self):
# def __init__(self, name='stuff_registry'):
# def verify_stuff_cls(self, stuff_cls):
# def verify_groups(self, groups, stuff_cls):
# def add_modelstuff(self, model, stuff_cls, groups=[]):
# def add_noncore_modelstuff_rendition(self, model, rendition):
# def remove_modelstuff(self, model):
# def index(self):
# def prepare_stuffgroups(self):
# def get_generated_stuffgroups(self):
# def get(self, request, format=None):
# def get_urls(self):
# def urls(self):
# def get_modelstuff_renditions(model_instance):
#
# Path: tests/models.py
# class RegisteredModel(models.Model):
# """
# A simple model used to test textplusstuff.registry.StuffRegistry
# """
# title = models.CharField(
# max_length=90
# )
#
# class Meta:
# verbose_name = _('Registered Model')
# verbose_name_plural = _('Registered Models')
#
# def __unicode__(self):
# return "registeredmodel:{}".format(self.pk)
#
# Path: tests/serializers.py
# class RegisteredModelSerializer(ExtraContextSerializerMixIn,
# serializers.ModelSerializer):
#
# class Meta:
# model = RegisteredModel
# fields = ('title',)
. Output only the next line. | path_to_template='RegisteredModel_test_rendition.html', |
Using the snippet: <|code_start|>
class RegisteredModelStuff(registry.ModelStuff):
# The queryset used to retrieve instances of TestModel
# within the front-end interface. For instance, you could
# exclude 'unpublished' instances or anything else you can
# query the ORM against
queryset = RegisteredModel.objects.all()
# What humans see when they see this stuff
# verbose_name = 'Registration Test Model'
# verbose_name_plural = 'Registration Test Models'
description = 'Add an Registration Test Model'
# The serializer we just defined, this is what provides the context/JSON
# payload for this Stuff
serializer_class = RegisteredModelSerializer
# All Stuff must have at least one rendition (specified in
# the `renditions` attribute below) which basically
# just points to a template and some human-readable metadata.
# At present there are only two options for setting rendition_type:
# either 'block' (the default) or inline. These will be used by
# the front-end editor when placing tokens.
renditions = [
registry.Rendition(
short_name='test_rendition',
verbose_name='Test Rendition',
<|code_end|>
, determine the next line of code. You have imports:
from textplusstuff import registry
from .models import RegisteredModel
from .serializers import RegisteredModelSerializer
and context (class names, function names, or code) available:
# Path: textplusstuff/registry.py
# class Rendition(object):
# class Stuff(object):
# class ModelStuff(Stuff):
# class ListSerializer(ModelSerializer):
# class Meta:
# class StuffRegistry(object):
# class ListStuffGroups(TextPlusStuffAPIViewMixIn, APIView):
# def __init__(self, short_name, verbose_name, description,
# path_to_template, rendition_type='block'):
# def get_context_data(self, **context):
# def render_as_html(self, context):
# def __init__(self, model):
# def _verify_rendition(self, rendition):
# def _verify_rendition_list_uniqueness(self, rendition_list):
# def _verify_and_build_initial_rendition_dict(self):
# def register_non_core_rendition(self, rendition):
# def get_list_serializer(self):
# def list_view(self):
# def detail_view(self):
# def get_url_name_key(self):
# def get_urls(self):
# def __init__(self, name='stuff_registry'):
# def verify_stuff_cls(self, stuff_cls):
# def verify_groups(self, groups, stuff_cls):
# def add_modelstuff(self, model, stuff_cls, groups=[]):
# def add_noncore_modelstuff_rendition(self, model, rendition):
# def remove_modelstuff(self, model):
# def index(self):
# def prepare_stuffgroups(self):
# def get_generated_stuffgroups(self):
# def get(self, request, format=None):
# def get_urls(self):
# def urls(self):
# def get_modelstuff_renditions(model_instance):
#
# Path: tests/models.py
# class RegisteredModel(models.Model):
# """
# A simple model used to test textplusstuff.registry.StuffRegistry
# """
# title = models.CharField(
# max_length=90
# )
#
# class Meta:
# verbose_name = _('Registered Model')
# verbose_name_plural = _('Registered Models')
#
# def __unicode__(self):
# return "registeredmodel:{}".format(self.pk)
#
# Path: tests/serializers.py
# class RegisteredModelSerializer(ExtraContextSerializerMixIn,
# serializers.ModelSerializer):
#
# class Meta:
# model = RegisteredModel
# fields = ('title',)
. Output only the next line. | description='Displays a Test Rendition rendered.', |
Continue the code snippet: <|code_start|>from __future__ import unicode_literals
class RegisteredModelSerializer(ExtraContextSerializerMixIn,
serializers.ModelSerializer):
class Meta:
model = RegisteredModel
<|code_end|>
. Use current file imports:
from rest_framework import serializers
from textplusstuff.serializers import (
ExtraContextSerializerMixIn,
TextPlusStuffFieldSerializer
)
from .models import RegisteredModel, TPSTestModel
and context (classes, functions, or code) from other files:
# Path: textplusstuff/serializers.py
# class ExtraContextSerializerMixIn(object):
# """
# A serializer mixin that conveniently adds the entirety of self.context to
# the 'extra_context' key of `to_representation`.
# """
#
# def to_native(self, instance):
# """For backwards compatibility with djangorestframework 2.X.X"""
# return self.to_representation(instance)
#
# def to_representation(self, instance):
# """
# Add self.context to the 'extra_context' key of a
# serializers output.
# """
# if REST_FRAMEWORK_VERSION.startswith('2.'):
# payload = super(
# ExtraContextSerializerMixIn, self
# ).to_native(instance)
# else:
# payload = super(
# ExtraContextSerializerMixIn, self
# ).to_representation(instance)
# extra_context = copy.copy(self.context) or {}
# extra_context.pop('view', None)
# extra_context.pop('request', None)
# extra_context.pop('format', None)
# payload.update({
# 'extra_context': extra_context
# })
# return payload
#
# class TextPlusStuffFieldSerializer(CharField):
# """
# Return a dictionary of all available permutations of a TextPlusStuffField
#
# Example:
# {
# 'raw_text': <Raw value of the field>,
# 'as_plaintext': <As plaintext, no tokens rendered>,
# 'as_markdown': <As markdown, no tokens rendered>,
# 'as_html': <As HTML markup with tokens rendered>,
# 'as_html_no_tokens': <As HTML markup no tokens rendered>,
# }
# """
#
# read_only = True
#
# def to_native(self, value):
# """For djangorestframework>=2.4.x"""
# return self.to_representation(value)
#
# def to_representation(self, value):
# if not isinstance(value, TextPlusStuff):
# raise ValueError(
# "Only TextPlusStuffFields can be rendered by "
# "the TextPlusStuffFieldSerializer"
# )
# else:
# return {
# 'raw_text': value.raw_text,
# 'as_plaintext': value.as_plaintext(),
# 'as_markdown': value.as_markdown(),
# 'as_html': value.as_html(extra_context=getattr(
# self, 'context', {}
# )),
# 'as_html_no_tokens': value.as_html(
# include_content_nodes=False
# ),
# 'as_json': value.as_json(convert_to_json_string=False)
# }
#
# Path: tests/models.py
# class RegisteredModel(models.Model):
# """
# A simple model used to test textplusstuff.registry.StuffRegistry
# """
# title = models.CharField(
# max_length=90
# )
#
# class Meta:
# verbose_name = _('Registered Model')
# verbose_name_plural = _('Registered Models')
#
# def __unicode__(self):
# return "registeredmodel:{}".format(self.pk)
#
# class TPSTestModel(models.Model):
# content = TextPlusStuffField(
# constructed_field='content_constructed'
# )
# content_constructed = TextPlusStuffConstructedField()
#
# def __unicode__(self):
# return "tpstestmodel:{}".format(self.pk)
. Output only the next line. | fields = ('title',) |
Predict the next line for this snippet: <|code_start|>from __future__ import unicode_literals
class RegisteredModelSerializer(ExtraContextSerializerMixIn,
serializers.ModelSerializer):
class Meta:
model = RegisteredModel
fields = ('title',)
class TPSTestModelSerializer(serializers.ModelSerializer):
content = TextPlusStuffFieldSerializer()
<|code_end|>
with the help of current file imports:
from rest_framework import serializers
from textplusstuff.serializers import (
ExtraContextSerializerMixIn,
TextPlusStuffFieldSerializer
)
from .models import RegisteredModel, TPSTestModel
and context from other files:
# Path: textplusstuff/serializers.py
# class ExtraContextSerializerMixIn(object):
# """
# A serializer mixin that conveniently adds the entirety of self.context to
# the 'extra_context' key of `to_representation`.
# """
#
# def to_native(self, instance):
# """For backwards compatibility with djangorestframework 2.X.X"""
# return self.to_representation(instance)
#
# def to_representation(self, instance):
# """
# Add self.context to the 'extra_context' key of a
# serializers output.
# """
# if REST_FRAMEWORK_VERSION.startswith('2.'):
# payload = super(
# ExtraContextSerializerMixIn, self
# ).to_native(instance)
# else:
# payload = super(
# ExtraContextSerializerMixIn, self
# ).to_representation(instance)
# extra_context = copy.copy(self.context) or {}
# extra_context.pop('view', None)
# extra_context.pop('request', None)
# extra_context.pop('format', None)
# payload.update({
# 'extra_context': extra_context
# })
# return payload
#
# class TextPlusStuffFieldSerializer(CharField):
# """
# Return a dictionary of all available permutations of a TextPlusStuffField
#
# Example:
# {
# 'raw_text': <Raw value of the field>,
# 'as_plaintext': <As plaintext, no tokens rendered>,
# 'as_markdown': <As markdown, no tokens rendered>,
# 'as_html': <As HTML markup with tokens rendered>,
# 'as_html_no_tokens': <As HTML markup no tokens rendered>,
# }
# """
#
# read_only = True
#
# def to_native(self, value):
# """For djangorestframework>=2.4.x"""
# return self.to_representation(value)
#
# def to_representation(self, value):
# if not isinstance(value, TextPlusStuff):
# raise ValueError(
# "Only TextPlusStuffFields can be rendered by "
# "the TextPlusStuffFieldSerializer"
# )
# else:
# return {
# 'raw_text': value.raw_text,
# 'as_plaintext': value.as_plaintext(),
# 'as_markdown': value.as_markdown(),
# 'as_html': value.as_html(extra_context=getattr(
# self, 'context', {}
# )),
# 'as_html_no_tokens': value.as_html(
# include_content_nodes=False
# ),
# 'as_json': value.as_json(convert_to_json_string=False)
# }
#
# Path: tests/models.py
# class RegisteredModel(models.Model):
# """
# A simple model used to test textplusstuff.registry.StuffRegistry
# """
# title = models.CharField(
# max_length=90
# )
#
# class Meta:
# verbose_name = _('Registered Model')
# verbose_name_plural = _('Registered Models')
#
# def __unicode__(self):
# return "registeredmodel:{}".format(self.pk)
#
# class TPSTestModel(models.Model):
# content = TextPlusStuffField(
# constructed_field='content_constructed'
# )
# content_constructed = TextPlusStuffConstructedField()
#
# def __unicode__(self):
# return "tpstestmodel:{}".format(self.pk)
, which may contain function names, class names, or code. Output only the next line. | class Meta: |
Next line prediction: <|code_start|>from __future__ import unicode_literals
class RegisteredModelSerializer(ExtraContextSerializerMixIn,
serializers.ModelSerializer):
class Meta:
model = RegisteredModel
<|code_end|>
. Use current file imports:
(from rest_framework import serializers
from textplusstuff.serializers import (
ExtraContextSerializerMixIn,
TextPlusStuffFieldSerializer
)
from .models import RegisteredModel, TPSTestModel)
and context including class names, function names, or small code snippets from other files:
# Path: textplusstuff/serializers.py
# class ExtraContextSerializerMixIn(object):
# """
# A serializer mixin that conveniently adds the entirety of self.context to
# the 'extra_context' key of `to_representation`.
# """
#
# def to_native(self, instance):
# """For backwards compatibility with djangorestframework 2.X.X"""
# return self.to_representation(instance)
#
# def to_representation(self, instance):
# """
# Add self.context to the 'extra_context' key of a
# serializers output.
# """
# if REST_FRAMEWORK_VERSION.startswith('2.'):
# payload = super(
# ExtraContextSerializerMixIn, self
# ).to_native(instance)
# else:
# payload = super(
# ExtraContextSerializerMixIn, self
# ).to_representation(instance)
# extra_context = copy.copy(self.context) or {}
# extra_context.pop('view', None)
# extra_context.pop('request', None)
# extra_context.pop('format', None)
# payload.update({
# 'extra_context': extra_context
# })
# return payload
#
# class TextPlusStuffFieldSerializer(CharField):
# """
# Return a dictionary of all available permutations of a TextPlusStuffField
#
# Example:
# {
# 'raw_text': <Raw value of the field>,
# 'as_plaintext': <As plaintext, no tokens rendered>,
# 'as_markdown': <As markdown, no tokens rendered>,
# 'as_html': <As HTML markup with tokens rendered>,
# 'as_html_no_tokens': <As HTML markup no tokens rendered>,
# }
# """
#
# read_only = True
#
# def to_native(self, value):
# """For djangorestframework>=2.4.x"""
# return self.to_representation(value)
#
# def to_representation(self, value):
# if not isinstance(value, TextPlusStuff):
# raise ValueError(
# "Only TextPlusStuffFields can be rendered by "
# "the TextPlusStuffFieldSerializer"
# )
# else:
# return {
# 'raw_text': value.raw_text,
# 'as_plaintext': value.as_plaintext(),
# 'as_markdown': value.as_markdown(),
# 'as_html': value.as_html(extra_context=getattr(
# self, 'context', {}
# )),
# 'as_html_no_tokens': value.as_html(
# include_content_nodes=False
# ),
# 'as_json': value.as_json(convert_to_json_string=False)
# }
#
# Path: tests/models.py
# class RegisteredModel(models.Model):
# """
# A simple model used to test textplusstuff.registry.StuffRegistry
# """
# title = models.CharField(
# max_length=90
# )
#
# class Meta:
# verbose_name = _('Registered Model')
# verbose_name_plural = _('Registered Models')
#
# def __unicode__(self):
# return "registeredmodel:{}".format(self.pk)
#
# class TPSTestModel(models.Model):
# content = TextPlusStuffField(
# constructed_field='content_constructed'
# )
# content_constructed = TextPlusStuffConstructedField()
#
# def __unicode__(self):
# return "tpstestmodel:{}".format(self.pk)
. Output only the next line. | fields = ('title',) |
Based on the snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
class SSL(TcpListener):
def __init__(self, host, port, cert, pkey, timeout=0.25):
TcpListener.__init__(self, host, port, timeout)
self.cert = cert
self.pkey = pkey
def accept(self):
print("[*] Waiting for incoming connection")
client, addr = self._listen.accept()
print("[*] Client:", addr[0], addr[1])
print("[*] Wrapping socket to TLS/SSL")
try:
self._socket = ssl.wrap_socket(client,
server_side=True,
certfile=self.cert,
keyfile=self.pkey,
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import ssl
import socket
import tlslite.api
from Peach.Publishers.tcp import TcpListener
from Peach.publisher import PublisherSoftException
from Peach.Engine.common import PeachException
and context (classes, functions, sometimes code) from other files:
# Path: Peach/publisher.py
# class PublisherSoftException(SoftException):
# """
# Recoverable exception occurred in the Publisher.
# """
# pass
#
# Path: Peach/Engine/common.py
# class PeachException(HardException):
# """
# Peach exceptions are specialized hard exceptions.
# The message contained in a PeachException is presentable to the user w/o any stack trace, etc.
# Examples would be:
# "Error: The DataModel element requires a name attribute."
# """
# def __init__(self, msg, module="Unknown"):
# Exception.__init__(self, msg)
# self.module = module
# self.msg = msg
. Output only the next line. | do_handshake_on_connect=False) |
Here is a snippet: <|code_start|> raise PeachException("Unable to open %s" % self.pkey)
self.privateKey = tlslite.api.parsePEMKey(pkey_content, private=True)
def accept(self):
print("[*] Waiting for incoming connection")
sys.stdout.flush()
client, addr = self._listen.accept()
print("[*] Connected by %s:%s" % (addr[0], str(addr[1])))
print("[*] Wrapping socket to TLS/SSL")
try:
self._socket = tlslite.api.TLSConnection(client)
except:
client.close()
value = sys.exc_info()[1]
msg = "[!] Wrapping socket failed, reason: %s" % value
raise PublisherSoftException(msg)
print("[*] Performing TLS/SSL handshake)")
try:
self._socket.handshakeServer(certChain=self.certChain,
privateKey=self.privateKey,
#reqCert=True,
nextProtos=[self.version])
except:
self.close()
value = sys.exc_info()[1]
msg = "[!] Performing TLS/SSL handshake failed, reason: %s" % value
raise PublisherSoftException(msg)
<|code_end|>
. Write the next line using the current file imports:
import sys
import ssl
import socket
import tlslite.api
from Peach.Publishers.tcp import TcpListener
from Peach.publisher import PublisherSoftException
from Peach.Engine.common import PeachException
and context from other files:
# Path: Peach/publisher.py
# class PublisherSoftException(SoftException):
# """
# Recoverable exception occurred in the Publisher.
# """
# pass
#
# Path: Peach/Engine/common.py
# class PeachException(HardException):
# """
# Peach exceptions are specialized hard exceptions.
# The message contained in a PeachException is presentable to the user w/o any stack trace, etc.
# Examples would be:
# "Error: The DataModel element requires a name attribute."
# """
# def __init__(self, msg, module="Unknown"):
# Exception.__init__(self, msg)
# self.module = module
# self.msg = msg
, which may include functions, classes, or code. Output only the next line. | print("done!") |
Predict the next line for this snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
class PhoneNumber(Transformer):
def __init__(self):
Transformer.__init__(self)
def realEncode(self, data):
s = ""
# Add padding F to make length of phone number even
s = s + "F" if len(data) % 2 else s
# Split string in 2 byte segments
segments = [s[i:i + 2] for i in range(0, len(s), 2)]
# Reverse and join back together
<|code_end|>
with the help of current file imports:
from Peach.transformer import Transformer
and context from other files:
# Path: Peach/transformer.py
# class Transformer(object):
# """
# Transformers encode or decode some form of input e.g. Base64 string.
# Chained transformer run after this transformer.
# """
#
# def __init__(self, anotherTransformer=None):
# """Create a Transformer object.
#
# :param anotherTransformer: a transformer to run next
# :type anotherTransformer: Transformer
# """
# self._anotherTransformer = anotherTransformer
#
# def changesSize(self):
# return True
#
# def encode(self, data):
# """Transform data and call next transformer in chain if provided.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# ret = self.realEncode(data)
# if self._anotherTransformer is not None:
# return self._anotherTransformer.encode(ret)
# return ret
#
# def decode(self, data):
# """Perform reverse transformation if possible.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# if self._anotherTransformer is not None:
# data = self._anotherTransformer.decode(data)
# return self.realDecode(data)
#
# def getTransformer(self):
# """Gets the next transformer in the chain.
#
# :returns: next transformer in chain or None
# :rtype: Transformer
# """
# return self._anotherTransformer
#
# def addTransformer(self, transformer):
# """Set the next transformer in the chain.
#
# :param transformer: transformer to set
# :type transformer: Transformer
# :returns: this transformer
# :rtype: Transformer
# """
# self._anotherTransformer = transformer
# return self
#
# def realEncode(self, data):
# """Override this method to implement your transform.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# raise Exception("realEncode(): Transformer does not work both ways.")
#
# def realDecode(self, data):
# """Override this method to implement your transform.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# raise Exception("realDecode(): Transformer does not work both ways.")
, which may contain function names, class names, or code. Output only the next line. | segments = "".join([i[1] + i[0] for i in segments]) |
Given snippet: <|code_start|> err = _zlib.deflateEnd(C.byref(self.st))
class Decompressor(object):
def __init__(self, dictionary=None):
self.dictionary = dictionary
self.st = _z_stream()
err = _zlib.inflateInit2_(C.byref(self.st), 15, ZLIB_VERSION,
C.sizeof(self.st))
assert err == Z_OK, err
def __call__(self, input):
outbuf = C.create_string_buffer(CHUNK)
self.st.avail_in = len(input)
self.st.next_in = C.cast(C.c_char_p(input), C.POINTER(C.c_ubyte))
self.st.avail_out = CHUNK
self.st.next_out = C.cast(outbuf, C.POINTER(C.c_ubyte))
err = _zlib.inflate(C.byref(self.st), Z_SYNC_FLUSH)
if err == Z_NEED_DICT:
assert self.dictionary, "no dictionary provided"
dict_id = _zlib.adler32(0,
C.cast(C.c_char_p(self.dictionary), C.POINTER(C.c_ubyte)),
len(self.dictionary))
err = _zlib.inflateSetDictionary(
C.byref(self.st),
C.cast(C.c_char_p(self.dictionary), C.POINTER(C.c_ubyte)),
len(self.dictionary)
)
assert err == Z_OK, err
err = _zlib.inflate(C.byref(self.st), Z_SYNC_FLUSH)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import ctypes as C
import os
from ctypes import util
from Peach.transformer import Transformer
and context:
# Path: Peach/transformer.py
# class Transformer(object):
# """
# Transformers encode or decode some form of input e.g. Base64 string.
# Chained transformer run after this transformer.
# """
#
# def __init__(self, anotherTransformer=None):
# """Create a Transformer object.
#
# :param anotherTransformer: a transformer to run next
# :type anotherTransformer: Transformer
# """
# self._anotherTransformer = anotherTransformer
#
# def changesSize(self):
# return True
#
# def encode(self, data):
# """Transform data and call next transformer in chain if provided.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# ret = self.realEncode(data)
# if self._anotherTransformer is not None:
# return self._anotherTransformer.encode(ret)
# return ret
#
# def decode(self, data):
# """Perform reverse transformation if possible.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# if self._anotherTransformer is not None:
# data = self._anotherTransformer.decode(data)
# return self.realDecode(data)
#
# def getTransformer(self):
# """Gets the next transformer in the chain.
#
# :returns: next transformer in chain or None
# :rtype: Transformer
# """
# return self._anotherTransformer
#
# def addTransformer(self, transformer):
# """Set the next transformer in the chain.
#
# :param transformer: transformer to set
# :type transformer: Transformer
# :returns: this transformer
# :rtype: Transformer
# """
# self._anotherTransformer = transformer
# return self
#
# def realEncode(self, data):
# """Override this method to implement your transform.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# raise Exception("realEncode(): Transformer does not work both ways.")
#
# def realDecode(self, data):
# """Override this method to implement your transform.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# raise Exception("realDecode(): Transformer does not work both ways.")
which might include code, classes, or functions. Output only the next line. | if err in [Z_OK, Z_STREAM_END]: |
Here is a snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
usingLightBlue = False
usingBluetooth = False
if sys.platform == "darwin":
try:
# Do not relay too much on this Publisher when using Lightblue,
# this library is unmaintained since 2009 but there is no other
# Python alternative for MacOS except PyObjC IOBluetooth Bridge.
except ImportError:
sys.exit("Lightblue is not installed.")
else:
print("[*] Library: Lightblue (%s)" % sys.platform)
usingLightBlue = True
elif sys.platform == "linux2":
try:
except ImportError:
sys.exit("PyBluez is not installed.")
else:
<|code_end|>
. Write the next line using the current file imports:
import sys
import time
import socket
import lightblue
import bluetooth
from Peach.publisher import Publisher
from Peach.Engine.common import PeachException
from Peach.Utilities.common import *
and context from other files:
# Path: Peach/publisher.py
# class Publisher(object):
# """
# The Publisher object(s) implement a way to send and/or receive data by
# some means. There are two "types" of publishers, stream based and call
# based. This base class supports both types.
# To support stream based publishing implement everything but "call". To
# support call based publishing implement start, stop, and call. A
# publisher can support both stream and call based publishing.
# """
#
# def __init__(self):
# #: Indicates which method should be called.
# self.withNode = False
# self.publisherBuffer = None
#
# def initialize(self):
# """
# Called at start of test run. Called once per <Test> section.
# """
# pass
#
# def finalize(self):
# """
# Called at end of test run. Called once per <Test> section.
# """
# pass
#
# def start(self):
# """
# Change state such that send/receive will work. For TCP this could be
# connecting to a remote host.
# """
# pass
#
# def stop(self):
# """
# Change state such that send/receive will not work. For TCP this could
# be closing a connection, for a file it might be closing the file
# handle.
# """
# pass
#
# def send(self, data):
# """
# Publish some data.
#
# :param data: data to publish
# :type data: str
# """
# raise PeachException("Action 'send' not supported by publisher.")
#
# def sendWithNode(self, data, dataNode):
# """
# Publish some data.
#
# :param data: data to publish
# :type data: str
# :param dataNode: root of data model that produced data
# :type dataNode: DataElement
# """
# raise PeachException("Action 'sendWithNode' not supported by "
# "publisher.")
#
# def receive(self, size=None):
# """
# Receive some data.
#
# :param size: number of bytes to return
# :type size: int
# :returns: data received
# :rtype: str
# """
# raise PeachException("Action 'receive' not supported by publisher.")
#
# def call(self, method, args):
# """
# Call a method using arguments.
#
# :param method: method to call
# :type method: str
# :param args: list of strings as arguments
# :type args: list
# :returns: data (if any)
# :rtype: str
# """
# raise PeachException("Action 'call' not supported by publisher.")
#
# def callWithNode(self, method, args, argNodes):
# """
# Call a method using arguments.
#
# :param method: method to call
# :type method: str
# :param args: list of strings as arguments
# :type args: list
# :param argNodes: list of DataElements
# :type argNodes: list
# :returns: data (if any)
# :rtype: str
# """
# raise PeachException("Action 'callWithNode' not supported by publisher.")
#
# def property(self, property, value=None):
# """
# Get or set property.
#
# :param property: name of method to invoke
# :type property: str
# :param value: value to set. If None, return property instead
# :type value: object
# """
# raise PeachException("Action 'property' not supported by publisher.")
#
# def propertyWithNode(self, property, value, valueNode):
# """
# Get or set property.
#
# :param property: name of method to invoke
# :type property: str
# :param value: value to set. If None, return property instead
# :type value: object
# :param valueNode: data model root node that produced value
# :type valueNode: DataElement
# """
# raise PeachException("Action 'propertyWithNode' not supported by publisher.")
#
# def connect(self):
# """
# Called to connect or open a connection / file.
# """
# raise PeachException("Action 'connect' not supported by publisher.")
#
# def accept(self):
# """
# Accept incoming connection. Blocks until incoming connection occurs.
# """
# raise PeachException("Action 'accept' not supported by publisher.")
#
# def close(self):
# """
# Close current stream/connection.
# """
# raise PeachException("Action 'close' not supported by publisher.")
#
# def debug(self, fmt):
# print("{}: {}".format(self.__class__.__name__, fmt))
#
# Path: Peach/Engine/common.py
# class PeachException(HardException):
# """
# Peach exceptions are specialized hard exceptions.
# The message contained in a PeachException is presentable to the user w/o any stack trace, etc.
# Examples would be:
# "Error: The DataModel element requires a name attribute."
# """
# def __init__(self, msg, module="Unknown"):
# Exception.__init__(self, msg)
# self.module = module
# self.msg = msg
, which may include functions, classes, or code. Output only the next line. | print("[*] Library: PyBluez (%s)" % sys.platform) |
Given snippet: <|code_start|> return services
def lightblue_server_test():
# L2CAP server sockets not currently supported :(
s = lightblue.socket(lightblue.L2CAP)
s.bind(("", 0x1001))
s.listen(1)
lightblue.advertise("Peach", s, lightblue.L2CAP)
conn, addr = s.accept()
print("Connected by", addr)
data = conn.recv(1024)
print("Received: %s" % data)
conn.close()
s.close()
def pybluez_server_test():
s = bluetooth.BluetoothSocket(bluetooth.L2CAP)
s.bind(("", 0x1001))
s.listen(1)
conn, addr = s.accept()
print("Connected by %s" % addr)
data = s.recv(1024)
print("Received: %s" % data)
conn.close()
s.close()
class L2CAP_Client(Publisher):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import time
import socket
import lightblue
import bluetooth
from Peach.publisher import Publisher
from Peach.Engine.common import PeachException
from Peach.Utilities.common import *
and context:
# Path: Peach/publisher.py
# class Publisher(object):
# """
# The Publisher object(s) implement a way to send and/or receive data by
# some means. There are two "types" of publishers, stream based and call
# based. This base class supports both types.
# To support stream based publishing implement everything but "call". To
# support call based publishing implement start, stop, and call. A
# publisher can support both stream and call based publishing.
# """
#
# def __init__(self):
# #: Indicates which method should be called.
# self.withNode = False
# self.publisherBuffer = None
#
# def initialize(self):
# """
# Called at start of test run. Called once per <Test> section.
# """
# pass
#
# def finalize(self):
# """
# Called at end of test run. Called once per <Test> section.
# """
# pass
#
# def start(self):
# """
# Change state such that send/receive will work. For TCP this could be
# connecting to a remote host.
# """
# pass
#
# def stop(self):
# """
# Change state such that send/receive will not work. For TCP this could
# be closing a connection, for a file it might be closing the file
# handle.
# """
# pass
#
# def send(self, data):
# """
# Publish some data.
#
# :param data: data to publish
# :type data: str
# """
# raise PeachException("Action 'send' not supported by publisher.")
#
# def sendWithNode(self, data, dataNode):
# """
# Publish some data.
#
# :param data: data to publish
# :type data: str
# :param dataNode: root of data model that produced data
# :type dataNode: DataElement
# """
# raise PeachException("Action 'sendWithNode' not supported by "
# "publisher.")
#
# def receive(self, size=None):
# """
# Receive some data.
#
# :param size: number of bytes to return
# :type size: int
# :returns: data received
# :rtype: str
# """
# raise PeachException("Action 'receive' not supported by publisher.")
#
# def call(self, method, args):
# """
# Call a method using arguments.
#
# :param method: method to call
# :type method: str
# :param args: list of strings as arguments
# :type args: list
# :returns: data (if any)
# :rtype: str
# """
# raise PeachException("Action 'call' not supported by publisher.")
#
# def callWithNode(self, method, args, argNodes):
# """
# Call a method using arguments.
#
# :param method: method to call
# :type method: str
# :param args: list of strings as arguments
# :type args: list
# :param argNodes: list of DataElements
# :type argNodes: list
# :returns: data (if any)
# :rtype: str
# """
# raise PeachException("Action 'callWithNode' not supported by publisher.")
#
# def property(self, property, value=None):
# """
# Get or set property.
#
# :param property: name of method to invoke
# :type property: str
# :param value: value to set. If None, return property instead
# :type value: object
# """
# raise PeachException("Action 'property' not supported by publisher.")
#
# def propertyWithNode(self, property, value, valueNode):
# """
# Get or set property.
#
# :param property: name of method to invoke
# :type property: str
# :param value: value to set. If None, return property instead
# :type value: object
# :param valueNode: data model root node that produced value
# :type valueNode: DataElement
# """
# raise PeachException("Action 'propertyWithNode' not supported by publisher.")
#
# def connect(self):
# """
# Called to connect or open a connection / file.
# """
# raise PeachException("Action 'connect' not supported by publisher.")
#
# def accept(self):
# """
# Accept incoming connection. Blocks until incoming connection occurs.
# """
# raise PeachException("Action 'accept' not supported by publisher.")
#
# def close(self):
# """
# Close current stream/connection.
# """
# raise PeachException("Action 'close' not supported by publisher.")
#
# def debug(self, fmt):
# print("{}: {}".format(self.__class__.__name__, fmt))
#
# Path: Peach/Engine/common.py
# class PeachException(HardException):
# """
# Peach exceptions are specialized hard exceptions.
# The message contained in a PeachException is presentable to the user w/o any stack trace, etc.
# Examples would be:
# "Error: The DataModel element requires a name attribute."
# """
# def __init__(self, msg, module="Unknown"):
# Exception.__init__(self, msg)
# self.module = module
# self.msg = msg
which might include code, classes, or functions. Output only the next line. | def __init__(self, ba_addr, port, timeout=8.0, giveup=3.0): |
Next line prediction: <|code_start|>
def start(self):
if self._connected:
return
print("[*] Connecting to %s:%d ..." % (self.host, self.port))
try:
self.smtp = smtplib.SMTP(self.host, self.port)
except:
raise PeachException("Peer %s:%d is down or connection settings are wrong." % (self.host, self.port))
self._connected = True
self.smtp.set_debuglevel(self.debugLevel)
def connect(self):
pass
def send(self, data):
if not self.loadBalance % 500 and self.loadBalance != 0:
print("[*] Pause ...")
time.sleep(10)
for i in range(3):
try:
self.smtp.sendmail(self.mailFrom, self.mailTo, data)
exception = None
break
except:
exception = sys.exc_info()
time.sleep(5)
if exception:
reason = ""
<|code_end|>
. Use current file imports:
(import time
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import Encoders
from email.Utils import COMMASPACE, formatdate
from Peach.publisher import Publisher
from Peach.Engine.common import PeachException)
and context including class names, function names, or small code snippets from other files:
# Path: Peach/publisher.py
# class Publisher(object):
# """
# The Publisher object(s) implement a way to send and/or receive data by
# some means. There are two "types" of publishers, stream based and call
# based. This base class supports both types.
# To support stream based publishing implement everything but "call". To
# support call based publishing implement start, stop, and call. A
# publisher can support both stream and call based publishing.
# """
#
# def __init__(self):
# #: Indicates which method should be called.
# self.withNode = False
# self.publisherBuffer = None
#
# def initialize(self):
# """
# Called at start of test run. Called once per <Test> section.
# """
# pass
#
# def finalize(self):
# """
# Called at end of test run. Called once per <Test> section.
# """
# pass
#
# def start(self):
# """
# Change state such that send/receive will work. For TCP this could be
# connecting to a remote host.
# """
# pass
#
# def stop(self):
# """
# Change state such that send/receive will not work. For TCP this could
# be closing a connection, for a file it might be closing the file
# handle.
# """
# pass
#
# def send(self, data):
# """
# Publish some data.
#
# :param data: data to publish
# :type data: str
# """
# raise PeachException("Action 'send' not supported by publisher.")
#
# def sendWithNode(self, data, dataNode):
# """
# Publish some data.
#
# :param data: data to publish
# :type data: str
# :param dataNode: root of data model that produced data
# :type dataNode: DataElement
# """
# raise PeachException("Action 'sendWithNode' not supported by "
# "publisher.")
#
# def receive(self, size=None):
# """
# Receive some data.
#
# :param size: number of bytes to return
# :type size: int
# :returns: data received
# :rtype: str
# """
# raise PeachException("Action 'receive' not supported by publisher.")
#
# def call(self, method, args):
# """
# Call a method using arguments.
#
# :param method: method to call
# :type method: str
# :param args: list of strings as arguments
# :type args: list
# :returns: data (if any)
# :rtype: str
# """
# raise PeachException("Action 'call' not supported by publisher.")
#
# def callWithNode(self, method, args, argNodes):
# """
# Call a method using arguments.
#
# :param method: method to call
# :type method: str
# :param args: list of strings as arguments
# :type args: list
# :param argNodes: list of DataElements
# :type argNodes: list
# :returns: data (if any)
# :rtype: str
# """
# raise PeachException("Action 'callWithNode' not supported by publisher.")
#
# def property(self, property, value=None):
# """
# Get or set property.
#
# :param property: name of method to invoke
# :type property: str
# :param value: value to set. If None, return property instead
# :type value: object
# """
# raise PeachException("Action 'property' not supported by publisher.")
#
# def propertyWithNode(self, property, value, valueNode):
# """
# Get or set property.
#
# :param property: name of method to invoke
# :type property: str
# :param value: value to set. If None, return property instead
# :type value: object
# :param valueNode: data model root node that produced value
# :type valueNode: DataElement
# """
# raise PeachException("Action 'propertyWithNode' not supported by publisher.")
#
# def connect(self):
# """
# Called to connect or open a connection / file.
# """
# raise PeachException("Action 'connect' not supported by publisher.")
#
# def accept(self):
# """
# Accept incoming connection. Blocks until incoming connection occurs.
# """
# raise PeachException("Action 'accept' not supported by publisher.")
#
# def close(self):
# """
# Close current stream/connection.
# """
# raise PeachException("Action 'close' not supported by publisher.")
#
# def debug(self, fmt):
# print("{}: {}".format(self.__class__.__name__, fmt))
#
# Path: Peach/Engine/common.py
# class PeachException(HardException):
# """
# Peach exceptions are specialized hard exceptions.
# The message contained in a PeachException is presentable to the user w/o any stack trace, etc.
# Examples would be:
# "Error: The DataModel element requires a name attribute."
# """
# def __init__(self, msg, module="Unknown"):
# Exception.__init__(self, msg)
# self.module = module
# self.msg = msg
. Output only the next line. | try: |
Predict the next line after this snippet: <|code_start|> except:
raise PeachException("The SMTP publisher parameter for port is not a valid number.")
self.debugLevel = int(debugLevel)
self.mailFrom = mailFrom
self.mailTo = mailTo
self.username = username
self.password = password
self.loadBalance = 0
self._connected = None
def start(self):
if self._connected:
return
print("[*] Connecting to %s:%d ..." % (self.host, self.port))
try:
self.smtp = smtplib.SMTP(self.host, self.port)
except:
raise PeachException("Peer %s:%d is down or connection settings are wrong." % (self.host, self.port))
self._connected = True
self.smtp.set_debuglevel(self.debugLevel)
def connect(self):
pass
def send(self, data):
if not self.loadBalance % 500 and self.loadBalance != 0:
print("[*] Pause ...")
time.sleep(10)
for i in range(3):
<|code_end|>
using the current file's imports:
import time
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import Encoders
from email.Utils import COMMASPACE, formatdate
from Peach.publisher import Publisher
from Peach.Engine.common import PeachException
and any relevant context from other files:
# Path: Peach/publisher.py
# class Publisher(object):
# """
# The Publisher object(s) implement a way to send and/or receive data by
# some means. There are two "types" of publishers, stream based and call
# based. This base class supports both types.
# To support stream based publishing implement everything but "call". To
# support call based publishing implement start, stop, and call. A
# publisher can support both stream and call based publishing.
# """
#
# def __init__(self):
# #: Indicates which method should be called.
# self.withNode = False
# self.publisherBuffer = None
#
# def initialize(self):
# """
# Called at start of test run. Called once per <Test> section.
# """
# pass
#
# def finalize(self):
# """
# Called at end of test run. Called once per <Test> section.
# """
# pass
#
# def start(self):
# """
# Change state such that send/receive will work. For TCP this could be
# connecting to a remote host.
# """
# pass
#
# def stop(self):
# """
# Change state such that send/receive will not work. For TCP this could
# be closing a connection, for a file it might be closing the file
# handle.
# """
# pass
#
# def send(self, data):
# """
# Publish some data.
#
# :param data: data to publish
# :type data: str
# """
# raise PeachException("Action 'send' not supported by publisher.")
#
# def sendWithNode(self, data, dataNode):
# """
# Publish some data.
#
# :param data: data to publish
# :type data: str
# :param dataNode: root of data model that produced data
# :type dataNode: DataElement
# """
# raise PeachException("Action 'sendWithNode' not supported by "
# "publisher.")
#
# def receive(self, size=None):
# """
# Receive some data.
#
# :param size: number of bytes to return
# :type size: int
# :returns: data received
# :rtype: str
# """
# raise PeachException("Action 'receive' not supported by publisher.")
#
# def call(self, method, args):
# """
# Call a method using arguments.
#
# :param method: method to call
# :type method: str
# :param args: list of strings as arguments
# :type args: list
# :returns: data (if any)
# :rtype: str
# """
# raise PeachException("Action 'call' not supported by publisher.")
#
# def callWithNode(self, method, args, argNodes):
# """
# Call a method using arguments.
#
# :param method: method to call
# :type method: str
# :param args: list of strings as arguments
# :type args: list
# :param argNodes: list of DataElements
# :type argNodes: list
# :returns: data (if any)
# :rtype: str
# """
# raise PeachException("Action 'callWithNode' not supported by publisher.")
#
# def property(self, property, value=None):
# """
# Get or set property.
#
# :param property: name of method to invoke
# :type property: str
# :param value: value to set. If None, return property instead
# :type value: object
# """
# raise PeachException("Action 'property' not supported by publisher.")
#
# def propertyWithNode(self, property, value, valueNode):
# """
# Get or set property.
#
# :param property: name of method to invoke
# :type property: str
# :param value: value to set. If None, return property instead
# :type value: object
# :param valueNode: data model root node that produced value
# :type valueNode: DataElement
# """
# raise PeachException("Action 'propertyWithNode' not supported by publisher.")
#
# def connect(self):
# """
# Called to connect or open a connection / file.
# """
# raise PeachException("Action 'connect' not supported by publisher.")
#
# def accept(self):
# """
# Accept incoming connection. Blocks until incoming connection occurs.
# """
# raise PeachException("Action 'accept' not supported by publisher.")
#
# def close(self):
# """
# Close current stream/connection.
# """
# raise PeachException("Action 'close' not supported by publisher.")
#
# def debug(self, fmt):
# print("{}: {}".format(self.__class__.__name__, fmt))
#
# Path: Peach/Engine/common.py
# class PeachException(HardException):
# """
# Peach exceptions are specialized hard exceptions.
# The message contained in a PeachException is presentable to the user w/o any stack trace, etc.
# Examples would be:
# "Error: The DataModel element requires a name attribute."
# """
# def __init__(self, msg, module="Unknown"):
# Exception.__init__(self, msg)
# self.module = module
# self.msg = msg
. Output only the next line. | try: |
Given the following code snippet before the placeholder: <|code_start|> 8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1,
)
# S-boxes.
S = (
(
14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13
),
(
15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9
),
(
10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12
),
(
7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
<|code_end|>
, predict the next line using imports from the current file:
from Peach.transformer import Transformer
and context including class names, function names, and sometimes code from other files:
# Path: Peach/transformer.py
# class Transformer(object):
# """
# Transformers encode or decode some form of input e.g. Base64 string.
# Chained transformer run after this transformer.
# """
#
# def __init__(self, anotherTransformer=None):
# """Create a Transformer object.
#
# :param anotherTransformer: a transformer to run next
# :type anotherTransformer: Transformer
# """
# self._anotherTransformer = anotherTransformer
#
# def changesSize(self):
# return True
#
# def encode(self, data):
# """Transform data and call next transformer in chain if provided.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# ret = self.realEncode(data)
# if self._anotherTransformer is not None:
# return self._anotherTransformer.encode(ret)
# return ret
#
# def decode(self, data):
# """Perform reverse transformation if possible.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# if self._anotherTransformer is not None:
# data = self._anotherTransformer.decode(data)
# return self.realDecode(data)
#
# def getTransformer(self):
# """Gets the next transformer in the chain.
#
# :returns: next transformer in chain or None
# :rtype: Transformer
# """
# return self._anotherTransformer
#
# def addTransformer(self, transformer):
# """Set the next transformer in the chain.
#
# :param transformer: transformer to set
# :type transformer: Transformer
# :returns: this transformer
# :rtype: Transformer
# """
# self._anotherTransformer = transformer
# return self
#
# def realEncode(self, data):
# """Override this method to implement your transform.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# raise Exception("realEncode(): Transformer does not work both ways.")
#
# def realDecode(self, data):
# """Override this method to implement your transform.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# raise Exception("realDecode(): Transformer does not work both ways.")
. Output only the next line. | 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, |
Given the code snippet: <|code_start|> '-CreateProfile', self.profile_name],
stderr=subprocess.STDOUT)
output = output.strip()
if "Success: created profile" not in output:
raise Exception("Unexpected output while creating Firefox profile: %s" % output)
self.profile_prefs_path = re.findall("'.+?'", output)[1].strip("'")
pref_path = config['DefaultFirefoxPrefs']
logging.debug(self.profile_prefs_path)
shutil.copyfile(pref_path, self.profile_prefs_path)
logging.debug("Successfully created temporary Firefox profile at %s" % self.profile_prefs_path)
@staticmethod
def getInstanceById(identifier, config):
if identifier not in FirefoxProfile.instances:
FirefoxProfile.instances[identifier] = FirefoxProfile(identifier, config)
return FirefoxProfile.instances[identifier]
@staticmethod
@atexit.register
def cleanInstances():
for instance in FirefoxProfile.instances.values():
instance.destroy()
def __repr__(self):
return self.profile_name
def destroy(self):
if self.profile_prefs_path.endswith('/prefs.js'):
profile_path = os.path.dirname(self.profile_prefs_path)
logging.debug("Deleting temporary Firefox profile at %s" % profile_path)
<|code_end|>
, generate the next line using the imports in this file:
import os
import uuid
import subprocess
import re
import atexit
import shutil
import logging
import shlex
from Peach.Utilities import network
and context (functions, classes, or occasionally code) from other files:
# Path: Peach/Utilities/network.py
# def cleanupSocketProcesses():
# def getUnboundPort(host="", minRange=30000, maxRange=35000, socket_type=1, assignOnlyOnce=False):
# def runHTTPDThread():
. Output only the next line. | shutil.rmtree(profile_path) |
Given snippet: <|code_start|> self.unitsep = unitsep
def fixup(self):
values = string.split(self.values, self.listsep)
if values is None:
raise Exception("Error: LogicalField was unable to locate its "
"values.")
rndIndex = random.randint(0, len(values) - 1)
rndValue = string.split(values[rndIndex], self.unitsep)
if rndValue[0] == "String":
return TranslateHexDigits(rndValue[1])
if rndValue[0] == "Number":
return int(rndValue[1], 16)
return TranslateHexDigits(rndValue[1])
class RandomField(Fixup):
def __init__(self, minlen, maxlen, fieldtype):
Fixup.__init__(self)
self.minlen = minlen
self.maxlen = maxlen
self.fieldtype = fieldtype
def fixup(self):
minlen = self.minlen
maxlen = self.maxlen
if minlen is None:
raise Exception("Error: RandomField was unable to locate minlen.")
if maxlen is None:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
import string
import re
import time
from Peach.fixup import Fixup
and context:
# Path: Peach/fixup.py
# class Fixup(object):
# """
# Fixup of values in the data model. This is done by keeping an internal
# list of references that can be resolved during fixup(). Helper functions
# are provided in this base class for resolving elements in the data model.
# """
#
# def __init__(self):
# self.context = None
# self.is_in_self = False
#
# def do_fixup(self):
# """Wrapper around fixup() to prevent endless recursion."""
# if not self.is_in_self:
# try:
# self.is_in_self = True
# return self.fixup()
# finally:
# self.is_in_self = False
#
# def _getRef(self):
# """
# After incoming data is cracked some elements move around. Peach will
# auto update parameters called "ref" but you will need to re-fetch the
# value using this method.
# """
# for param in self.context.fixup:
# if param.name == "ref":
# return eval(param.defaultValue)
#
# def fixup(self):
# """Performs the required fixup."""
# raise Exception("Fixup not implemented yet!")
which might include code, classes, or functions. Output only the next line. | raise Exception("Error: RandomField was unable to locate maxlen.") |
Based on the snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
try:
class _DbgEventHandler(PyDbgEng.IDebugOutputCallbacksSink, PyDbgEng.IDebugEventCallbacksSink):
buff = ''
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import gc
import re
import sys
import time
import struct
import signal
import pickle
import tempfile
import psutil
import comtypes
import PyDbgEng
import win32serviceutil
import win32service
import win32api, win32con, win32process, win32pdh
import vtrace, envi
import threading
from Peach.agent import Monitor
from ctypes import *
from comtypes import HRESULT, COMError
from comtypes.client import CreateObject, GetEvents, PumpEvents
from comtypes.hresult import S_OK, E_FAIL, E_UNEXPECTED, E_INVALIDARG
from comtypes.automation import IID
from comtypes.gen import DbgEng
from multiprocessing import *
and context (classes, functions, sometimes code) from other files:
# Path: Peach/agent.py
# class Monitor(object):
# """
# Extend from this to implement a Monitor.
# Monitors are run by an Agent and must operate in an async manner.
# Any blocking tasks must be performed in another thread.
#
# Agent: onTestStarting()
# Agent: onTestFinished()
# Agent: redoTest()
# Agent: Sending redoTest result [False]
# Agent: detectFault()
# Agent: Detected fault!
# Agent: Sending detectFault result [True]
# Agent: getMonitorData()
# Agent: onFault()
# Agent: stopRun()
# Agent: onShutdown()
# """
#
# def __init__(self, args):
# """
# Arguments are supplied via the Peach XML file.
#
# @type args: Dictionary
# @param args: Dictionary of parameters
# """
# self._name = None
#
# def OnTestStarting(self):
# """Called right before start of test case or variation."""
# pass
#
# def OnTestFinished(self):
# """Called right after a test case or variation."""
# pass
#
# def GetMonitorData(self):
# """Get any monitored data from a test case."""
# return None
#
# def RedoTest(self):
# """Should the current test be re-performed."""
# return False
#
# def DetectedFault(self):
# """Check if a fault was detected."""
# return False
#
# def OnFault(self):
# """Called when a fault was detected."""
# pass
#
# def OnShutdown(self):
# """Called when Agent is shutting down, typically at end of a test run or when a Stop-Run occurs."""
# pass
#
# def StopRun(self):
# """Return True to force test run to fail. This should return True if an unrecoverable error occurs."""
# return False
#
# def PublisherCall(self, method):
# """Called when a call action is being performed.
# Call actions are used to launch programs, this gives the monitor a chance to determine if it should be
# running the program under a debugger instead. Note: This is a bit of a hack to get this working.
# """
# pass
. Output only the next line. | TakeStackTrace = True |
Based on the snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
sys.path.append("..")
sys.path.append("../..")
g_socketData = None
g_faultDetected = False
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import time
import socket
from Peach.agent import Monitor
from twisted.internet import reactor, protocol
from threading import Thread
and context (classes, functions, sometimes code) from other files:
# Path: Peach/agent.py
# class Monitor(object):
# """
# Extend from this to implement a Monitor.
# Monitors are run by an Agent and must operate in an async manner.
# Any blocking tasks must be performed in another thread.
#
# Agent: onTestStarting()
# Agent: onTestFinished()
# Agent: redoTest()
# Agent: Sending redoTest result [False]
# Agent: detectFault()
# Agent: Detected fault!
# Agent: Sending detectFault result [True]
# Agent: getMonitorData()
# Agent: onFault()
# Agent: stopRun()
# Agent: onShutdown()
# """
#
# def __init__(self, args):
# """
# Arguments are supplied via the Peach XML file.
#
# @type args: Dictionary
# @param args: Dictionary of parameters
# """
# self._name = None
#
# def OnTestStarting(self):
# """Called right before start of test case or variation."""
# pass
#
# def OnTestFinished(self):
# """Called right after a test case or variation."""
# pass
#
# def GetMonitorData(self):
# """Get any monitored data from a test case."""
# return None
#
# def RedoTest(self):
# """Should the current test be re-performed."""
# return False
#
# def DetectedFault(self):
# """Check if a fault was detected."""
# return False
#
# def OnFault(self):
# """Called when a fault was detected."""
# pass
#
# def OnShutdown(self):
# """Called when Agent is shutting down, typically at end of a test run or when a Stop-Run occurs."""
# pass
#
# def StopRun(self):
# """Return True to force test run to fail. This should return True if an unrecoverable error occurs."""
# return False
#
# def PublisherCall(self, method):
# """Called when a call action is being performed.
# Call actions are used to launch programs, this gives the monitor a chance to determine if it should be
# running the program under a debugger instead. Note: This is a bit of a hack to get this working.
# """
# pass
. Output only the next line. | g_stopReactor = False |
Using the snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
class Data7Bit(Transformer):
def __init__(self):
Transformer.__init__(self)
def realEncode(self, data):
result = []
count = 0
last = 0
for c in data:
<|code_end|>
, determine the next line of code. You have imports:
from Peach.transformer import Transformer
and context (class names, function names, or code) available:
# Path: Peach/transformer.py
# class Transformer(object):
# """
# Transformers encode or decode some form of input e.g. Base64 string.
# Chained transformer run after this transformer.
# """
#
# def __init__(self, anotherTransformer=None):
# """Create a Transformer object.
#
# :param anotherTransformer: a transformer to run next
# :type anotherTransformer: Transformer
# """
# self._anotherTransformer = anotherTransformer
#
# def changesSize(self):
# return True
#
# def encode(self, data):
# """Transform data and call next transformer in chain if provided.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# ret = self.realEncode(data)
# if self._anotherTransformer is not None:
# return self._anotherTransformer.encode(ret)
# return ret
#
# def decode(self, data):
# """Perform reverse transformation if possible.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# if self._anotherTransformer is not None:
# data = self._anotherTransformer.decode(data)
# return self.realDecode(data)
#
# def getTransformer(self):
# """Gets the next transformer in the chain.
#
# :returns: next transformer in chain or None
# :rtype: Transformer
# """
# return self._anotherTransformer
#
# def addTransformer(self, transformer):
# """Set the next transformer in the chain.
#
# :param transformer: transformer to set
# :type transformer: Transformer
# :returns: this transformer
# :rtype: Transformer
# """
# self._anotherTransformer = transformer
# return self
#
# def realEncode(self, data):
# """Override this method to implement your transform.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# raise Exception("realEncode(): Transformer does not work both ways.")
#
# def realDecode(self, data):
# """Override this method to implement your transform.
#
# :param data: data to transform
# :type data: str
# :returns: transformed data
# :rtype: str
# """
# raise Exception("realDecode(): Transformer does not work both ways.")
. Output only the next line. | this = ord(c) << (8 - count) |
Based on the snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
try:
except ImportError:
try:
# Todo: Test monitors on Windows and check Python 3 compatibility with PyWin32
# Todo: Find out which methods are used from this import and do it the right way.
except:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import sys
import time
import json
import shlex
import signal
import threading
import Queue
import queue
import win32con
import win32api
import win32serviceutil
from subprocess import Popen, STDOUT, PIPE, check_output
from win32process import *
from Peach.agent import Monitor, MonitorDebug
from Peach.Engine.common import PeachException
from Peach.Utilities.common import *
and context (classes, functions, sometimes code) from other files:
# Path: Peach/agent.py
# class Monitor(object):
# """
# Extend from this to implement a Monitor.
# Monitors are run by an Agent and must operate in an async manner.
# Any blocking tasks must be performed in another thread.
#
# Agent: onTestStarting()
# Agent: onTestFinished()
# Agent: redoTest()
# Agent: Sending redoTest result [False]
# Agent: detectFault()
# Agent: Detected fault!
# Agent: Sending detectFault result [True]
# Agent: getMonitorData()
# Agent: onFault()
# Agent: stopRun()
# Agent: onShutdown()
# """
#
# def __init__(self, args):
# """
# Arguments are supplied via the Peach XML file.
#
# @type args: Dictionary
# @param args: Dictionary of parameters
# """
# self._name = None
#
# def OnTestStarting(self):
# """Called right before start of test case or variation."""
# pass
#
# def OnTestFinished(self):
# """Called right after a test case or variation."""
# pass
#
# def GetMonitorData(self):
# """Get any monitored data from a test case."""
# return None
#
# def RedoTest(self):
# """Should the current test be re-performed."""
# return False
#
# def DetectedFault(self):
# """Check if a fault was detected."""
# return False
#
# def OnFault(self):
# """Called when a fault was detected."""
# pass
#
# def OnShutdown(self):
# """Called when Agent is shutting down, typically at end of a test run or when a Stop-Run occurs."""
# pass
#
# def StopRun(self):
# """Return True to force test run to fail. This should return True if an unrecoverable error occurs."""
# return False
#
# def PublisherCall(self, method):
# """Called when a call action is being performed.
# Call actions are used to launch programs, this gives the monitor a chance to determine if it should be
# running the program under a debugger instead. Note: This is a bit of a hack to get this working.
# """
# pass
#
# def MonitorDebug(monitor, msg):
# print("Monitor[%s]: %s" % (monitor, highlight.info(msg)))
#
# Path: Peach/Engine/common.py
# class PeachException(HardException):
# """
# Peach exceptions are specialized hard exceptions.
# The message contained in a PeachException is presentable to the user w/o any stack trace, etc.
# Examples would be:
# "Error: The DataModel element requires a name attribute."
# """
# def __init__(self, msg, module="Unknown"):
# Exception.__init__(self, msg)
# self.module = module
# self.msg = msg
. Output only the next line. | if sys.platform == 'win32': |
Predict the next line after this snippet: <|code_start|> assert files.lower_extension('FOO') == 'FOO'
assert files.lower_extension('archive.tar.gz') == 'archive.tar.gz'
assert files.lower_extension('ARCHIVE.TAR.GZ') == 'ARCHIVE.TAR.gz'
assert files.lower_extension('audio.m4a') == 'audio.m4a'
assert files.lower_extension('AUDIO.M4A') == 'AUDIO.m4a'
def test_all():
assert 'txt' in files.ALL
assert 'exe' in files.ALL
assert 'any' in files.ALL
def test_none():
assert 'txt' not in files.NONE
assert 'exe' not in files.NONE
assert 'any' not in files.NONE
def test_all_except():
all_except = files.AllExcept('exe')
assert 'csv' in all_except
assert 'exe' not in all_except
def test_mime_known_type():
assert files.mime('test.txt') == 'text/plain'
assert files.mime('test.csv') == 'text/csv'
<|code_end|>
using the current file's imports:
from flask_fs import files
and any relevant context from other files:
# Path: flask_fs/files.py
# TEXT = ['txt']
# DOCUMENTS = 'rtf odf ods gnumeric abw doc docx xls xlsx'.split()
# IMAGES = 'jpg jpe jpeg png gif svg bmp'.split()
# AUDIO = 'wav mp3 aac ogg oga flac'.split()
# DATA = 'csv ini json plist xml yaml yml'.split()
# SCRIPTS = 'js php pl py rb sh bat'.split()
# ARCHIVES = 'gz bz2 zip tar tgz txz 7z'.split()
# EXECUTABLES = 'so exe dll'.split()
# DEFAULTS = TEXT + DOCUMENTS + IMAGES + DATA
# ALL = All()
# NONE = DisallowAll()
# def extension(filename):
# def lower_extension(filename):
# def mime(filename, default=None):
# def __contains__(self, item):
# def __contains__(self, item):
# def __init__(self, items):
# def __contains__(self, item):
# class All(object):
# class DisallowAll(object):
# class AllExcept(object):
. Output only the next line. | def test_mime_default_to_none(): |
Predict the next line for this snippet: <|code_start|> assert tester.file
assert tester.file.filename == expected_filename
assert expected_filename in storage
assert tester.to_mongo() == {
'file': {
'filename': expected_filename,
}
}
tester.save()
tester = Tester.objects.get(id=tester.id)
assert tester.file.filename == expected_filename
def test_save_with_callable_basename(self, storage, utils):
class Tester(db.Document):
file = FileField(fs=storage, basename=lambda o: 'prefix/filename')
filename = 'test.txt'
tester = Tester()
tester.file.save(utils.filestorage(filename, 'this is a stest'))
tester.validate()
expected_filename = 'prefix/filename.txt'
assert tester.file
assert tester.file.filename == expected_filename
assert expected_filename in storage
assert tester.to_mongo() == {
'file': {
'filename': expected_filename,
<|code_end|>
with the help of current file imports:
import filecmp
import os
import flask_fs as fs
import pytest
from PIL import Image
from flask_fs.mongo import FileField, ImageField
from flask_mongoengine import MongoEngine
and context from other files:
# Path: flask_fs/mongo.py
# class FileField(BaseField):
# '''
# Store reference to files in a given storage.
# '''
# proxy_class = FileReference
#
# def __init__(self, fs=None, upload_to=None, basename=None, *args, **kwargs):
# self.fs = fs
# self.upload_to = upload_to
# self.basename = basename
# super(FileField, self).__init__(*args, **kwargs)
#
# def proxy(self, filename=None, instance=None, **kwargs):
# return self.proxy_class(
# fs=self.fs,
# filename=filename,
# upload_to=self.upload_to,
# basename=self.basename,
# instance=instance,
# name=self.name,
# **kwargs
# )
#
# def to_python(self, value):
# if not isinstance(value, self.proxy_class):
# if isinstance(value, dict):
# value = self.proxy(**value)
# elif isinstance(value, six.text_type):
# value = self.proxy(filename=value)
# return value
#
# def __set__(self, instance, value):
# if not isinstance(value, self.proxy_class):
# value = self.proxy(filename=value, instance=instance)
# return super(FileField, self).__set__(instance, value)
#
# def __get__(self, instance, owner):
# if instance is None:
# return self
#
# fileref = instance._data.get(self.name)
# if not isinstance(fileref, self.proxy_class):
# fileref = self.proxy(filename=fileref, instance=instance)
# instance._data[self.name] = fileref
# elif fileref._instance is None:
# fileref._instance = instance
# return fileref
#
# def to_mongo(self, value):
# if not value:
# return None
# return value.to_mongo()
#
# class ImageField(FileField):
# '''
# Store reference to images in a given Storage.
#
# Allow to automatically generate thumbnails or resized image.
# Original image always stay untouched.
# '''
# proxy_class = ImageReference
#
# def __init__(self, max_size=None, thumbnails=None, optimize=None, *args, **kwargs):
# self.max_size = max_size
# self.thumbnail_sizes = thumbnails
# self.optimize = optimize
# super(ImageField, self).__init__(*args, **kwargs)
#
# def proxy(self, **kwargs):
# return super(ImageField, self).proxy(max_size=self.max_size,
# thumbnail_sizes=self.thumbnail_sizes,
# optimize=self.optimize,
# **kwargs)
, which may contain function names, class names, or code. Output only the next line. | } |
Given snippet: <|code_start|>
tester.save()
tester = Tester.objects.get(id=tester.id)
assert tester.file.filename == filename
def test_save_from_filestorage(self, storage, utils):
class Tester(db.Document):
file = FileField(fs=storage)
filename = 'test.txt'
tester = Tester()
tester.file.save(utils.filestorage(filename, 'this is a stest'))
tester.validate()
assert tester.file
assert str(tester.file) == tester.file.url
assert tester.file.filename == filename
assert tester.to_mongo() == {
'file': {
'filename': filename,
}
}
assert filename in storage
tester.save()
tester = Tester.objects.get(id=tester.id)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import filecmp
import os
import flask_fs as fs
import pytest
from PIL import Image
from flask_fs.mongo import FileField, ImageField
from flask_mongoengine import MongoEngine
and context:
# Path: flask_fs/mongo.py
# class FileField(BaseField):
# '''
# Store reference to files in a given storage.
# '''
# proxy_class = FileReference
#
# def __init__(self, fs=None, upload_to=None, basename=None, *args, **kwargs):
# self.fs = fs
# self.upload_to = upload_to
# self.basename = basename
# super(FileField, self).__init__(*args, **kwargs)
#
# def proxy(self, filename=None, instance=None, **kwargs):
# return self.proxy_class(
# fs=self.fs,
# filename=filename,
# upload_to=self.upload_to,
# basename=self.basename,
# instance=instance,
# name=self.name,
# **kwargs
# )
#
# def to_python(self, value):
# if not isinstance(value, self.proxy_class):
# if isinstance(value, dict):
# value = self.proxy(**value)
# elif isinstance(value, six.text_type):
# value = self.proxy(filename=value)
# return value
#
# def __set__(self, instance, value):
# if not isinstance(value, self.proxy_class):
# value = self.proxy(filename=value, instance=instance)
# return super(FileField, self).__set__(instance, value)
#
# def __get__(self, instance, owner):
# if instance is None:
# return self
#
# fileref = instance._data.get(self.name)
# if not isinstance(fileref, self.proxy_class):
# fileref = self.proxy(filename=fileref, instance=instance)
# instance._data[self.name] = fileref
# elif fileref._instance is None:
# fileref._instance = instance
# return fileref
#
# def to_mongo(self, value):
# if not value:
# return None
# return value.to_mongo()
#
# class ImageField(FileField):
# '''
# Store reference to images in a given Storage.
#
# Allow to automatically generate thumbnails or resized image.
# Original image always stay untouched.
# '''
# proxy_class = ImageReference
#
# def __init__(self, max_size=None, thumbnails=None, optimize=None, *args, **kwargs):
# self.max_size = max_size
# self.thumbnail_sizes = thumbnails
# self.optimize = optimize
# super(ImageField, self).__init__(*args, **kwargs)
#
# def proxy(self, **kwargs):
# return super(ImageField, self).proxy(max_size=self.max_size,
# thumbnail_sizes=self.thumbnail_sizes,
# optimize=self.optimize,
# **kwargs)
which might include code, classes, or functions. Output only the next line. | assert tester.file.filename == filename |
Predict the next line for this snippet: <|code_start|> 'xe': u'ɛ',
'e': u'eɪ',
'xi': u'ɪ',
'i': u'iː',
'o': u'oʊ',
'xo': u'ɔɪ',
'xu': u'ʊ',
'u': u'uː',
'b': u'b',
'xc': u'ʧ',
'd': u'd',
'xd': u'ð',
'f': u'f',
'g': u'g',
'h': u'h',
'xj': u'ʤ',
'k': u'k',
'l': u'l',
'm': u'm',
'n': u'n',
'xg': u'ŋ',
'p': u'p',
'r': u'r',
's': u's',
'xs': u'ʃ',
't': u't',
'xt': u'θ',
'v': u'v',
'w': u'w',
'y': u'j',
<|code_end|>
with the help of current file imports:
import os
import re
import abkhazia.utils as utils
from abkhazia.corpus.prepare import AbstractPreparatorWithCMU
and context from other files:
# Path: abkhazia/corpus/prepare/abstract_preparator.py
# class AbstractPreparatorWithCMU(AbstractPreparator):
# """Specialized wrapper for preparators relying on the CMU dictionary
#
# Abkhazia automatically downloaded the dictionary for you during
# installation. It is available for free at
# http://www.speech.cs.cmu.edu/cgi-bin/cmudict. The preparator is
# designed for version 0.7a of the CMU dictionary, but other recent
# versions could probably be used without changing anything.
#
# """
# default_cmu_dict = pkg_resources.resource_filename(
# pkg_resources.Requirement.parse('abkhazia'),
# 'abkhazia/share/cmudict.0.7a')
#
# def __init__(self, input_dir, cmu_dict=None,
# log=utils.logger.null_logger()):
# super(AbstractPreparatorWithCMU, self).__init__(input_dir, log)
#
# # init path to CMU dictionary
# if cmu_dict is None:
# cmu_dict = self.default_cmu_dict
# if not os.path.isfile(cmu_dict):
# raise IOError(
# 'CMU dictionary does not exist: {}'
# .format(cmu_dict))
#
# self.cmu_dict = cmu_dict
# self.log.debug('CMU dictionary is %s', self.cmu_dict)
, which may contain function names, class names, or code. Output only the next line. | 'z': u'z', |
Continue the code snippet: <|code_start|>
"""
def __init__(self, corpus, log=logger.null_logger(),
random_seed=None, prune=True):
self.log = log
self.prune = prune
self.corpus = corpus
# seed the random generator
if random_seed is not None:
self.log.debug('random seed is %i', random_seed)
random.seed(random_seed)
# read utt2spk from the input corpus
utt_ids, utt_speakers = zip(*self.corpus.utt2spk.items())
self.utts = list(zip(utt_ids, utt_speakers))
self.size = len(utt_ids)
self.speakers = set(utt_speakers)
self.log.debug('loaded %i utterances from %i speakers',
self.size, len(self.speakers))
@staticmethod
def default_test_prop():
"""Return the default proportion for the test set
Try to read from configuration file, else return 0.5"""
try:
return float(config.get(
'split', 'default-test-proportion'))
except configparser.NoOptionError:
<|code_end|>
. Use current file imports:
import configparser
import random
from abkhazia.utils import logger, config
and context (classes, functions, or code) from other files:
# Path: abkhazia/utils/logger.py
# class LevelFilter(logging.Filter):
# class WhitespaceRemovingFormatter(logging.Formatter):
# class NoEmptyMessageFilter(logging.Filter):
# class NoLocalSubdirNotFound(logging.Filter):
# def __init__(self, passlevels):
# def filter(self, record):
# def format(self, record):
# def filter(self, record):
# def filter(self, record):
# def get_log(log_file=os.devnull, verbose=False, header_in_stdout=False):
# def reopen_files(log, mode='a+'):
# def null_logger():
#
# Path: abkhazia/utils/config.py
# class AbkhaziaConfig(object):
# def default_config_file(name='abkhazia'):
# def __init__(self, config_file=None):
. Output only the next line. | return 0.5 |
Next line prediction: <|code_start|> represent the proportion of the dataset to include in the
train split. If None, the value is automatically set to the
complement of the test size. (default is None)
"""
def __init__(self, corpus, log=logger.null_logger(),
random_seed=None, prune=True):
self.log = log
self.prune = prune
self.corpus = corpus
# seed the random generator
if random_seed is not None:
self.log.debug('random seed is %i', random_seed)
random.seed(random_seed)
# read utt2spk from the input corpus
utt_ids, utt_speakers = zip(*self.corpus.utt2spk.items())
self.utts = list(zip(utt_ids, utt_speakers))
self.size = len(utt_ids)
self.speakers = set(utt_speakers)
self.log.debug('loaded %i utterances from %i speakers',
self.size, len(self.speakers))
@staticmethod
def default_test_prop():
"""Return the default proportion for the test set
Try to read from configuration file, else return 0.5"""
<|code_end|>
. Use current file imports:
(import configparser
import random
from abkhazia.utils import logger, config)
and context including class names, function names, or small code snippets from other files:
# Path: abkhazia/utils/logger.py
# class LevelFilter(logging.Filter):
# class WhitespaceRemovingFormatter(logging.Formatter):
# class NoEmptyMessageFilter(logging.Filter):
# class NoLocalSubdirNotFound(logging.Filter):
# def __init__(self, passlevels):
# def filter(self, record):
# def format(self, record):
# def filter(self, record):
# def filter(self, record):
# def get_log(log_file=os.devnull, verbose=False, header_in_stdout=False):
# def reopen_files(log, mode='a+'):
# def null_logger():
#
# Path: abkhazia/utils/config.py
# class AbkhaziaConfig(object):
# def default_config_file(name='abkhazia'):
# def __init__(self, config_file=None):
. Output only the next line. | try: |
Here is a snippet: <|code_start|> kaldi.options.make_option(
'add-layers-period', default=2, type=int,
help='add new layers every <int> iterations'),
kaldi.options.make_option(
'num-hidden-layers', default=3, type=int, help=''),
kaldi.options.make_option(
'splice-width', default=4, type=int,
help='meaning +- <int> frames on each side for second LDA'),
kaldi.options.make_option(
'randprune', default=4.0, type=float,
help='speeds up LDA'),
kaldi.options.make_option(
'alpha', default=4.0, type=float,
help='relates to preconditioning'),
kaldi.options.make_option(
'target-multiplier', default=0, type=float,
help='Set this to e.g. 1.0 to enable perturbed training'),
kaldi.options.make_option(
'mix-up', default=0, type=int, help=(
'Number of components to mix up to (should be > #tree leaves, '
'if specified)')),
kaldi.options.make_option(
'num-utts-subset', default=300, type=int, help='''
number of utterances in validation and training
subsets used for shrinkage and diagnostics.
Should have 2*num-utt-subset <= corpus.nutts'''),
kaldi.options.make_option(
'max-high-io-jobs', default=-1, type=int,
<|code_end|>
. Write the next line using the current file imports:
import os
import pkg_resources
import abkhazia.utils as utils
import abkhazia.kaldi as kaldi
from abkhazia.acoustic.abstract_acoustic_model import (
AbstractAcousticModel)
and context from other files:
# Path: abkhazia/acoustic/abstract_acoustic_model.py
# class AbstractAcousticModel(AbstractRecipe):
# """Abstract base class of acoustic models trainers
#
# Instantiates and run a Kaldi recipe to train a HMM-GMM model on an
# abkhazia corpus, along with attached features.
#
# Parameters:
# -----------
#
# corpus (Corpus): abkhazia corpus to process
#
# src_dir (str): path to the source directory (the model `n-1`), or
# a features_dir (if n=1, i.e. on monophone models)
#
# output_dir (str): path to the created recipe and results
#
# log (logging.Logger): where to send log messages
#
# """
# # Linked to 'abkhazia acoustic' from command line
# name = 'acoustic'
#
# model_type = NotImplemented
#
# options = NotImplemented
#
# def __init__(self, corpus, input_dir, output_dir, lang_args,
# log=utils.logger.null_logger):
# super(AbstractAcousticModel, self).__init__(
# corpus, output_dir, log=log)
#
# self.input_dir = os.path.abspath(input_dir)
# self.data_dir = os.path.join(self.recipe_dir, 'data', 'acoustic')
# self.lang_dir = os.path.join(self.output_dir, 'lang')
# self.lang_args = lang_args
#
# def check_parameters(self):
# """Check features are valid, setup metadata"""
# super(AbstractAcousticModel, self).check_parameters()
#
# # check lang_args are OK
# lang = self.lang_args
# assert lang['level'] in ('word', 'phone')
# assert (lang['silence_probability'] <= 1
# and lang['silence_probability'] > 0)
# assert isinstance(lang['position_dependent_phones'], bool)
# assert isinstance(lang['keep_tmp_dirs'], bool)
#
# # write the meta.txt file
# self.meta.source += '\n'.join((
# 'input directory:\t{}'.format(self.input_dir),
# 'acoustic model type:\t{}'.format(self.model_type)))
#
# def set_option(self, name, value):
# """Set option `name` to `value`
#
# Raise KeyError on unknown option and TypeError if the value
# cannot be converted to the option type
#
# """
# self.options[name].value = self.options[name].type(value)
#
# def create(self):
# super(AbstractAcousticModel, self).create()
#
# # copy features scp files in the recipe_dir
# Features.export_features(self.input_dir, self.data_dir)
#
# # create lang directory with L.fst
# lang = self.lang_args
# prepare_lang.prepare_lang(
# self.corpus,
# self.lang_dir,
# level=lang['level'],
# silence_probability=lang['silence_probability'],
# position_dependent_phones=lang['position_dependent_phones'],
# keep_tmp_dirs=lang['keep_tmp_dirs'],
# log=self.log)
#
# def export(self):
# """Copy model files to output_dir"""
# result_directory = os.path.join(
# self.recipe_dir, 'exp', self.model_type)
#
# for path in (
# # exclude files starting with numbers, as we want only
# # final state
# p for p in utils.list_directory(result_directory, abspath=True)
# if not os.path.basename(p)[0].isdigit()):
# if os.path.isdir(path): # for log subdir
# shutil.copytree(
# path,
# os.path.join(self.output_dir, os.path.basename(path)))
# else:
# shutil.copy(path, self.output_dir)
#
# super(AbstractAcousticModel, self).export()
#
# def run(self):
# raise NotImplementedError
#
# def _run_am_command(self, command, target, message):
# self.log.info(message)
# if not os.path.isdir(target):
# os.makedirs(target)
# self._run_command(command, verbose=False)
#
# def _opt(self, name):
# """Return the value of an option given its name"""
# return str(self.options[name])
, which may include functions, classes, or code. Output only the next line. | help=('limits the number of jobs with lots of I/O running ' |
Here is a snippet: <|code_start|> corrupted_wavs.append(utt_id)
if corrupted_wavs != []:
self.log.debug('some utterances have no associated wav: {}'
.format(corrupted_wavs))
return text
def make_lexicon(self):
# To generate the lexicon, we will use the cmu dict and the
# dict of OOVs generated by LibriSpeech)
cmu_combined = dict()
with open(self.librispeech_dict, 'r') as infile:
for line in infile:
if not re.match(";;; ", line):
dictionary = re.match("(.*)\t(.*)", line)
if dictionary:
entry = dictionary.group(1)
phn = dictionary.group(2)
# remove pronunciation variants
phn = phn.replace("0", "")
phn = phn.replace("1", "")
phn = phn.replace("2", "")
# create the combined dictionary
cmu_combined[entry] = phn
with open(self.cmu_dict, 'r') as infile:
for line in infile:
if not re.match(";;; ", line):
dictionary = re.match(r"(.*)\s\s(.*)", line)
if dictionary:
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import abkhazia.utils as utils
from abkhazia.corpus.prepare import AbstractPreparatorWithCMU
and context from other files:
# Path: abkhazia/corpus/prepare/abstract_preparator.py
# class AbstractPreparatorWithCMU(AbstractPreparator):
# """Specialized wrapper for preparators relying on the CMU dictionary
#
# Abkhazia automatically downloaded the dictionary for you during
# installation. It is available for free at
# http://www.speech.cs.cmu.edu/cgi-bin/cmudict. The preparator is
# designed for version 0.7a of the CMU dictionary, but other recent
# versions could probably be used without changing anything.
#
# """
# default_cmu_dict = pkg_resources.resource_filename(
# pkg_resources.Requirement.parse('abkhazia'),
# 'abkhazia/share/cmudict.0.7a')
#
# def __init__(self, input_dir, cmu_dict=None,
# log=utils.logger.null_logger()):
# super(AbstractPreparatorWithCMU, self).__init__(input_dir, log)
#
# # init path to CMU dictionary
# if cmu_dict is None:
# cmu_dict = self.default_cmu_dict
# if not os.path.isfile(cmu_dict):
# raise IOError(
# 'CMU dictionary does not exist: {}'
# .format(cmu_dict))
#
# self.cmu_dict = cmu_dict
# self.log.debug('CMU dictionary is %s', self.cmu_dict)
, which may include functions, classes, or code. Output only the next line. | entry = dictionary.group(1) |
Continue the code snippet: <|code_start|> '4oez0e04','4odz0e03','4odx0e01','4odz0e04',
'4odz0e01','4odz0e02','4ojz0e03','4ojz0e04',
'4ojz0e01','4ojz0e02','4ojx0e01','4ogz0e03',
'4ogz0e04','4ogz0e02','4ogx0e01','4ogz0e01',
'4ocz0e04','4ocz0e01','4ocx0e01','4ocz0e03',
'4ocz0e02','4oaz0e04','4oaz0e03','4oaz0e01',
'4oaz0e02','4oax0e01','4ofz0e01','4ofz0e04',
'4ofz0e03','4ofz0e02','4ofx0e01','4obz0e01',
'4obz0e02','4obz0e03','4obx0e01','4obz0e04',
'4oiz0e04','4oiz0e02','4oiz0e01','4oiz0e03',
'4oix0e01','4ohz0e01','4ohz0e03','4ohx0e01',
'4ohz0e04','4ohz0e02','4oez0f04','4oez0f02',
'4oex0f01','4oez0f03','4oez0f01','4odz0f02',
'4odz0f01','4odz0f04','4odx0f01','4odz0f03',
'4ojz0f03','4ojz0f02','4ojx0f01','4ojz0f01',
'4ojz0f04','4ogz0f01','4ogz0f04','4ogx0f01',
'4ogz0f02','4ogz0f03','4ocz0f03','4ocz0f02',
'4ocz0f01','4ocz0f04','4ocx0f01','4oax0f01',
'4oaz0f02','4oaz0f03','4oaz0f01','4oaz0f04',
'4ofz0f04','4ofz0f02','4ofz0f01','4ofx0f01',
'4ofz0f03','4obx0f01','4obz0f01','4obz0f02',
'4obz0f04','4obz0f03','4oix0f01','4oiz0f04',
'4oiz0f01','4oiz0f02','4oiz0f03','4ohz0f03',
'4ohz0f01','4ohx0f01','4ohz0f04','4ohz0f02',
'4oex0101','4oex0301','4odx0301','4odx0101',
'4ojx0301','4ojx0101','4ogx0301','4ogx0101',
'4ocx0101','4ocx0301','4oax0101','4oax0301',
'4ofx0301','4ofx0101','4obx0101','4obx0301',
'4oix0101','4oix0301','4ohx0101','4ohx0301',
'4n5x0201','4n5x0101','4n3x0201','4n3x0101',
<|code_end|>
. Use current file imports:
import os
import re
import abkhazia.utils as utils
from abkhazia.corpus.prepare import AbstractPreparatorWithCMU
and context (classes, functions, or code) from other files:
# Path: abkhazia/corpus/prepare/abstract_preparator.py
# class AbstractPreparatorWithCMU(AbstractPreparator):
# """Specialized wrapper for preparators relying on the CMU dictionary
#
# Abkhazia automatically downloaded the dictionary for you during
# installation. It is available for free at
# http://www.speech.cs.cmu.edu/cgi-bin/cmudict. The preparator is
# designed for version 0.7a of the CMU dictionary, but other recent
# versions could probably be used without changing anything.
#
# """
# default_cmu_dict = pkg_resources.resource_filename(
# pkg_resources.Requirement.parse('abkhazia'),
# 'abkhazia/share/cmudict.0.7a')
#
# def __init__(self, input_dir, cmu_dict=None,
# log=utils.logger.null_logger()):
# super(AbstractPreparatorWithCMU, self).__init__(input_dir, log)
#
# # init path to CMU dictionary
# if cmu_dict is None:
# cmu_dict = self.default_cmu_dict
# if not os.path.isfile(cmu_dict):
# raise IOError(
# 'CMU dictionary does not exist: {}'
# .format(cmu_dict))
#
# self.cmu_dict = cmu_dict
# self.log.debug('CMU dictionary is %s', self.cmu_dict)
. Output only the next line. | '4n8x0201','4n8x0101','4n9x0101','4n9x0201', |
Here is a snippet: <|code_start|> else:
print(body % (low, high, val, stars,
_stars(val, val_max, stars)))
def _print_linear_hist(vals, val_type, strip_leading_zero):
global stars_max
log2_dist_max = 64
idx_max = -1
val_max = 0
for i, v in enumerate(vals):
if v > 0: idx_max = i
if v > val_max: val_max = v
header = " %-13s : count distribution"
body = " %-10d : %-8d |%-*s|"
stars = stars_max
if idx_max >= 0:
print(header % val_type)
for i in range(0, idx_max + 1):
val = vals[i]
if strip_leading_zero:
if val:
print(body % (i, val, stars,
_stars(val, val_max, stars)))
strip_leading_zero = False
else:
print(body % (i, val, stars,
<|code_end|>
. Write the next line using the current file imports:
from collections.abc import MutableMapping
from collections import MutableMapping
from time import strftime
from functools import reduce
from .libbcc import lib, _RAW_CB_TYPE, _LOST_CB_TYPE, _RINGBUF_CB_TYPE, bcc_perf_buffer_opts
from .utils import get_online_cpus
from .utils import get_possible_cpus
import ctypes as ct
import os
import errno
import re
import sys
and context from other files:
# Path: src/python/bcc/libbcc.py
# _RAW_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_void_p, ct.c_int)
# _LOST_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_ulonglong)
# _RINGBUF_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p, ct.c_int)
# _SYM_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_char_p, ct.c_ulonglong)
# NONE = 0x0
# CONSTANT = 0x1
# DEREF_OFFSET = 0x2
# DEREF_IDENT = 0x4
# BASE_REGISTER_NAME = 0x8
# INDEX_REGISTER_NAME = 0x10
# SCALE = 0x20
# _USDT_CB = ct.CFUNCTYPE(None, ct.POINTER(bcc_usdt))
# _USDT_PROBE_CB = ct.CFUNCTYPE(None, ct.c_char_p, ct.c_char_p,
# ct.c_ulonglong, ct.c_int)
# class bcc_perf_buffer_opts(ct.Structure):
# class bcc_symbol(ct.Structure):
# class bcc_ip_offset_union(ct.Union):
# class bcc_stacktrace_build_id(ct.Structure):
# class bcc_symbol_option(ct.Structure):
# class bcc_usdt(ct.Structure):
# class bcc_usdt_location(ct.Structure):
# class BCC_USDT_ARGUMENT_FLAGS(object):
# class bcc_usdt_argument(ct.Structure):
, which may include functions, classes, or code. Output only the next line. | _stars(val, val_max, stars))) |
Given snippet: <|code_start|> return key
def leaf_scanf(self, leaf_str):
leaf = self.Leaf()
res = lib.bpf_table_leaf_sscanf(self.bpf.module, self.map_id, leaf_str,
ct.byref(leaf))
if res < 0:
raise Exception("Could not scanf leaf")
return leaf
def __getitem__(self, key):
leaf = self.Leaf()
res = lib.bpf_lookup_elem(self.map_fd, ct.byref(key), ct.byref(leaf))
if res < 0:
raise KeyError
return leaf
def __setitem__(self, key, leaf):
res = lib.bpf_update_elem(self.map_fd, ct.byref(key), ct.byref(leaf), 0)
if res < 0:
errstr = os.strerror(ct.get_errno())
raise Exception("Could not update table: %s" % errstr)
def __delitem__(self, key):
res = lib.bpf_delete_elem(self.map_fd, ct.byref(key))
if res < 0:
raise KeyError
# override the MutableMapping's implementation of these since they
# don't handle KeyError nicely
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections.abc import MutableMapping
from collections import MutableMapping
from time import strftime
from functools import reduce
from .libbcc import lib, _RAW_CB_TYPE, _LOST_CB_TYPE, _RINGBUF_CB_TYPE, bcc_perf_buffer_opts
from .utils import get_online_cpus
from .utils import get_possible_cpus
import ctypes as ct
import os
import errno
import re
import sys
and context:
# Path: src/python/bcc/libbcc.py
# _RAW_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_void_p, ct.c_int)
# _LOST_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_ulonglong)
# _RINGBUF_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p, ct.c_int)
# _SYM_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_char_p, ct.c_ulonglong)
# NONE = 0x0
# CONSTANT = 0x1
# DEREF_OFFSET = 0x2
# DEREF_IDENT = 0x4
# BASE_REGISTER_NAME = 0x8
# INDEX_REGISTER_NAME = 0x10
# SCALE = 0x20
# _USDT_CB = ct.CFUNCTYPE(None, ct.POINTER(bcc_usdt))
# _USDT_PROBE_CB = ct.CFUNCTYPE(None, ct.c_char_p, ct.c_char_p,
# ct.c_ulonglong, ct.c_int)
# class bcc_perf_buffer_opts(ct.Structure):
# class bcc_symbol(ct.Structure):
# class bcc_ip_offset_union(ct.Union):
# class bcc_stacktrace_build_id(ct.Structure):
# class bcc_symbol_option(ct.Structure):
# class bcc_usdt(ct.Structure):
# class bcc_usdt_location(ct.Structure):
# class BCC_USDT_ARGUMENT_FLAGS(object):
# class bcc_usdt_argument(ct.Structure):
which might include code, classes, or functions. Output only the next line. | def itervalues(self): |
Predict the next line after this snippet: <|code_start|> # Using print+sys.exit instead of raising exceptions,
# because exceptions are caught by the caller.
print("Type: '%s' not recognized. Please define the data with ctypes manually."
% field_type, file=sys.stderr)
sys.exit(1)
i += 1
return type('', (ct.Structure,), {'_fields_': fields})
def Table(bpf, map_id, map_fd, keytype, leaftype, name, **kwargs):
"""Table(bpf, map_id, map_fd, keytype, leaftype, **kwargs)
Create a python object out of a reference to a bpf table handle"""
ttype = lib.bpf_table_type_id(bpf.module, map_id)
t = None
if ttype == BPF_MAP_TYPE_HASH:
t = HashTable(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_ARRAY:
t = Array(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_PROG_ARRAY:
t = ProgArray(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_PERF_EVENT_ARRAY:
t = PerfEventArray(bpf, map_id, map_fd, keytype, leaftype, name)
elif ttype == BPF_MAP_TYPE_PERCPU_HASH:
t = PerCpuHash(bpf, map_id, map_fd, keytype, leaftype, **kwargs)
elif ttype == BPF_MAP_TYPE_PERCPU_ARRAY:
t = PerCpuArray(bpf, map_id, map_fd, keytype, leaftype, **kwargs)
elif ttype == BPF_MAP_TYPE_LPM_TRIE:
t = LpmTrie(bpf, map_id, map_fd, keytype, leaftype)
<|code_end|>
using the current file's imports:
from collections.abc import MutableMapping
from collections import MutableMapping
from time import strftime
from functools import reduce
from .libbcc import lib, _RAW_CB_TYPE, _LOST_CB_TYPE, _RINGBUF_CB_TYPE, bcc_perf_buffer_opts
from .utils import get_online_cpus
from .utils import get_possible_cpus
import ctypes as ct
import os
import errno
import re
import sys
and any relevant context from other files:
# Path: src/python/bcc/libbcc.py
# _RAW_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_void_p, ct.c_int)
# _LOST_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_ulonglong)
# _RINGBUF_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p, ct.c_int)
# _SYM_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_char_p, ct.c_ulonglong)
# NONE = 0x0
# CONSTANT = 0x1
# DEREF_OFFSET = 0x2
# DEREF_IDENT = 0x4
# BASE_REGISTER_NAME = 0x8
# INDEX_REGISTER_NAME = 0x10
# SCALE = 0x20
# _USDT_CB = ct.CFUNCTYPE(None, ct.POINTER(bcc_usdt))
# _USDT_PROBE_CB = ct.CFUNCTYPE(None, ct.c_char_p, ct.c_char_p,
# ct.c_ulonglong, ct.c_int)
# class bcc_perf_buffer_opts(ct.Structure):
# class bcc_symbol(ct.Structure):
# class bcc_ip_offset_union(ct.Union):
# class bcc_stacktrace_build_id(ct.Structure):
# class bcc_symbol_option(ct.Structure):
# class bcc_usdt(ct.Structure):
# class bcc_usdt_location(ct.Structure):
# class BCC_USDT_ARGUMENT_FLAGS(object):
# class bcc_usdt_argument(ct.Structure):
. Output only the next line. | elif ttype == BPF_MAP_TYPE_STACK_TRACE: |
Given snippet: <|code_start|> body = "%20d -> %-20d : %-8d |%-*s|"
stars = int(stars_max / 2)
if idx_max > 0:
print(header % val_type)
for i in range(1, idx_max + 1):
low = (1 << i) >> 1
high = (1 << i) - 1
if (low == high):
low -= 1
val = vals[i]
if strip_leading_zero:
if val:
print(body % (low, high, val, stars,
_stars(val, val_max, stars)))
strip_leading_zero = False
else:
print(body % (low, high, val, stars,
_stars(val, val_max, stars)))
def _print_linear_hist(vals, val_type, strip_leading_zero):
global stars_max
log2_dist_max = 64
idx_max = -1
val_max = 0
for i, v in enumerate(vals):
if v > 0: idx_max = i
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections.abc import MutableMapping
from collections import MutableMapping
from time import strftime
from functools import reduce
from .libbcc import lib, _RAW_CB_TYPE, _LOST_CB_TYPE, _RINGBUF_CB_TYPE, bcc_perf_buffer_opts
from .utils import get_online_cpus
from .utils import get_possible_cpus
import ctypes as ct
import os
import errno
import re
import sys
and context:
# Path: src/python/bcc/libbcc.py
# _RAW_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_void_p, ct.c_int)
# _LOST_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_ulonglong)
# _RINGBUF_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p, ct.c_int)
# _SYM_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_char_p, ct.c_ulonglong)
# NONE = 0x0
# CONSTANT = 0x1
# DEREF_OFFSET = 0x2
# DEREF_IDENT = 0x4
# BASE_REGISTER_NAME = 0x8
# INDEX_REGISTER_NAME = 0x10
# SCALE = 0x20
# _USDT_CB = ct.CFUNCTYPE(None, ct.POINTER(bcc_usdt))
# _USDT_PROBE_CB = ct.CFUNCTYPE(None, ct.c_char_p, ct.c_char_p,
# ct.c_ulonglong, ct.c_int)
# class bcc_perf_buffer_opts(ct.Structure):
# class bcc_symbol(ct.Structure):
# class bcc_ip_offset_union(ct.Union):
# class bcc_stacktrace_build_id(ct.Structure):
# class bcc_symbol_option(ct.Structure):
# class bcc_usdt(ct.Structure):
# class bcc_usdt_location(ct.Structure):
# class BCC_USDT_ARGUMENT_FLAGS(object):
# class bcc_usdt_argument(ct.Structure):
which might include code, classes, or functions. Output only the next line. | if v > val_max: val_max = v |
Here is a snippet: <|code_start|>
def Table(bpf, map_id, map_fd, keytype, leaftype, name, **kwargs):
"""Table(bpf, map_id, map_fd, keytype, leaftype, **kwargs)
Create a python object out of a reference to a bpf table handle"""
ttype = lib.bpf_table_type_id(bpf.module, map_id)
t = None
if ttype == BPF_MAP_TYPE_HASH:
t = HashTable(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_ARRAY:
t = Array(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_PROG_ARRAY:
t = ProgArray(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_PERF_EVENT_ARRAY:
t = PerfEventArray(bpf, map_id, map_fd, keytype, leaftype, name)
elif ttype == BPF_MAP_TYPE_PERCPU_HASH:
t = PerCpuHash(bpf, map_id, map_fd, keytype, leaftype, **kwargs)
elif ttype == BPF_MAP_TYPE_PERCPU_ARRAY:
t = PerCpuArray(bpf, map_id, map_fd, keytype, leaftype, **kwargs)
elif ttype == BPF_MAP_TYPE_LPM_TRIE:
t = LpmTrie(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_STACK_TRACE:
t = StackTrace(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_LRU_HASH:
t = LruHash(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_LRU_PERCPU_HASH:
t = LruPerCpuHash(bpf, map_id, map_fd, keytype, leaftype)
elif ttype == BPF_MAP_TYPE_CGROUP_ARRAY:
<|code_end|>
. Write the next line using the current file imports:
from collections.abc import MutableMapping
from collections import MutableMapping
from time import strftime
from functools import reduce
from .libbcc import lib, _RAW_CB_TYPE, _LOST_CB_TYPE, _RINGBUF_CB_TYPE, bcc_perf_buffer_opts
from .utils import get_online_cpus
from .utils import get_possible_cpus
import ctypes as ct
import os
import errno
import re
import sys
and context from other files:
# Path: src/python/bcc/libbcc.py
# _RAW_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_void_p, ct.c_int)
# _LOST_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_ulonglong)
# _RINGBUF_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_void_p, ct.c_int)
# _SYM_CB_TYPE = ct.CFUNCTYPE(ct.c_int, ct.c_char_p, ct.c_ulonglong)
# NONE = 0x0
# CONSTANT = 0x1
# DEREF_OFFSET = 0x2
# DEREF_IDENT = 0x4
# BASE_REGISTER_NAME = 0x8
# INDEX_REGISTER_NAME = 0x10
# SCALE = 0x20
# _USDT_CB = ct.CFUNCTYPE(None, ct.POINTER(bcc_usdt))
# _USDT_PROBE_CB = ct.CFUNCTYPE(None, ct.c_char_p, ct.c_char_p,
# ct.c_ulonglong, ct.c_int)
# class bcc_perf_buffer_opts(ct.Structure):
# class bcc_symbol(ct.Structure):
# class bcc_ip_offset_union(ct.Union):
# class bcc_stacktrace_build_id(ct.Structure):
# class bcc_symbol_option(ct.Structure):
# class bcc_usdt(ct.Structure):
# class bcc_usdt_location(ct.Structure):
# class BCC_USDT_ARGUMENT_FLAGS(object):
# class bcc_usdt_argument(ct.Structure):
, which may include functions, classes, or code. Output only the next line. | t = CgroupArray(bpf, map_id, map_fd, keytype, leaftype) |
Given the code snippet: <|code_start|>
def __init__(self, left_op, right_op):
super(Binary, self).__init__()
self.left_op, self.right_op = left_op, right_op
def forward(self, *inputs):
left_out, right_out = (
self.left_op.forward(*inputs),
self.right_op.forward(*inputs)
)
return [self.combinator(a, b) for a, b in zip(left_out, right_out)]
def shape_inference(self):
self.left_op.shape_inference()
self.right_op.shape_inference()
def get_shape_in(self):
return self.left_op.get_shape_in()
def get_shape_out(self):
return self.left_op.get_shape_out()
def set_shape_in(self, shape_in):
self.left_op.set_shape_in(shape_in)
self.right_op.set_shape_in(shape_in)
def set_shape_out(self, shape_out):
self.left_op.set_shape_out(shape_out)
self.right_op.set_shape_out(shape_out)
<|code_end|>
, generate the next line using the imports in this file:
from abc import abstractmethod
from deepx.core.op import Op
and context (functions, classes, or occasionally code) from other files:
# Path: deepx/core/op.py
# class Op(object):
#
# def __init__(self):
# self.parameters = {}
# self.device = T.get_current_device()
# self.shape_in, self.shape_out = None, None
# self.initializer = T.get_current_initialization()
#
# def get_parameters(self):
# return list(self.parameters.values())
#
# def get_parameter_list(self, *args, **kwargs):
# params = kwargs.pop('params', None)
# return [self.get_parameter(a, params=params) for a in args]
#
# def get_parameter(self, key, params=None):
# if params is None:
# return self.parameters[key]
# return params[key]
#
# def set_parameter(self, key, value):
# self.parameters[key] = value
#
# def create_parameter(self, name, shape, initializer=None):
# if initializer is None:
# initializer = self.initializer
# if isinstance(initializer, tuple):
# init_type, kwargs = initializer
# else:
# init_type, kwargs = initializer, {}
# if callable(init_type):
# init = lambda: init_type(shape, **kwargs)
# else:
# init = get_initializer(init_type)(shape, **kwargs)
# self.set_parameter(name, T.variable(init()))
#
# def __call__(self, *inputs, **kwargs):
# if self.get_shape_in() is None:
# in_shape = [T.get_shape(input) for input in inputs]
# self.set_shape_in(in_shape)
# self.shape_inference()
# output = self.forward(*inputs, **kwargs)
# if isinstance(output, list) or isinstance(output, tuple):
# if len(output) == 1:
# return output[0]
# return output
#
# def get_shape_out(self):
# return self.shape_out
#
# def get_shape_in(self):
# return self.shape_in
#
# def set_shape_in(self, shape_in):
# self.shape_in = shape_in
#
# def set_shape_out(self, shape_out):
# self.shape_out = shape_out
#
# def compose(self, op):
# from deepx.core.compose import Compose
# return Compose(self, op)
#
# def add(self, op):
# from deepx.core.arithmetic import Add
# return Add(self, op)
#
# def sub(self, op):
# from deepx.core.arithmetic import Sub
# return Sub(self, op)
#
# def mul(self, op):
# from deepx.core.arithmetic import Mul
# return Mul(self, op)
#
# def div(self, op):
# from deepx.core.arithmetic import Div
# return Div(self, op)
#
# def __add__(self, op):
# return self.add(op)
#
# def __radd__(self, op):
# return self.add(op)
#
# def __sub__(self, op):
# return self.sub(op)
#
# def __rsub__(self, op):
# return op.sub(self)
#
# def __mul__(self, op):
# return self.mul(op)
#
# def __rmul__(self, op):
# return self.mul(op)
#
# def __div__(self, op):
# return self.div(op)
#
# def __rdiv__(self, op):
# return op.div(self)
#
# def __rshift__(self, op):
# return self.compose(op)
#
# def __rrshift__(self, op):
# return self.compose(op)
#
# def __repr__(self):
# return "{op_name}({shape_in}, {shape_out})".format(
# op_name=self.__class__.__name__,
# shape_in=self.get_shape_in(),
# shape_out=self.get_shape_out()
# )
#
# @abstractmethod
# def forward(self):
# pass
#
# @abstractmethod
# def shape_inference(self):
# pass
#
# @abstractmethod
# def is_initialized(self):
# pass
. Output only the next line. | def is_initialized(self): |
Here is a snippet: <|code_start|>class Add(Binary):
def combinator(self, a, b):
return a + b
def __repr__(self):
return "{} + {}".format(
self.left_op,
self.right_op
)
class Sub(Binary):
def combinator(self, a, b):
return a - b
def __repr__(self):
return "{} - {}".format(
self.left_op,
self.right_op
)
class Mul(Binary):
def combinator(self, a, b):
return a * b
def __repr__(self):
return "{} * {}".format(
self.left_op,
<|code_end|>
. Write the next line using the current file imports:
from abc import abstractmethod
from deepx.core.hof import Binary
and context from other files:
# Path: deepx/core/hof.py
# class Binary(Op):
#
# def __init__(self, left_op, right_op):
# super(Binary, self).__init__()
# self.left_op, self.right_op = left_op, right_op
#
# def forward(self, *inputs):
# left_out, right_out = (
# self.left_op.forward(*inputs),
# self.right_op.forward(*inputs)
# )
# return [self.combinator(a, b) for a, b in zip(left_out, right_out)]
#
# def shape_inference(self):
# self.left_op.shape_inference()
# self.right_op.shape_inference()
#
# def get_shape_in(self):
# return self.left_op.get_shape_in()
#
# def get_shape_out(self):
# return self.left_op.get_shape_out()
#
# def set_shape_in(self, shape_in):
# self.left_op.set_shape_in(shape_in)
# self.right_op.set_shape_in(shape_in)
#
# def set_shape_out(self, shape_out):
# self.left_op.set_shape_out(shape_out)
# self.right_op.set_shape_out(shape_out)
#
# def is_initialized(self):
# return self.left_op.is_initialized() and self.right_op.is_initialized()
#
# def get_parameters(self):
# return self.left_op.get_parameters() + self.right_op.get_parameters()
#
# @abstractmethod
# def combinator(self, a, b):
# pass
, which may include functions, classes, or code. Output only the next line. | self.right_op |
Given the code snippet: <|code_start|># (c) Copyright 2014,2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<backup_id>[^/]*)$', views.DetailView.as_view(), name='detail'),
url(r'^restore/(?P<backup_id>.*)$',
views.RestoreView.as_view(),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import url
from disaster_recovery.backups import views
and context (functions, classes, or occasionally code) from other files:
# Path: disaster_recovery/backups/views.py
# class IndexView(tables.DataTableView):
# class DetailView(generic.TemplateView):
# class RestoreView(workflows.WorkflowView):
# def get_data(self):
# def get_context_data(self, **kwargs):
# def get_object(self, *args, **kwargs):
# def is_update(self):
# def get_workflow_name(self):
# def get_initial(self):
# def get_workflow(self, *args, **kwargs):
. Output only the next line. | name='restore'), |
Continue the code snippet: <|code_start|># (c) Copyright 2014,2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class ContainerBrowser(browsers.ResourceBrowser):
name = "backup_configuration"
verbose_name = _("Job Configuration")
navigation_table_class = tables.JobsTable
content_table_class = tables.ActionsTable
navigable_item_name = _("Jobs")
<|code_end|>
. Use current file imports:
from django.utils.translation import ugettext_lazy as _
from disaster_recovery.jobs import tables
from horizon import browsers
and context (classes, functions, or code) from other files:
# Path: disaster_recovery/jobs/tables.py
# class ObjectFilterAction(tables.FilterAction):
# class AttachJobToSession(tables.LinkAction):
# class DeleteJob(tables.DeleteAction):
# class DeleteMultipleJobs(DeleteJob):
# class CloneJob(tables.Action):
# class EditJob(tables.LinkAction):
# class EditActionsInJob(tables.LinkAction):
# class StartJob(tables.Action):
# class StopJob(tables.Action):
# class CreateJob(tables.LinkAction):
# class UpdateRow(tables.Row):
# class JobsTable(tables.DataTable):
# class Meta(object):
# class DeleteAction(tables.DeleteAction):
# class DeleteMultipleActions(DeleteAction):
# class ActionsTable(tables.DataTable):
# class Meta(object):
# def allowed(self, request, datum):
# def allowed(self, request, instance):
# def get_link_url(self, datum):
# def action_present(count):
# def action_past(count):
# def delete(self, request, job_id):
# def single(self, table, request, job_id):
# def get_link_url(self, datum=None):
# def get_link_url(self, datum=None):
# def single(self, table, request, job_id):
# def allowed(self, request, job=None):
# def single(self, table, request, job_id):
# def allowed(self, request, job=None):
# def get_link(row):
# def get_object_id(self, row):
# def get_object_display(self, job):
# def action_present(count):
# def action_past(count):
# def delete(self, request, obj_id):
# def get_object_id(self, container):
. Output only the next line. | navigation_kwarg_name = "name" |
Based on the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Filter(tables.FilterAction):
filter_type = "server"
filter_choices = (("exact", "Exact text", True),)
class DeleteClient(tables.DeleteAction):
help_text = _("Delete Clients is not recoverable.")
@staticmethod
def action_present(count):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import tables
from django.urls import reverse
from disaster_recovery.utils import shield
import disaster_recovery.api.api as freezer_api
and context (classes, functions, sometimes code) from other files:
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | return ungettext_lazy( |
Given the following code snippet before the placeholder: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class IndexView(tables.DataTableView):
name = _("Clients")
slug = "clients"
table_class = freezer_tables.ClientsTable
template_name = "disaster_recovery/clients/index.html"
@shield('Unable to get clients', redirect='clients:index')
def get_data(self):
filters = self.table.get_filter_string() or None
return freezer_api.Client(self.request).list(search=filters)
class ClientView(generic.TemplateView):
template_name = 'disaster_recovery/clients/detail.html'
@shield('Unable to get client', redirect='clients:index')
def get_context_data(self, **kwargs):
<|code_end|>
, predict the next line using imports from the current file:
import pprint
import disaster_recovery.api.api as freezer_api
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from horizon import tables
from disaster_recovery.clients import tables as freezer_tables
from disaster_recovery.utils import shield
and context including class names, function names, and sometimes code from other files:
# Path: disaster_recovery/clients/tables.py
# class Filter(tables.FilterAction):
# class DeleteClient(tables.DeleteAction):
# class DeleteMultipleClients(DeleteClient):
# class ClientsTable(tables.DataTable):
# class Meta(object):
# def action_present(count):
# def action_past(count):
# def delete(self, request, client_id):
# def get_link(client):
# def get_object_display_key(self, datum):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | client = freezer_api.Client(self.request).get(kwargs['client_id'], |
Given the following code snippet before the placeholder: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class SessionsView(browsers.ResourceBrowserView):
browser_class = project_browsers.SessionBrowser
template_name = "disaster_recovery/sessions/browser.html"
@shield('Unable to get sessions list.', redirect='sessions:index')
def get_sessions_data(self):
return freezer_api.Session(self.request).list(limit=100)
@shield('Unable to get job list.', redirect='sessions:index')
def get_jobs_data(self):
if self.kwargs['session_id']:
return freezer_api.Session(self.request).jobs(
self.kwargs['session_id'])
<|code_end|>
, predict the next line using imports from the current file:
from horizon import browsers
from horizon import workflows
from disaster_recovery.sessions.workflows import attach
from disaster_recovery.sessions.workflows import create
from disaster_recovery.utils import shield
import disaster_recovery.api.api as freezer_api
import disaster_recovery.sessions.browsers as project_browsers
and context including class names, function names, and sometimes code from other files:
# Path: disaster_recovery/sessions/workflows/attach.py
# class SessionConfigurationAction(workflows.Action):
# class Meta:
# class SessionConfiguration(workflows.Step):
# class AttachJobToSession(workflows.Workflow):
# def populate_session_id_choices(self, request, context):
# def handle(self, request, context):
#
# Path: disaster_recovery/sessions/workflows/create.py
# class SessionConfigurationAction(workflows.Action):
# class Meta:
# class SessionConfiguration(workflows.Step):
# class CreateSession(workflows.Workflow):
# def clean(self):
# def _validate_iso_format(self, start_date):
# def _check_start_datetime(self, cleaned_data):
# def _check_end_datetime(self, cleaned_data):
# def handle(self, request, context):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | return [] |
Predict the next line for this snippet: <|code_start|> def get_sessions_data(self):
return freezer_api.Session(self.request).list(limit=100)
@shield('Unable to get job list.', redirect='sessions:index')
def get_jobs_data(self):
if self.kwargs['session_id']:
return freezer_api.Session(self.request).jobs(
self.kwargs['session_id'])
return []
class AttachToSessionWorkflow(workflows.WorkflowView):
workflow_class = attach.AttachJobToSession
@shield('Unable to get job', redirect='jobs:index')
def get_object(self, *args, **kwargs):
return freezer_api.Job(self.request).get(self.kwargs['job_id'])
def is_update(self):
return 'job_id' in self.kwargs and \
bool(self.kwargs['job_id'])
@shield('Unable to get job', redirect='jobs:index')
def get_initial(self):
initial = super(AttachToSessionWorkflow, self).get_initial()
job = self.get_object()
initial.update({'job_id': job.id})
return initial
<|code_end|>
with the help of current file imports:
from horizon import browsers
from horizon import workflows
from disaster_recovery.sessions.workflows import attach
from disaster_recovery.sessions.workflows import create
from disaster_recovery.utils import shield
import disaster_recovery.api.api as freezer_api
import disaster_recovery.sessions.browsers as project_browsers
and context from other files:
# Path: disaster_recovery/sessions/workflows/attach.py
# class SessionConfigurationAction(workflows.Action):
# class Meta:
# class SessionConfiguration(workflows.Step):
# class AttachJobToSession(workflows.Workflow):
# def populate_session_id_choices(self, request, context):
# def handle(self, request, context):
#
# Path: disaster_recovery/sessions/workflows/create.py
# class SessionConfigurationAction(workflows.Action):
# class Meta:
# class SessionConfiguration(workflows.Step):
# class CreateSession(workflows.Workflow):
# def clean(self):
# def _validate_iso_format(self, start_date):
# def _check_start_datetime(self, cleaned_data):
# def _check_end_datetime(self, cleaned_data):
# def handle(self, request, context):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
, which may contain function names, class names, or code. Output only the next line. | class CreateSessionWorkflow(workflows.WorkflowView): |
Using the snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class IndexView(tables.DataTableView):
name = _("Actions")
slug = "actions"
table_class = freezer_tables.ActionsTable
template_name = "disaster_recovery/actions/index.html"
@shield("Unable to get actions", redirect="actions:index")
def get_data(self):
filters = self.table.get_filter_string() or None
return freezer_api.Action(self.request).list(search=filters)
class ActionView(generic.TemplateView):
template_name = 'disaster_recovery/actions/detail.html'
@shield('Unable to get action', redirect='actions:index')
def get_context_data(self, **kwargs):
action = freezer_api.Action(self.request).get(kwargs['action_id'],
json=True)
<|code_end|>
, determine the next line of code. You have imports:
import pprint
import disaster_recovery.api.api as freezer_api
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from horizon import tables
from horizon import workflows
from disaster_recovery.actions import tables as freezer_tables
from disaster_recovery.actions.workflows import action as action_workflow
from disaster_recovery.utils import shield
and context (class names, function names, or code) available:
# Path: disaster_recovery/actions/tables.py
# class DeleteAction(tables.DeleteAction):
# class DeleteMultipleActions(DeleteAction):
# class Filter(tables.FilterAction):
# class CreateAction(tables.LinkAction):
# class EditAction(tables.LinkAction):
# class UpdateRow(tables.Row):
# class ActionsTable(tables.DataTable):
# class Meta:
# def action_present(count):
# def action_past(count):
# def delete(self, request, action_id):
# def get_link_url(self, datum=None):
# def get_link(action):
# def get_object_display(self, action):
#
# Path: disaster_recovery/actions/workflows/action.py
# class ActionConfigurationAction(workflows.Action):
# class Meta(object):
# class ActionConfiguration(workflows.Step):
# class SnapshotConfigurationAction(workflows.Action):
# class Meta(object):
# class SnapshotConfiguration(workflows.Step):
# class AdvancedConfigurationAction(workflows.Action):
# class Meta(object):
# class AdvancedConfiguration(workflows.Step):
# class RulesConfigurationAction(workflows.Action):
# class Meta(object):
# class RulesConfiguration(workflows.Step):
# class ActionWorkflow(workflows.Workflow):
# def clean(self):
# def _check_nova_restore_network(self, cleaned_data):
# def _check_nova_inst_id(self, cleaned_data):
# def _check_cinder_vol_id(self, cleaned_data):
# def _check_restore_abs_path(self, cleaned_data):
# def _check_container(self, cleaned_data):
# def _check_backup_name(self, cleaned_data):
# def _check_path_to_backup(self, cleaned_data):
# def populate_mode_choices(self, request, context):
# def populate_action_choices(self, request, context):
# def populate_storage_choices(self, request, context):
# def populate_engine_name_choices(self, request, context):
# def __init__(self, request, context, *args, **kwargs):
# def populate_os_identity_api_version_choices(self, request, context):
# def handle(self, request, context):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | return {'data': pprint.pformat(action)} |
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class IndexView(tables.DataTableView):
name = _("Actions")
slug = "actions"
table_class = freezer_tables.ActionsTable
<|code_end|>
. Use current file imports:
import pprint
import disaster_recovery.api.api as freezer_api
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from horizon import tables
from horizon import workflows
from disaster_recovery.actions import tables as freezer_tables
from disaster_recovery.actions.workflows import action as action_workflow
from disaster_recovery.utils import shield
and context (classes, functions, or code) from other files:
# Path: disaster_recovery/actions/tables.py
# class DeleteAction(tables.DeleteAction):
# class DeleteMultipleActions(DeleteAction):
# class Filter(tables.FilterAction):
# class CreateAction(tables.LinkAction):
# class EditAction(tables.LinkAction):
# class UpdateRow(tables.Row):
# class ActionsTable(tables.DataTable):
# class Meta:
# def action_present(count):
# def action_past(count):
# def delete(self, request, action_id):
# def get_link_url(self, datum=None):
# def get_link(action):
# def get_object_display(self, action):
#
# Path: disaster_recovery/actions/workflows/action.py
# class ActionConfigurationAction(workflows.Action):
# class Meta(object):
# class ActionConfiguration(workflows.Step):
# class SnapshotConfigurationAction(workflows.Action):
# class Meta(object):
# class SnapshotConfiguration(workflows.Step):
# class AdvancedConfigurationAction(workflows.Action):
# class Meta(object):
# class AdvancedConfiguration(workflows.Step):
# class RulesConfigurationAction(workflows.Action):
# class Meta(object):
# class RulesConfiguration(workflows.Step):
# class ActionWorkflow(workflows.Workflow):
# def clean(self):
# def _check_nova_restore_network(self, cleaned_data):
# def _check_nova_inst_id(self, cleaned_data):
# def _check_cinder_vol_id(self, cleaned_data):
# def _check_restore_abs_path(self, cleaned_data):
# def _check_container(self, cleaned_data):
# def _check_backup_name(self, cleaned_data):
# def _check_path_to_backup(self, cleaned_data):
# def populate_mode_choices(self, request, context):
# def populate_action_choices(self, request, context):
# def populate_storage_choices(self, request, context):
# def populate_engine_name_choices(self, request, context):
# def __init__(self, request, context, *args, **kwargs):
# def populate_os_identity_api_version_choices(self, request, context):
# def handle(self, request, context):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | template_name = "disaster_recovery/actions/index.html" |
Given the code snippet: <|code_start|># not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class IndexView(tables.DataTableView):
name = _("Actions")
slug = "actions"
table_class = freezer_tables.ActionsTable
template_name = "disaster_recovery/actions/index.html"
@shield("Unable to get actions", redirect="actions:index")
def get_data(self):
filters = self.table.get_filter_string() or None
return freezer_api.Action(self.request).list(search=filters)
class ActionView(generic.TemplateView):
<|code_end|>
, generate the next line using the imports in this file:
import pprint
import disaster_recovery.api.api as freezer_api
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from horizon import tables
from horizon import workflows
from disaster_recovery.actions import tables as freezer_tables
from disaster_recovery.actions.workflows import action as action_workflow
from disaster_recovery.utils import shield
and context (functions, classes, or occasionally code) from other files:
# Path: disaster_recovery/actions/tables.py
# class DeleteAction(tables.DeleteAction):
# class DeleteMultipleActions(DeleteAction):
# class Filter(tables.FilterAction):
# class CreateAction(tables.LinkAction):
# class EditAction(tables.LinkAction):
# class UpdateRow(tables.Row):
# class ActionsTable(tables.DataTable):
# class Meta:
# def action_present(count):
# def action_past(count):
# def delete(self, request, action_id):
# def get_link_url(self, datum=None):
# def get_link(action):
# def get_object_display(self, action):
#
# Path: disaster_recovery/actions/workflows/action.py
# class ActionConfigurationAction(workflows.Action):
# class Meta(object):
# class ActionConfiguration(workflows.Step):
# class SnapshotConfigurationAction(workflows.Action):
# class Meta(object):
# class SnapshotConfiguration(workflows.Step):
# class AdvancedConfigurationAction(workflows.Action):
# class Meta(object):
# class AdvancedConfiguration(workflows.Step):
# class RulesConfigurationAction(workflows.Action):
# class Meta(object):
# class RulesConfiguration(workflows.Step):
# class ActionWorkflow(workflows.Workflow):
# def clean(self):
# def _check_nova_restore_network(self, cleaned_data):
# def _check_nova_inst_id(self, cleaned_data):
# def _check_cinder_vol_id(self, cleaned_data):
# def _check_restore_abs_path(self, cleaned_data):
# def _check_container(self, cleaned_data):
# def _check_backup_name(self, cleaned_data):
# def _check_path_to_backup(self, cleaned_data):
# def populate_mode_choices(self, request, context):
# def populate_action_choices(self, request, context):
# def populate_storage_choices(self, request, context):
# def populate_engine_name_choices(self, request, context):
# def __init__(self, request, context, *args, **kwargs):
# def populate_os_identity_api_version_choices(self, request, context):
# def handle(self, request, context):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | template_name = 'disaster_recovery/actions/detail.html' |
Next line prediction: <|code_start|> backup = freezer_api.Backup(self.request).get(kwargs['backup_id'],
json=True)
return {'data': pprint.pformat(backup)}
class RestoreView(workflows.WorkflowView):
workflow_class = restore_workflow.Restore
@shield('Unable to get backup.', redirect='backups:index')
def get_object(self, *args, **kwargs):
return freezer_api.Backup(self.request).get(self.kwargs['backup_id'])
def is_update(self):
return 'name' in self.kwargs and bool(self.kwargs['name'])
@shield('Unable to get backup.', redirect='backups:index')
def get_workflow_name(self):
backup = freezer_api.Backup(self.request).get(self.kwargs['backup_id'])
backup_date_str = datetime.datetime.fromtimestamp(
int(backup.time_stamp)).strftime("%Y/%m/%d %H:%M")
return "Restore '{}' from {}".format(backup.backup_name,
backup_date_str)
def get_initial(self):
return {"backup_id": self.kwargs['backup_id']}
@shield('Unable to get backup.', redirect='backups:index')
def get_workflow(self, *args, **kwargs):
workflow = super(RestoreView, self).get_workflow(*args, **kwargs)
workflow.name = self.get_workflow_name()
<|code_end|>
. Use current file imports:
(import datetime
import pprint
import disaster_recovery.api.api as freezer_api
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from horizon import tables
from horizon import workflows
from disaster_recovery.backups import tables as freezer_tables
from disaster_recovery.backups.workflows import restore as restore_workflow
from disaster_recovery.utils import shield)
and context including class names, function names, or small code snippets from other files:
# Path: disaster_recovery/backups/tables.py
# class Restore(tables.LinkAction):
# class DeleteBackup(tables.DeleteAction):
# class DeleteMultipleBackups(DeleteBackup):
# class Filter(tables.FilterAction):
# class BackupsTable(tables.DataTable):
# class Meta:
# def get_link_url(self, datum=None):
# def action_present(count):
# def action_past(count):
# def delete(self, request, backup_id):
# def icons(backup):
# def backup_detail_view(backup):
# def get_pagination_string(self):
# def get_object_display_key(self, datum):
#
# Path: disaster_recovery/backups/workflows/restore.py
# class DestinationAction(workflows.MembershipAction):
# class Meta(object):
# class Destination(workflows.Step):
# class Restore(workflows.Workflow):
# def clean(self):
# def has_required_fields(self):
# def handle(self, request, data):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | return workflow |
Given snippet: <|code_start|>
class DetailView(generic.TemplateView):
template_name = 'disaster_recovery/backups/detail.html'
@shield('Unable to get backup.', redirect='backups:index')
def get_context_data(self, **kwargs):
backup = freezer_api.Backup(self.request).get(kwargs['backup_id'],
json=True)
return {'data': pprint.pformat(backup)}
class RestoreView(workflows.WorkflowView):
workflow_class = restore_workflow.Restore
@shield('Unable to get backup.', redirect='backups:index')
def get_object(self, *args, **kwargs):
return freezer_api.Backup(self.request).get(self.kwargs['backup_id'])
def is_update(self):
return 'name' in self.kwargs and bool(self.kwargs['name'])
@shield('Unable to get backup.', redirect='backups:index')
def get_workflow_name(self):
backup = freezer_api.Backup(self.request).get(self.kwargs['backup_id'])
backup_date_str = datetime.datetime.fromtimestamp(
int(backup.time_stamp)).strftime("%Y/%m/%d %H:%M")
return "Restore '{}' from {}".format(backup.backup_name,
backup_date_str)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import pprint
import disaster_recovery.api.api as freezer_api
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from horizon import tables
from horizon import workflows
from disaster_recovery.backups import tables as freezer_tables
from disaster_recovery.backups.workflows import restore as restore_workflow
from disaster_recovery.utils import shield
and context:
# Path: disaster_recovery/backups/tables.py
# class Restore(tables.LinkAction):
# class DeleteBackup(tables.DeleteAction):
# class DeleteMultipleBackups(DeleteBackup):
# class Filter(tables.FilterAction):
# class BackupsTable(tables.DataTable):
# class Meta:
# def get_link_url(self, datum=None):
# def action_present(count):
# def action_past(count):
# def delete(self, request, backup_id):
# def icons(backup):
# def backup_detail_view(backup):
# def get_pagination_string(self):
# def get_object_display_key(self, datum):
#
# Path: disaster_recovery/backups/workflows/restore.py
# class DestinationAction(workflows.MembershipAction):
# class Meta(object):
# class Destination(workflows.Step):
# class Restore(workflows.Workflow):
# def clean(self):
# def has_required_fields(self):
# def handle(self, request, data):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
which might include code, classes, or functions. Output only the next line. | def get_initial(self): |
Given snippet: <|code_start|> )
@shield("Unable to delete session", redirect="sessions:index")
def delete(self, request, session_id):
return freezer_api.Session(request).delete(session_id)
class EditSession(tables.LinkAction):
name = "edit_session"
verbose_name = _("Edit Session")
classes = ("ajax-modal",)
icon = "pencil"
def get_link_url(self, datum=None):
return reverse("horizon:disaster_recovery:sessions:edit",
kwargs={'session_id': datum.session_id})
class DeleteMultipleActions(DeleteSession):
name = "delete_multiple_actions"
class DeleteJobFromSession(tables.DeleteAction):
name = "delete_job_from_session"
help_text = _("Delete jobs is not recoverable.")
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Delete Job",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from django.urls import reverse
from horizon import tables
from disaster_recovery.utils import shield
import disaster_recovery.api.api as freezer_api
and context:
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
which might include code, classes, or functions. Output only the next line. | u"Delete Jobs", |
Predict the next line after this snippet: <|code_start|># (c) Copyright 2014,2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^create/(?P<action_id>[^/]+)?$',
views.ActionWorkflowView.as_view(),
name='create'),
url(r'^action/(?P<action_id>[^/]+)?$',
views.ActionView.as_view(),
name='action'),
<|code_end|>
using the current file's imports:
from django.conf.urls import url
from disaster_recovery.actions import views
and any relevant context from other files:
# Path: disaster_recovery/actions/views.py
# class IndexView(tables.DataTableView):
# class ActionView(generic.TemplateView):
# class ActionWorkflowView(workflows.WorkflowView):
# def get_data(self):
# def get_context_data(self, **kwargs):
# def is_update(self):
# def get_initial(self):
. Output only the next line. | ] |
Continue the code snippet: <|code_start|>
class Restore(tables.LinkAction):
name = "restore"
verbose_name = _("Restore")
classes = ("ajax-modal", "btn-launch")
ajax = True
def get_link_url(self, datum=None):
return reverse("horizon:disaster_recovery:backups:restore",
kwargs={'backup_id': datum.id})
class DeleteBackup(tables.DeleteAction):
help_text = _("Delete backups is not recoverable.")
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Delete Backup",
u"Delete Backups",
count
)
@staticmethod
def action_past(count):
return ungettext_lazy(
u"Deleted Backup",
u"Deleted Backups",
<|code_end|>
. Use current file imports:
from django.urls import reverse
from django.utils import safestring
from django.utils.translation import ungettext_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import tables
from horizon.utils import functions as utils
from disaster_recovery.utils import shield
from disaster_recovery.utils import timestamp_to_string
import disaster_recovery.api.api as freezer_api
and context (classes, functions, or code) from other files:
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
#
# Path: disaster_recovery/utils.py
# def timestamp_to_string(ts):
# return django_date(
# datetime.datetime.fromtimestamp(int(ts)),
# 'SHORT_DATETIME_FORMAT')
. Output only the next line. | count |
Given the code snippet: <|code_start|>
class Restore(tables.LinkAction):
name = "restore"
verbose_name = _("Restore")
classes = ("ajax-modal", "btn-launch")
ajax = True
def get_link_url(self, datum=None):
return reverse("horizon:disaster_recovery:backups:restore",
kwargs={'backup_id': datum.id})
class DeleteBackup(tables.DeleteAction):
help_text = _("Delete backups is not recoverable.")
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Delete Backup",
u"Delete Backups",
count
)
@staticmethod
def action_past(count):
return ungettext_lazy(
u"Deleted Backup",
u"Deleted Backups",
<|code_end|>
, generate the next line using the imports in this file:
from django.urls import reverse
from django.utils import safestring
from django.utils.translation import ungettext_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import tables
from horizon.utils import functions as utils
from disaster_recovery.utils import shield
from disaster_recovery.utils import timestamp_to_string
import disaster_recovery.api.api as freezer_api
and context (functions, classes, or occasionally code) from other files:
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
#
# Path: disaster_recovery/utils.py
# def timestamp_to_string(ts):
# return django_date(
# datetime.datetime.fromtimestamp(int(ts)),
# 'SHORT_DATETIME_FORMAT')
. Output only the next line. | count |
Predict the next line after this snippet: <|code_start|>
class ObjectFilterAction(tables.FilterAction):
def allowed(self, request, datum):
return bool(self.table.kwargs['job_id'])
class AttachJobToSession(tables.LinkAction):
name = "attach_job_to_session"
verbose_name = _("Attach To Session")
classes = ("ajax-modal",)
url = "horizon:disaster_recovery:sessions:attach"
def allowed(self, request, instance):
return True
def get_link_url(self, datum):
return reverse("horizon:disaster_recovery:sessions:attach",
kwargs={'job_id': datum.job_id})
class DeleteJob(tables.DeleteAction):
help_text = _("Delete jobs is not recoverable.")
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Delete Job File",
u"Delete Job Files",
count
<|code_end|>
using the current file's imports:
from django import shortcuts
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import tables
from horizon import messages
from django.urls import reverse
from disaster_recovery.utils import shield
import disaster_recovery.api.api as freezer_api
and any relevant context from other files:
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | ) |
Given the following code snippet before the placeholder: <|code_start|> @shield("Unable to get actions for this job.", redirect='jobs:index')
def get_actions_in_job_data(self):
if self.kwargs['job_id']:
return freezer_api.Job(self.request).actions(self.kwargs['job_id'])
return []
class JobWorkflowView(workflows.WorkflowView):
workflow_class = configure_workflow.ConfigureJob
@shield("Unable to get job", redirect="jobs:index")
def get_object(self):
return freezer_api.Job(self.request).get(self.kwargs['job_id'])
def is_update(self):
return 'job_id' in self.kwargs and bool(self.kwargs['job_id'])
@shield("Unable to get job", redirect="jobs:index")
def get_initial(self):
initial = super(JobWorkflowView, self).get_initial()
if self.is_update():
initial.update({'job_id': None})
job = freezer_api.Job(self.request).get(self.kwargs['job_id'],
json=True)
initial.update(**job)
initial.update(**job['job_schedule'])
return initial
<|code_end|>
, predict the next line using imports from the current file:
from horizon import browsers
from horizon import workflows
from disaster_recovery.jobs.workflows import create as configure_workflow
from disaster_recovery.jobs.workflows import update_job as update_job_workflow
from disaster_recovery.jobs.workflows import update_actions as update_workflow
from disaster_recovery.utils import shield
import disaster_recovery.api.api as freezer_api
import disaster_recovery.jobs.browsers as project_browsers
and context including class names, function names, and sometimes code from other files:
# Path: disaster_recovery/jobs/workflows/create.py
# class ActionsConfigurationAction(workflows.Action):
# class Meta(object):
# class ActionsConfiguration(workflows.Step):
# class ClientsConfigurationAction(workflows.MembershipAction):
# class Meta:
# class ClientsConfiguration(workflows.UpdateMembersStep):
# class InfoConfigurationAction(workflows.Action):
# class Meta(object):
# class InfoConfiguration(workflows.Step):
# class ConfigureJob(workflows.Workflow):
# def __init__(self, request, *args, **kwargs):
# def contribute(self, data, context):
# def __init__(self, request, context, *args, **kwargs):
# def clean(self):
# def _validate_iso_format(self, start_date):
# def populate_interval_uint_choices(self, request, context):
# def _check_start_datetime(self, cleaned_data):
# def _check_end_datetime(self, cleaned_data):
# def handle(self, request, context):
#
# Path: disaster_recovery/jobs/workflows/update_job.py
# class InfoConfigurationAction(workflows.Action):
# class Meta(object):
# class InfoConfiguration(workflows.Step):
# class UpdateJob(workflows.Workflow):
# def __init__(self, request, context, *args, **kwargs):
# def clean(self):
# def _validate_iso_format(self, start_date):
# def _check_start_datetime(self, cleaned_data):
# def _check_end_datetime(self, cleaned_data):
# def handle(self, request, context):
#
# Path: disaster_recovery/jobs/workflows/update_actions.py
# class ActionsConfigurationAction(workflows.Action):
# class Meta(object):
# class ActionsConfiguration(workflows.Step):
# class UpdateActions(workflows.Workflow):
# def handle(self, request, context):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | class EditJobWorkflowView(workflows.WorkflowView): |
Based on the snippet: <|code_start|>
@shield("Unable to get job", redirect="jobs:index")
def get_initial(self):
initial = super(EditJobWorkflowView, self).get_initial()
if self.is_update():
initial.update({'job_id': None})
job = freezer_api.Job(self.request).get(self.kwargs['job_id'],
json=True)
initial.update(**job)
initial.update(**job['job_schedule'])
return initial
class ActionsInJobView(workflows.WorkflowView):
workflow_class = update_workflow.UpdateActions
@shield("Unable to get job", redirect="jobs:index")
def get_object(self):
return freezer_api.Job(self.request).get(self.kwargs['job_id'])
def is_update(self):
return 'job_id' in self.kwargs and bool(self.kwargs['job_id'])
@shield("Unable to get job", redirect="jobs:index")
def get_initial(self):
initial = super(ActionsInJobView, self).get_initial()
if self.is_update():
job = freezer_api.Job(self.request).get(self.kwargs['job_id'])
initial.update({'job_id': job.id})
<|code_end|>
, predict the immediate next line with the help of imports:
from horizon import browsers
from horizon import workflows
from disaster_recovery.jobs.workflows import create as configure_workflow
from disaster_recovery.jobs.workflows import update_job as update_job_workflow
from disaster_recovery.jobs.workflows import update_actions as update_workflow
from disaster_recovery.utils import shield
import disaster_recovery.api.api as freezer_api
import disaster_recovery.jobs.browsers as project_browsers
and context (classes, functions, sometimes code) from other files:
# Path: disaster_recovery/jobs/workflows/create.py
# class ActionsConfigurationAction(workflows.Action):
# class Meta(object):
# class ActionsConfiguration(workflows.Step):
# class ClientsConfigurationAction(workflows.MembershipAction):
# class Meta:
# class ClientsConfiguration(workflows.UpdateMembersStep):
# class InfoConfigurationAction(workflows.Action):
# class Meta(object):
# class InfoConfiguration(workflows.Step):
# class ConfigureJob(workflows.Workflow):
# def __init__(self, request, *args, **kwargs):
# def contribute(self, data, context):
# def __init__(self, request, context, *args, **kwargs):
# def clean(self):
# def _validate_iso_format(self, start_date):
# def populate_interval_uint_choices(self, request, context):
# def _check_start_datetime(self, cleaned_data):
# def _check_end_datetime(self, cleaned_data):
# def handle(self, request, context):
#
# Path: disaster_recovery/jobs/workflows/update_job.py
# class InfoConfigurationAction(workflows.Action):
# class Meta(object):
# class InfoConfiguration(workflows.Step):
# class UpdateJob(workflows.Workflow):
# def __init__(self, request, context, *args, **kwargs):
# def clean(self):
# def _validate_iso_format(self, start_date):
# def _check_start_datetime(self, cleaned_data):
# def _check_end_datetime(self, cleaned_data):
# def handle(self, request, context):
#
# Path: disaster_recovery/jobs/workflows/update_actions.py
# class ActionsConfigurationAction(workflows.Action):
# class Meta(object):
# class ActionsConfiguration(workflows.Step):
# class UpdateActions(workflows.Workflow):
# def handle(self, request, context):
#
# Path: disaster_recovery/utils.py
# def shield(message, redirect=''):
# """decorator to reduce boilerplate try except blocks for horizon functions
# :param message: a str error message
# :param redirect: a str with the redirect namespace without including
# horizon:disaster_recovery:
# eg. @shield('error', redirect='jobs:index')
# """
# def wrap(function):
#
# @wraps(function)
# def wrapped_function(view, *args, **kwargs):
#
# try:
# return function(view, *args, **kwargs)
# except Exception as error:
# LOG.error(error.message)
# namespace = "horizon:disaster_recovery:"
# r = reverse("{0}{1}".format(namespace, redirect))
#
# if view.request.path == r:
# # To avoid an endless loop, we must not redirect to the
# # same page on which the error happened
# user_home = get_user_home(view.request.user)
# exceptions.handle(view.request, _(error.message),
# redirect=user_home)
# else:
# exceptions.handle(view.request, _(error.message),
# redirect=r)
#
# return wrapped_function
# return wrap
. Output only the next line. | return initial |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.