Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|>
class Alina(Decoder):
decoder_name = "Alina"
decoder__version = 1
decoder_author = ["@botnet_hunter, @kevthehermit"]
<|code_end|>
. Write the next line using the current file imports:
from malwareconfig import crypto
from malwareconfig.common import Decoder
from malwareconfig.common import string_printable
and context from other files:
# Path: malwareconfig/crypto.py
# def decrypt_rsa(key, data):
# def decrypt_xor(key, data):
# def decrypt_arc4(key, data):
# def decrypt_des_ecb(key, data, iv=None):
# def decrypt_des_cbc(key, data, iv=None):
# def decrypt_des3(key, data):
# def decrypt_aes(key, data):
# def decrypt_aes_cbc_iv(key, iv, data):
# def decrypt_blowfish(key, data):
# def decrypt_RC6(key, encrypted, P, Q, rounds):
# def rol(a, i):
# def ror(a, i):
# def to_int(bytestring):
# def decrypt_block(block, S):
# def derive_pbkdf2(key, salt, iv_length, key_length, iterations=8):
# T = 2 * rounds + 4
# L = to_int(key)
# S = []
# S = [0 for i in range(T)]
# S[0] = P
# A = 0
# B = 0
# A = S[i] = rol((S[i] + A + B), 3)
# B = L[j] = rol((L[j] + A + B), (A + B))
#
# Path: malwareconfig/common.py
# class Decoder(object):
# decoder_name = ""
# decoder_version = 1
# decoder_author = ""
# decoder_description = ""
# file_info = object
#
# def set_file(self, file_info):
# self.file_info = file_info
#
# def get_config(self):
# pass
#
# Path: malwareconfig/common.py
# def string_printable(line):
# line = str(line)
# new_line = ''
# for c in line:
# if c in string.printable:
# new_line += c
# else:
# new_line += '\\x' + c.encode("utf-8").hex()
# return new_line
, which may include functions, classes, or code. Output only the next line. | decoder_description = "Point of sale malware designed to extract credit card information from RAM" |
Based on the snippet: <|code_start|>
def test_review(qtbot):
dlg = DlgReview('some content', 'log content', None, None)
assert dlg.ui.edit_main.toPlainText() == 'some content'
assert dlg.ui.edit_log.toPlainText() == 'log content'
qtbot.keyPress(dlg.ui.edit_main, 'A')
<|code_end|>
, predict the immediate next line with the help of imports:
from qcrash._dialogs.review import DlgReview
and context (classes, functions, sometimes code) from other files:
# Path: qcrash/_dialogs/review.py
# class DlgReview(QtWidgets.QDialog):
# """
# Dialog for reviewing the final report.
# """
# def __init__(self, content, log, parent, window_icon):
# """
# :param content: content of the final report, before review
# :param parent: parent widget
# """
# super(DlgReview, self).__init__(parent)
# self.ui = dlg_review_ui.Ui_Dialog()
# self.ui.setupUi(self)
# self.ui.tabWidget.setCurrentIndex(0)
# self.ui.edit_main.setPlainText(content)
# self.ui.edit_main.installEventFilter(self)
# self.ui.edit_log.installEventFilter(self)
# self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
# self.setWindowIcon(
# QtGui.QIcon.fromTheme('document-edit')
# if window_icon is None else window_icon)
# if log:
# self.ui.edit_log.setPlainText(log)
# else:
# self.ui.tabWidget.tabBar().hide()
# self.ui.edit_main.setFocus()
#
# def eventFilter(self, obj, event):
# interesting_objects = [self.ui.edit_log, self.ui.edit_main]
# if obj in interesting_objects and event.type() == QtCore.QEvent.KeyPress:
# if event.key() == QtCore.Qt.Key_Return and \
# event.modifiers() & QtCore.Qt.ControlModifier:
# self.accept()
# return True
# return False
#
# @classmethod
# def review(cls, content, log, parent, window_icon): # pragma: no cover
# """
# Reviews the final bug report.
#
# :param content: content of the final report, before review
# :param parent: parent widget
#
# :returns: the reviewed report content or None if the review was
# canceled.
# """
# dlg = DlgReview(content, log, parent, window_icon)
# if dlg.exec_():
# return dlg.ui.edit_main.toPlainText(), \
# dlg.ui.edit_log.toPlainText()
# return None, None
. Output only the next line. | assert dlg.ui.edit_main.toPlainText() == 'Asome content' |
Here is a snippet: <|code_start|>
def test_format_body():
description = 'A description'
traceback = 'A traceback'
<|code_end|>
. Write the next line using the current file imports:
from qcrash.formatters.markdown import MardownFormatter
and context from other files:
# Path: qcrash/formatters/markdown.py
# class MardownFormatter(BaseFormatter):
# """
# Formats the issue report using Markdown.
# """
# def format_body(self, description, sys_info=None, traceback=None):
# """
# Formats the body using markdown.
#
# :param description: Description of the issue, written by the user.
# :param sys_info: Optional system information string
# :param log: Optional application log
# :param traceback: Optional traceback.
# """
# body = BODY_ITEM_TEMPLATE % {
# 'name': 'Description', 'value': description
# }
# if traceback:
# traceback = '\n'.join(traceback.splitlines()[-NB_LINES_MAX:])
# body += BODY_ITEM_TEMPLATE % {
# 'name': 'Traceback', 'value': '```\n%s\n```' % traceback
# }
# if sys_info:
# sys_info = '- %s' % '\n- '.join(sys_info.splitlines())
# body += BODY_ITEM_TEMPLATE % {
# 'name': 'System information', 'value': sys_info
# }
# return body
, which may include functions, classes, or code. Output only the next line. | sys_info = '''OS: Linux |
Given the following code snippet before the placeholder: <|code_start|>
EMAIL = 'your.email@provider.com'
def get_backend():
return EmailBackend(EMAIL, 'TestQCrash')
<|code_end|>
, predict the next line using imports from the current file:
from qcrash.backends.email import EmailBackend
and context including class names, function names, and sometimes code from other files:
# Path: qcrash/backends/email.py
# class EmailBackend(BaseBackend):
# """
# This backend sends the crash report via email (using mailto).
#
# Usage::
#
# email_backend = qcrash.backends.EmailBackend(
# 'your_email@provider.com', 'YourAppName')
# qcrash.install_backend(email_backend)
#
# """
# def __init__(self, email, app_name, formatter=EmailFormatter()):
# """
# :param email: email address to send the bug report to
# :param app_name: application name, will appear in the object of the
# mail
# :param formatter: the formatter to use to create the final report.
# """
# super(EmailBackend, self).__init__(
# formatter, "Send email", "Send the report via email",
# QtGui.QIcon.fromTheme('mail-send'), need_review=False)
# self.formatter.app_name = app_name
# self.email = email
#
# def send_report(self, title, body, application_log=None):
# base_url = "mailto:%s?subject=%s" % (self.email, title)
# if application_log:
# body += "\nApplication log\n----------------\n\n%s" % application_log
# base_url += '&body=%s' % body
# url = QtCore.QUrl(base_url)
# QtGui.QDesktopServices.openUrl(url)
# return False
. Output only the next line. | def test_send_report(): |
Based on the snippet: <|code_start|>
def test_qsettings():
b = BaseBackend(None, '', '', None)
assert b.qsettings() is not None
def test_set_formatter():
b = BaseBackend(None, '', '', None)
<|code_end|>
, predict the immediate next line with the help of imports:
from qcrash.backends.base import BaseBackend
from qcrash.formatters.email import EmailFormatter
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: qcrash/backends/base.py
# class BaseBackend(object):
# """
# Base class for implementing a backend.
#
# Subclass must define ``button_text``, ``button_tooltip``and ``button_icon``
# and implement ``send_report(title, description)``.
#
# The report's title and body will be formatted automatically by the
# associated :attr:`formatter`.
# """
# def __init__(self, formatter, button_text, button_tooltip,
# button_icon=None, need_review=True):
# """
# :param formatter: the associated formatter (see :meth:`set_formatter`)
# :param button_text: Text of the associated button in the report dialog
# :param button_icon: Icon of the associated button in the report dialog
# :param button_tooltip: Tooltip of the associated button in the report
# dialog
# :param need_review: True to show the review dialog before submitting.
# Some backends (such as the email backend) do not need a review
# dialog as the user can already review it before sending the final
# report
# """
# self.formatter = formatter
# self.button_text = button_text
# self.button_tooltip = button_tooltip
# self.button_icon = button_icon
# self.need_review = need_review
# self.parent_widget = None
#
# def qsettings(self):
# """
# Gets the qsettings instance that you can use to store various settings
# such as the user credentials (you should use the `keyring` module if
# you want to store user's password).
# """
# from qcrash.api import _qsettings
# return _qsettings
#
# def set_formatter(self, formatter):
# """
# Sets the formatter associated with the backend.
#
# The formatter will automatically get called to format the report title
# and body before ``send_report`` is being called.
# """
# self.formatter = formatter
#
# def send_report(self, title, body, application_log=None):
# """
# Sends the actual bug report.
#
# :param title: title of the report, already formatted.
# :param body: body of the reporit, already formtatted.
# :param application_log: Content of the application log. Default is None.
#
# :returns: Whether the dialog should be closed.
# """
# raise NotImplementedError
#
# Path: qcrash/formatters/email.py
# class EmailFormatter(BaseFormatter):
# """
# Formats the crash report for use in an email (text/plain)
# """
# def __init__(self, app_name=None):
# """
# :param app_name: Name of the application. If set the email subject will
# starts with [app_name]
# """
# self.app_name = app_name
#
# def format_title(self, title):
# """
# Formats title (add ``[app_name]`` if app_name is not None).
# """
# if self.app_name:
# return '[%s] %s' % (self.app_name, title)
# return title
#
# def format_body(self, description, sys_info=None, traceback=None):
# """
# Formats the body in plain text. (add a series of '-' under each section
# title).
#
# :param description: Description of the issue, written by the user.
# :param sys_info: Optional system information string
# :param log: Optional application log
# :param traceback: Optional traceback.
# """
# name = 'Description'
# delim = '-' * 40
# body = BODY_ITEM_TEMPLATE % {
# 'name': name, 'value': description, 'delim': delim
# }
# if traceback:
# name = 'Traceback'
# traceback = '\n'.join(traceback.splitlines()[-NB_LINES_MAX:])
# body += BODY_ITEM_TEMPLATE % {
# 'name': name, 'value': traceback, 'delim': delim
# }
# if sys_info:
# name = 'System information'
# body += BODY_ITEM_TEMPLATE % {
# 'name': name, 'value': sys_info, 'delim': delim
# }
# return body
. Output only the next line. | assert b.formatter is None |
Next line prediction: <|code_start|>
def test_set_qsettings():
assert api._qsettings.organizationName() == 'QCrash'
api.set_qsettings(QtCore.QSettings('TestQCrash'))
assert api._qsettings.organizationName() == 'TestQCrash'
<|code_end|>
. Use current file imports:
(import sys
import pytest
from qcrash import api
from qcrash.qt import QtCore
from qcrash._hooks import QtExceptHook)
and context including class names, function names, or small code snippets from other files:
# Path: qcrash/api.py
# def install_backend(*args):
# def get_backends():
# def install_except_hook(except_hook=_hooks.except_hook):
# def set_qsettings(qsettings):
# def show_report_dialog(window_title='Report an issue...',
# window_icon=None, traceback=None, issue_title='',
# issue_description='', parent=None,
# modal=None, include_log=True, include_sys_info=True):
# def _return_empty_string():
#
# Path: qcrash/_hooks.py
# class QtExceptHook(QtCore.QObject):
# _report_exception_requested = Signal(object, object)
#
# def __init__(self, except_hook, *args, **kwargs):
# super(QtExceptHook, self).__init__(*args, **kwargs)
# sys.excepthook = self._except_hook
# self._report_exception_requested.connect(except_hook)
#
# def _except_hook(self, exc_type, exc_val, tb):
# tb = '\n'.join([''.join(traceback.format_tb(tb)),
# '{0}: {1}'.format(exc_type.__name__, exc_val)])
# _logger().critical('unhandled exception:\n%s', tb)
# # exception might come from another thread, use a signal
# # so that we can be sure we will show the bug report dialog from
# # the main gui thread.
# self._report_exception_requested.emit(exc_val, tb)
. Output only the next line. | def test_value_errors(): |
Here is a snippet: <|code_start|>
def test_set_qsettings():
assert api._qsettings.organizationName() == 'QCrash'
api.set_qsettings(QtCore.QSettings('TestQCrash'))
assert api._qsettings.organizationName() == 'TestQCrash'
<|code_end|>
. Write the next line using the current file imports:
import sys
import pytest
from qcrash import api
from qcrash.qt import QtCore
from qcrash._hooks import QtExceptHook
and context from other files:
# Path: qcrash/api.py
# def install_backend(*args):
# def get_backends():
# def install_except_hook(except_hook=_hooks.except_hook):
# def set_qsettings(qsettings):
# def show_report_dialog(window_title='Report an issue...',
# window_icon=None, traceback=None, issue_title='',
# issue_description='', parent=None,
# modal=None, include_log=True, include_sys_info=True):
# def _return_empty_string():
#
# Path: qcrash/_hooks.py
# class QtExceptHook(QtCore.QObject):
# _report_exception_requested = Signal(object, object)
#
# def __init__(self, except_hook, *args, **kwargs):
# super(QtExceptHook, self).__init__(*args, **kwargs)
# sys.excepthook = self._except_hook
# self._report_exception_requested.connect(except_hook)
#
# def _except_hook(self, exc_type, exc_val, tb):
# tb = '\n'.join([''.join(traceback.format_tb(tb)),
# '{0}: {1}'.format(exc_type.__name__, exc_val)])
# _logger().critical('unhandled exception:\n%s', tb)
# # exception might come from another thread, use a signal
# # so that we can be sure we will show the bug report dialog from
# # the main gui thread.
# self._report_exception_requested.emit(exc_val, tb)
, which may include functions, classes, or code. Output only the next line. | def test_value_errors(): |
Here is a snippet: <|code_start|>
def test_github_login_dialog():
dlg = DlgGitHubLogin(None, '', False, False)
assert not dlg.ui.bt_sign_in.isEnabled()
dlg.ui.le_username.setText('user')
dlg.ui.le_password.setText('password')
assert dlg.ui.cb_remember.isChecked() is False
assert dlg.ui.cb_remember_password.isChecked() is False
assert dlg.ui.cb_remember_password.isEnabled() is False
<|code_end|>
. Write the next line using the current file imports:
from qcrash._dialogs.gh_login import DlgGitHubLogin
and context from other files:
# Path: qcrash/_dialogs/gh_login.py
# class DlgGitHubLogin(QtWidgets.QDialog):
# HTML = '<html><head/><body><p align="center"><img src="%s"/></p>' \
# '<p align="center">Sign in to GitHub</p></body></html>'
#
# def __init__(self, parent, username, remember, remember_password):
# super(DlgGitHubLogin, self).__init__(parent)
# self.ui = dlg_github_login_ui.Ui_Dialog()
# self.ui.setupUi(self)
# self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
# self.ui.cb_remember.toggled.connect(
# self.ui.cb_remember_password.setEnabled)
#
# mark = GH_MARK_NORMAL
# if self.palette().base().color().lightness() < 128:
# mark = GH_MARK_LIGHT
# html = self.HTML % mark
# self.ui.lbl_html.setText(html)
# self.ui.bt_sign_in.clicked.connect(self.accept)
# self.ui.le_username.textChanged.connect(self.update_btn_state)
# self.ui.le_password.textChanged.connect(self.update_btn_state)
# self.ui.bt_sign_in.setDisabled(True)
# self.ui.le_username.setText(username)
# self.ui.cb_remember.setChecked(remember)
# self.ui.cb_remember_password.setChecked(remember_password)
# self.ui.cb_remember_password.setEnabled(remember)
# if username:
# self.ui.le_password.setFocus()
# else:
# self.ui.le_username.setFocus()
# self.adjustSize()
# self.setFixedSize(self.width(), self.height())
# self.ui.le_password.installEventFilter(self)
# self.ui.le_username.installEventFilter(self)
#
# def eventFilter(self, obj, event):
# interesting_objects = [self.ui.le_password, self.ui.le_username]
# if obj in interesting_objects and event.type() == QtCore.QEvent.KeyPress:
# if event.key() == QtCore.Qt.Key_Return and event.modifiers() & QtCore.Qt.ControlModifier and \
# self.ui.bt_sign_in.isEnabled():
# self.accept()
# return True
# return False
#
# def update_btn_state(self):
# enable = str(self.ui.le_username.text()).strip() != ''
# enable &= str(self.ui.le_password.text()).strip() != ''
# self.ui.bt_sign_in.setEnabled(enable)
#
# @classmethod
# def login(cls, parent, username, remember, remember_pswd): # pragma: no cover
# dlg = DlgGitHubLogin(parent, username, remember, remember_pswd)
# if dlg.exec_() == dlg.Accepted:
# return dlg.ui.le_username.text(), dlg.ui.le_password.text(), \
# dlg.ui.cb_remember.isChecked(), \
# dlg.ui.cb_remember_password.isEnabled() and dlg.ui.cb_remember_password.isChecked()
# return None, None, None, None
, which may include functions, classes, or code. Output only the next line. | assert dlg.ui.bt_sign_in.isEnabled() |
Next line prediction: <|code_start|>
def test_format_title():
title = 'test'
appname = 'TestQCrash'
expected = '[%s] %s' % (appname, title)
assert EmailFormatter(app_name=appname).format_title(title) == expected
assert EmailFormatter().format_title(title) == title
def test_format_body():
appname = 'TestQCrash'
<|code_end|>
. Use current file imports:
(from qcrash.formatters.email import EmailFormatter)
and context including class names, function names, or small code snippets from other files:
# Path: qcrash/formatters/email.py
# class EmailFormatter(BaseFormatter):
# """
# Formats the crash report for use in an email (text/plain)
# """
# def __init__(self, app_name=None):
# """
# :param app_name: Name of the application. If set the email subject will
# starts with [app_name]
# """
# self.app_name = app_name
#
# def format_title(self, title):
# """
# Formats title (add ``[app_name]`` if app_name is not None).
# """
# if self.app_name:
# return '[%s] %s' % (self.app_name, title)
# return title
#
# def format_body(self, description, sys_info=None, traceback=None):
# """
# Formats the body in plain text. (add a series of '-' under each section
# title).
#
# :param description: Description of the issue, written by the user.
# :param sys_info: Optional system information string
# :param log: Optional application log
# :param traceback: Optional traceback.
# """
# name = 'Description'
# delim = '-' * 40
# body = BODY_ITEM_TEMPLATE % {
# 'name': name, 'value': description, 'delim': delim
# }
# if traceback:
# name = 'Traceback'
# traceback = '\n'.join(traceback.splitlines()[-NB_LINES_MAX:])
# body += BODY_ITEM_TEMPLATE % {
# 'name': name, 'value': traceback, 'delim': delim
# }
# if sys_info:
# name = 'System information'
# body += BODY_ITEM_TEMPLATE % {
# 'name': name, 'value': sys_info, 'delim': delim
# }
# return body
. Output only the next line. | description = 'A description' |
Given the following code snippet before the placeholder: <|code_start|> }
''')
assert self.space.int_w(w_res) == 13
def test_simple_args(self):
w_res = self.interpret('''
def foo(a, b) {
return a + b
}
def main() {
return foo(10, 3)
}
''')
assert self.space.int_w(w_res) == 13
def test_named_args(self):
w_res = self.interpret('''
def foo(a, b) {
return a * 10 + b
}
def main() {
return foo(a=2, b=3)
}
''')
assert self.space.int_w(w_res) == 23
w_res = self.interpret('''
def foo(a, b) {
<|code_end|>
, predict the next line using imports from the current file:
from nolang.error import AppError
from support import BaseTest
and context including class names, function names, and sometimes code from other files:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
. Output only the next line. | return a * 10 + b |
Next line prediction: <|code_start|>
class W_BoolObject(W_Root):
def __init__(self, boolval):
self._boolval = boolval
def is_true(self, space):
<|code_end|>
. Use current file imports:
(from nolang.objects.root import W_Root)
and context including class names, function names, or small code snippets from other files:
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
. Output only the next line. | return self._boolval |
Given snippet: <|code_start|>
class TestClasses(BaseTest):
def test_simple_class(self):
w_res = self.interpret('''
class X {
def __init__(self) {
self.x = 13
}
}
def main() {
let x
x = X()
return x.x
}
''')
assert self.space.int_w(w_res) == 13
def test_method_call(self):
w_res = self.interpret('''
class X {
def method(self) {
return 3
}
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from support import BaseTest
from nolang.error import AppError
and context:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
which might include code, classes, or functions. Output only the next line. | } |
Continue the code snippet: <|code_start|> def setitem(self, space, w_index, w_value):
self._items_w[self.unwrap_index(space, w_index)] = w_value
def iter(self, space):
return W_ListIterator(self)
def append(self, space, w_obj):
self._items_w.append(w_obj)
def extend(self, space, w_other):
self._items_w.extend(space.listview(w_other))
@unwrap_spec(items_w='list')
def allocate(space, w_tp, items_w):
return space.newlist(items_w)
W_ListObject.spec = TypeSpec(
'List',
constructor=allocate,
methods={
'append': W_ListObject.append,
'extend': W_ListObject.extend,
},
properties={},
)
class W_ListIterator(W_Root):
<|code_end|>
. Use current file imports:
from nolang.error import AppError
from nolang.objects.root import W_Root
from nolang.builtins.spec import unwrap_spec, TypeSpec
and context (classes, functions, or code) from other files:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
. Output only the next line. | def __init__(self, w_list): |
Using the snippet: <|code_start|> def listview(self, space):
return self._items_w
def len(self, space):
return len(self._items_w)
def contains(self, space, w_obj):
for w_item in self._items_w:
if space.binop_eq(w_obj, w_item):
return True
return False
def unwrap_index(self, space, w_index):
try:
i = space.int_w(w_index)
except AppError as ae:
if ae.match(space, space.w_typeerror):
raise space.apperr(space.w_typeerror, 'list index must be int')
raise
if i < 0 or i >= len(self._items_w):
raise space.apperr(space.w_indexerror, 'list index out of range')
return i
def getitem(self, space, w_index):
return self._items_w[self.unwrap_index(space, w_index)]
def setitem(self, space, w_index, w_value):
self._items_w[self.unwrap_index(space, w_index)] = w_value
def iter(self, space):
<|code_end|>
, determine the next line of code. You have imports:
from nolang.error import AppError
from nolang.objects.root import W_Root
from nolang.builtins.spec import unwrap_spec, TypeSpec
and context (class names, function names, or code) available:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
. Output only the next line. | return W_ListIterator(self) |
Given snippet: <|code_start|>
class W_ListObject(W_Root):
def __init__(self, items_w):
self._items_w = items_w[:]
def str(self, space):
return '[' + ', '.join([space.str(i) for i in self._items_w]) + ']'
def listview(self, space):
return self._items_w
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from nolang.error import AppError
from nolang.objects.root import W_Root
from nolang.builtins.spec import unwrap_spec, TypeSpec
and context:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
which might include code, classes, or functions. Output only the next line. | def len(self, space): |
Predict the next line after this snippet: <|code_start|>
def str(self, space):
return '[' + ', '.join([space.str(i) for i in self._items_w]) + ']'
def listview(self, space):
return self._items_w
def len(self, space):
return len(self._items_w)
def contains(self, space, w_obj):
for w_item in self._items_w:
if space.binop_eq(w_obj, w_item):
return True
return False
def unwrap_index(self, space, w_index):
try:
i = space.int_w(w_index)
except AppError as ae:
if ae.match(space, space.w_typeerror):
raise space.apperr(space.w_typeerror, 'list index must be int')
raise
if i < 0 or i >= len(self._items_w):
raise space.apperr(space.w_indexerror, 'list index out of range')
return i
def getitem(self, space, w_index):
return self._items_w[self.unwrap_index(space, w_index)]
<|code_end|>
using the current file's imports:
from nolang.error import AppError
from nolang.objects.root import W_Root
from nolang.builtins.spec import unwrap_spec, TypeSpec
and any relevant context from other files:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
. Output only the next line. | def setitem(self, space, w_index, w_value): |
Continue the code snippet: <|code_start|>
class W_FrameWrapper(W_Root):
def __init__(self, frameref):
self.frameref = frameref
def get_filename(self, space):
return space.newtext(self.frameref.bytecode.filename)
W_FrameWrapper.spec = TypeSpec(
<|code_end|>
. Use current file imports:
from nolang.objects.root import W_Root
from nolang.builtins.spec import TypeSpec
and context (classes, functions, or code) from other files:
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# Path: nolang/builtins/spec.py
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
. Output only the next line. | 'Frame', |
Here is a snippet: <|code_start|>
class W_FrameWrapper(W_Root):
def __init__(self, frameref):
self.frameref = frameref
def get_filename(self, space):
return space.newtext(self.frameref.bytecode.filename)
W_FrameWrapper.spec = TypeSpec(
'Frame',
constructor=None,
methods={},
properties={
'filename': (W_FrameWrapper.get_filename, None)
<|code_end|>
. Write the next line using the current file imports:
from nolang.objects.root import W_Root
from nolang.builtins.spec import TypeSpec
and context from other files:
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# Path: nolang/builtins/spec.py
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
, which may include functions, classes, or code. Output only the next line. | } |
Given snippet: <|code_start|>
class W_Exception(W_UserObject):
def __init__(self, w_tp, message):
W_UserObject.__init__(self, w_tp)
self.message = message
def get_message(self, space):
return space.newtext(self.message)
def __repr__(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from nolang.builtins.spec import unwrap_spec, TypeSpec
from nolang.objects.userobject import W_UserObject
and context:
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# Path: nolang/objects/userobject.py
# class W_UserObject(W_Root):
# def __init__(self, w_type):
# self.w_type = w_type
# self._dict_w = {}
#
# def gettype(self, space):
# return self.w_type
#
# def setattr(self, space, attrname, w_val):
# if self.w_type.force_names is not None:
# if attrname not in self.w_type.force_names:
# msg = '%s is not an allowed attribute of object of class %s' % (
# attrname, self.w_type.name)
# raise space.apperr(space.w_attrerror, msg)
# self._dict_w[attrname] = w_val
#
# def getattr(self, space, attrname):
# try:
# return self._dict_w[attrname]
# except KeyError:
# return space.w_NotImplemented
which might include code, classes, or functions. Output only the next line. | return '<%s %s>' % (self.w_type.name, self.message) |
Predict the next line after this snippet: <|code_start|>
class W_Exception(W_UserObject):
def __init__(self, w_tp, message):
W_UserObject.__init__(self, w_tp)
self.message = message
def get_message(self, space):
return space.newtext(self.message)
def __repr__(self):
return '<%s %s>' % (self.w_type.name, self.message)
@unwrap_spec(msg='utf8')
def allocate(space, w_tp, msg):
return W_Exception(w_tp, msg)
W_Exception.spec = TypeSpec('Exception',
constructor=allocate,
methods={
},
properties={
<|code_end|>
using the current file's imports:
from nolang.builtins.spec import unwrap_spec, TypeSpec
from nolang.objects.userobject import W_UserObject
and any relevant context from other files:
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# Path: nolang/objects/userobject.py
# class W_UserObject(W_Root):
# def __init__(self, w_type):
# self.w_type = w_type
# self._dict_w = {}
#
# def gettype(self, space):
# return self.w_type
#
# def setattr(self, space, attrname, w_val):
# if self.w_type.force_names is not None:
# if attrname not in self.w_type.force_names:
# msg = '%s is not an allowed attribute of object of class %s' % (
# attrname, self.w_type.name)
# raise space.apperr(space.w_attrerror, msg)
# self._dict_w[attrname] = w_val
#
# def getattr(self, space, attrname):
# try:
# return self._dict_w[attrname]
# except KeyError:
# return space.w_NotImplemented
. Output only the next line. | 'message': (W_Exception.get_message, None) |
Next line prediction: <|code_start|>
class W_Exception(W_UserObject):
def __init__(self, w_tp, message):
W_UserObject.__init__(self, w_tp)
self.message = message
<|code_end|>
. Use current file imports:
(from nolang.builtins.spec import unwrap_spec, TypeSpec
from nolang.objects.userobject import W_UserObject)
and context including class names, function names, or small code snippets from other files:
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# Path: nolang/objects/userobject.py
# class W_UserObject(W_Root):
# def __init__(self, w_type):
# self.w_type = w_type
# self._dict_w = {}
#
# def gettype(self, space):
# return self.w_type
#
# def setattr(self, space, attrname, w_val):
# if self.w_type.force_names is not None:
# if attrname not in self.w_type.force_names:
# msg = '%s is not an allowed attribute of object of class %s' % (
# attrname, self.w_type.name)
# raise space.apperr(space.w_attrerror, msg)
# self._dict_w[attrname] = w_val
#
# def getattr(self, space, attrname):
# try:
# return self._dict_w[attrname]
# except KeyError:
# return space.w_NotImplemented
. Output only the next line. | def get_message(self, space): |
Based on the snippet: <|code_start|>
def utf8_w(self, space):
return self.utf8val
def str(self, space):
return self.utf8_w(space)
def len(self, space):
if self.lgt == -1:
# XXX compute it better once utf8 lands
self.lgt = len(self.utf8val.decode('utf-8'))
return self.lgt
def hash(self, space):
return compute_hash(self.utf8val)
def eq(self, space, w_other):
try:
other = space.utf8_w(w_other)
except AppError as ae:
if space.type(ae.w_exception) is space.w_typeerror:
raise NotImplementedOp
raise
return self.utf8val == other
def is_frozen(self, space):
return True
@unwrap_spec(value='utf8')
<|code_end|>
, predict the immediate next line with the help of imports:
from rpython.rlib.objectmodel import compute_hash
from nolang.error import AppError
from nolang.objects.root import W_Root, NotImplementedOp
from nolang.builtins.spec import TypeSpec, unwrap_spec
and context (classes, functions, sometimes code) from other files:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# class NotImplementedOp(Exception):
# pass
#
# Path: nolang/builtins/spec.py
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
. Output only the next line. | def new_str(space, value): |
Here is a snippet: <|code_start|>
class W_StrObject(W_Root):
def __init__(self, utf8val, lgt=-1):
assert isinstance(utf8val, str)
self.utf8val = utf8val
<|code_end|>
. Write the next line using the current file imports:
from rpython.rlib.objectmodel import compute_hash
from nolang.error import AppError
from nolang.objects.root import W_Root, NotImplementedOp
from nolang.builtins.spec import TypeSpec, unwrap_spec
and context from other files:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# class NotImplementedOp(Exception):
# pass
#
# Path: nolang/builtins/spec.py
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
, which may include functions, classes, or code. Output only the next line. | self.lgt = lgt |
Given the code snippet: <|code_start|>
class W_StrObject(W_Root):
def __init__(self, utf8val, lgt=-1):
assert isinstance(utf8val, str)
self.utf8val = utf8val
self.lgt = lgt
def utf8_w(self, space):
return self.utf8val
def str(self, space):
return self.utf8_w(space)
def len(self, space):
if self.lgt == -1:
# XXX compute it better once utf8 lands
self.lgt = len(self.utf8val.decode('utf-8'))
return self.lgt
def hash(self, space):
<|code_end|>
, generate the next line using the imports in this file:
from rpython.rlib.objectmodel import compute_hash
from nolang.error import AppError
from nolang.objects.root import W_Root, NotImplementedOp
from nolang.builtins.spec import TypeSpec, unwrap_spec
and context (functions, classes, or occasionally code) from other files:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# class NotImplementedOp(Exception):
# pass
#
# Path: nolang/builtins/spec.py
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
. Output only the next line. | return compute_hash(self.utf8val) |
Predict the next line for this snippet: <|code_start|> w_ls = self.space.listview(w_res)
assert [self.space.int_w(w) for w in w_ls] == [0, 1, 2, 3]
def test_merge(self):
w_res = self.interpret_expr('''
let a, b, ab;
a = {"a": "foo", 1: "bar"};
b = {"b": "baz", 1: "rab"};
ab = a.merge(b);
return [a, b, ab];
''')
space = self.space
[w_a, w_b, w_ab] = space.listview(w_res)
# a and b are unmodified
assert space.len(w_a) == 2
assert space.utf8_w(space.getitem(w_a, space.newtext("a"))) == "foo"
assert space.utf8_w(space.getitem(w_a, space.newint(1))) == "bar"
assert space.len(w_b) == 2
assert space.utf8_w(space.getitem(w_b, space.newtext("b"))) == "baz"
assert space.utf8_w(space.getitem(w_b, space.newint(1))) == "rab"
# ab is the merged output
assert space.len(w_ab) == 3
assert space.utf8_w(space.getitem(w_ab, space.newtext("a"))) == "foo"
assert space.utf8_w(space.getitem(w_ab, space.newtext("b"))) == "baz"
assert space.utf8_w(space.getitem(w_ab, space.newint(1))) == "rab"
def test_pop(self):
w_res = self.interpret_expr('''
let a;
a = {"a": "foo", 1: "bar"};
<|code_end|>
with the help of current file imports:
from nolang.error import AppError
from support import BaseTest
and context from other files:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
, which may contain function names, class names, or code. Output only the next line. | return [a.pop(1), a]; |
Predict the next line after this snippet: <|code_start|>
class Frame(W_Root):
def __init__(self, bytecode, name=None):
self.name = name
self.bytecode = bytecode
if bytecode.module is not None: # for tests
self.globals_w = bytecode.module.functions
self.locals_w = [None] * len(bytecode.varnames)
self.stack_w = [None] * bytecode.stack_depth
self.resume_stack = [0] * bytecode.resume_stack_depth
self.resume_stack_depth = 0
self.pos = 0
def populate_args(self, args_w):
for i in range(len(args_w)):
self.locals_w[i] = args_w[i]
<|code_end|>
using the current file's imports:
from nolang.objects.root import W_Root
and any relevant context from other files:
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
. Output only the next line. | def push(self, w_val): |
Given the code snippet: <|code_start|>
class W_DictObject(W_Root):
def __init__(self, key_eq, key_hash, items_w):
self._items_w = r_dict(key_eq, key_hash)
for k, v in items_w:
self._items_w[k] = v
def str(self, space):
return '{' + ', '.join([space.str(k) + ': ' + space.str(v)
for k, v in self._items_w.items()]) + '}'
def dictview(self, space):
return self._items_w
def len(self, space):
return len(self._items_w)
def contains(self, space, w_obj):
return w_obj in self._items_w
def getitem(self, space, w_key):
if w_key not in self._items_w:
raise space.apperr(space.w_keyerror, space.str(w_key))
return self._items_w[w_key]
<|code_end|>
, generate the next line using the imports in this file:
from rpython.rlib.objectmodel import r_dict
from nolang.builtins.spec import unwrap_spec, TypeSpec
from nolang.objects.root import W_Root
and context (functions, classes, or occasionally code) from other files:
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
. Output only the next line. | def get(self, space, w_key, w_default=None): |
Predict the next line for this snippet: <|code_start|> return self._items_w[w_key]
def get(self, space, w_key, w_default=None):
if w_key not in self._items_w:
return w_default
return self._items_w[w_key]
def dict_pop(self, space, w_key):
if w_key not in self._items_w:
raise space.apperr(space.w_keyerror, space.str(w_key))
return self._items_w.pop(w_key)
def setitem(self, space, w_key, w_value):
self._items_w[w_key] = w_value
def merge(self, space, w_other):
other_w = space.dictview(w_other)
w_res = space.newdict([])
w_res._items_w.update(self._items_w)
w_res._items_w.update(other_w)
return w_res
def keys(self, space):
return space.newlist(self._items_w.keys())
def values(self, space):
return space.newlist(self._items_w.values())
@unwrap_spec(items_w='dict')
<|code_end|>
with the help of current file imports:
from rpython.rlib.objectmodel import r_dict
from nolang.builtins.spec import unwrap_spec, TypeSpec
from nolang.objects.root import W_Root
and context from other files:
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
, which may contain function names, class names, or code. Output only the next line. | def allocate(space, w_tp, items_w): |
Predict the next line for this snippet: <|code_start|>
def setitem(self, space, w_key, w_value):
self._items_w[w_key] = w_value
def merge(self, space, w_other):
other_w = space.dictview(w_other)
w_res = space.newdict([])
w_res._items_w.update(self._items_w)
w_res._items_w.update(other_w)
return w_res
def keys(self, space):
return space.newlist(self._items_w.keys())
def values(self, space):
return space.newlist(self._items_w.values())
@unwrap_spec(items_w='dict')
def allocate(space, w_tp, items_w):
w_res = space.newdict([])
w_res._items_w.update(items_w)
return w_res
W_DictObject.spec = TypeSpec(
'Dict',
constructor=allocate,
methods={
'merge': W_DictObject.merge,
<|code_end|>
with the help of current file imports:
from rpython.rlib.objectmodel import r_dict
from nolang.builtins.spec import unwrap_spec, TypeSpec
from nolang.objects.root import W_Root
and context from other files:
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
, which may contain function names, class names, or code. Output only the next line. | 'get': W_DictObject.get, |
Predict the next line for this snippet: <|code_start|> x = ["foo"];
x.append("bar");
return x;
''')
space = self.space
assert space.len(w_res) == 2
assert space.utf8_w(space.getitem(w_res, space.newint(1))) == "bar"
def test_extend(self):
w_res = self.interpret_expr('''
let x;
x = ["a", "b"];
x.extend(["c", "d"]);
return x;
''')
list_w = self.space.listview(w_res)
assert [self.space.utf8_w(w) for w in list_w] == ["a", "b", "c", "d"]
def test_extend_nonlist(self):
try:
self.interpret_expr('["a", "b"].extend("c");')
except AppError as ae:
assert ae.match(self.space, self.space.w_typeerror)
assert ae.w_exception.message == 'expected list'
else:
raise Exception("Applevel TypeError not raised.")
def test_method_call_on_wrong_obj(self):
try:
self.interpret_expr('''
<|code_end|>
with the help of current file imports:
from nolang.error import AppError
from support import BaseTest
and context from other files:
# Path: nolang/error.py
# class AppError(Exception):
# def __init__(self, w_exception):
# self.w_exception = w_exception
# self.traceback = None
#
# def record_position(self, frame, bytecode, index):
# self.traceback = TracebackElem(frame, index, bytecode, self.traceback)
#
# def match(self, space, w_expected):
# return space.issubclass(space.type(self.w_exception), w_expected)
#
# def __repr__(self):
# return '<AppError %r>' % (self.w_exception,)
# __str__ = __repr__
, which may contain function names, class names, or code. Output only the next line. | List.append(1, 2) |
Continue the code snippet: <|code_start|>
@unwrap_spec()
def len(space, w_obj):
return space.newint(space.len(w_obj))
@parameters(name='isinstance')
def builtin_isinstance(space, w_obj, w_type):
if not isinstance(w_type, W_UserType):
# typename = space.type(w_type).name
# XXX improve the error message
raise space.apperr(space.w_typeerror, "isinstance right argument is "
"not a type")
return space.newbool(space.isinstance(w_obj, w_type))
@parameters(name='str')
def builtin_str(space, w_obj):
<|code_end|>
. Use current file imports:
from nolang.builtins.spec import unwrap_spec, parameters
from nolang.objects.usertype import W_UserType
and context (classes, functions, or code) from other files:
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# def parameters(**args):
# def wrapper(func):
# func.unwrap_parameters = args
# return func
# return wrapper
#
# Path: nolang/objects/usertype.py
# class W_UserType(W_Root):
# def __init__(self, allocate, name, class_elements_w, w_parent,
# default_alloc=True, force_names=None):
# self.name = name
# self.allocate = allocate
# self.class_elements_w = class_elements_w
# self.default_alloc = default_alloc
# if w_parent is not None:
# self._dict_w = w_parent._dict_w.copy()
# else:
# self._dict_w = {}
# for item in class_elements_w:
# self._dict_w[item.name] = item
# self.w_parent = w_parent
# if force_names is None:
# self.force_names = None
# else:
# self.force_names = {}
# for elem in force_names:
# self.force_names[elem] = None
#
# def setup(self, space):
# for item in self.class_elements_w:
# item.setup(space)
#
# def call(self, space, interpreter, args_w, kwargs):
# if self.allocate is None:
# raise Exception("cannot be called like that")
# w_obj = space.call(self.allocate, [self] + args_w, kwargs)
# if '__init__' in self._dict_w:
# space.call(self._dict_w['__init__'], [w_obj] + args_w, kwargs)
# elif self.default_alloc:
# if len(args_w) != 0:
# raise space.apperr(space.w_argerror, "Default constructor"
# " expecting no arguments")
# return w_obj
#
# def getattr(self, space, attrname):
# try:
# return self._dict_w[attrname]
# except KeyError:
# return space.w_NotImplemented
#
# def issubclass(self, w_type):
# cur = self
# while cur is not None:
# if cur is w_type:
# return True
# cur = cur.w_parent
# return False
#
# def __repr__(self):
# return "<UserType %s>" % (self.name,)
. Output only the next line. | return space.newtext(space.str(w_obj)) |
Given the code snippet: <|code_start|>
@unwrap_spec()
def len(space, w_obj):
return space.newint(space.len(w_obj))
@parameters(name='isinstance')
<|code_end|>
, generate the next line using the imports in this file:
from nolang.builtins.spec import unwrap_spec, parameters
from nolang.objects.usertype import W_UserType
and context (functions, classes, or occasionally code) from other files:
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# def parameters(**args):
# def wrapper(func):
# func.unwrap_parameters = args
# return func
# return wrapper
#
# Path: nolang/objects/usertype.py
# class W_UserType(W_Root):
# def __init__(self, allocate, name, class_elements_w, w_parent,
# default_alloc=True, force_names=None):
# self.name = name
# self.allocate = allocate
# self.class_elements_w = class_elements_w
# self.default_alloc = default_alloc
# if w_parent is not None:
# self._dict_w = w_parent._dict_w.copy()
# else:
# self._dict_w = {}
# for item in class_elements_w:
# self._dict_w[item.name] = item
# self.w_parent = w_parent
# if force_names is None:
# self.force_names = None
# else:
# self.force_names = {}
# for elem in force_names:
# self.force_names[elem] = None
#
# def setup(self, space):
# for item in self.class_elements_w:
# item.setup(space)
#
# def call(self, space, interpreter, args_w, kwargs):
# if self.allocate is None:
# raise Exception("cannot be called like that")
# w_obj = space.call(self.allocate, [self] + args_w, kwargs)
# if '__init__' in self._dict_w:
# space.call(self._dict_w['__init__'], [w_obj] + args_w, kwargs)
# elif self.default_alloc:
# if len(args_w) != 0:
# raise space.apperr(space.w_argerror, "Default constructor"
# " expecting no arguments")
# return w_obj
#
# def getattr(self, space, attrname):
# try:
# return self._dict_w[attrname]
# except KeyError:
# return space.w_NotImplemented
#
# def issubclass(self, w_type):
# cur = self
# while cur is not None:
# if cur is w_type:
# return True
# cur = cur.w_parent
# return False
#
# def __repr__(self):
# return "<UserType %s>" % (self.name,)
. Output only the next line. | def builtin_isinstance(space, w_obj, w_type): |
Using the snippet: <|code_start|>
@unwrap_spec()
def len(space, w_obj):
return space.newint(space.len(w_obj))
@parameters(name='isinstance')
<|code_end|>
, determine the next line of code. You have imports:
from nolang.builtins.spec import unwrap_spec, parameters
from nolang.objects.usertype import W_UserType
and context (class names, function names, or code) available:
# Path: nolang/builtins/spec.py
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
#
# def parameters(**args):
# def wrapper(func):
# func.unwrap_parameters = args
# return func
# return wrapper
#
# Path: nolang/objects/usertype.py
# class W_UserType(W_Root):
# def __init__(self, allocate, name, class_elements_w, w_parent,
# default_alloc=True, force_names=None):
# self.name = name
# self.allocate = allocate
# self.class_elements_w = class_elements_w
# self.default_alloc = default_alloc
# if w_parent is not None:
# self._dict_w = w_parent._dict_w.copy()
# else:
# self._dict_w = {}
# for item in class_elements_w:
# self._dict_w[item.name] = item
# self.w_parent = w_parent
# if force_names is None:
# self.force_names = None
# else:
# self.force_names = {}
# for elem in force_names:
# self.force_names[elem] = None
#
# def setup(self, space):
# for item in self.class_elements_w:
# item.setup(space)
#
# def call(self, space, interpreter, args_w, kwargs):
# if self.allocate is None:
# raise Exception("cannot be called like that")
# w_obj = space.call(self.allocate, [self] + args_w, kwargs)
# if '__init__' in self._dict_w:
# space.call(self._dict_w['__init__'], [w_obj] + args_w, kwargs)
# elif self.default_alloc:
# if len(args_w) != 0:
# raise space.apperr(space.w_argerror, "Default constructor"
# " expecting no arguments")
# return w_obj
#
# def getattr(self, space, attrname):
# try:
# return self._dict_w[attrname]
# except KeyError:
# return space.w_NotImplemented
#
# def issubclass(self, w_type):
# cur = self
# while cur is not None:
# if cur is w_type:
# return True
# cur = cur.w_parent
# return False
#
# def __repr__(self):
# return "<UserType %s>" % (self.name,)
. Output only the next line. | def builtin_isinstance(space, w_obj, w_type): |
Given snippet: <|code_start|>
class TestMain(object):
def test_main(self, tmpdir):
fname = tmpdir.join("foo.q")
fname.write(reformat_code("""
def main() {
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from support import reformat_code
from nolang.main import main
and context:
# Path: nolang/main.py
# def main(argv):
# if len(argv) != 2:
# print __doc__
# return 1
# return run_code(argv[1])
which might include code, classes, or functions. Output only the next line. | print(3); |
Given the code snippet: <|code_start|>
class W_StringBuilder(W_Root):
def __init__(self, length):
self._s = StringBuilder(length)
@unwrap_spec(txt='utf8')
def append(self, txt):
self._s.append(txt)
def build(self, space):
return space.newtext(self._s.build())
@unwrap_spec(length='int')
def new_stringbuilder(space, w_tp, length=0):
return W_StringBuilder(length)
W_StringBuilder.spec = TypeSpec(
'StringBuilder',
methods={
'append': W_StringBuilder.append,
<|code_end|>
, generate the next line using the imports in this file:
from rpython.rlib.rstring import StringBuilder
from nolang.objects.root import W_Root
from nolang.builtins.spec import TypeSpec, unwrap_spec
and context (functions, classes, or occasionally code) from other files:
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# Path: nolang/builtins/spec.py
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
. Output only the next line. | 'build': W_StringBuilder.build, |
Continue the code snippet: <|code_start|>
class W_StringBuilder(W_Root):
def __init__(self, length):
self._s = StringBuilder(length)
@unwrap_spec(txt='utf8')
def append(self, txt):
self._s.append(txt)
def build(self, space):
<|code_end|>
. Use current file imports:
from rpython.rlib.rstring import StringBuilder
from nolang.objects.root import W_Root
from nolang.builtins.spec import TypeSpec, unwrap_spec
and context (classes, functions, or code) from other files:
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# Path: nolang/builtins/spec.py
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
. Output only the next line. | return space.newtext(self._s.build()) |
Here is a snippet: <|code_start|>
class W_StringBuilder(W_Root):
def __init__(self, length):
self._s = StringBuilder(length)
@unwrap_spec(txt='utf8')
def append(self, txt):
self._s.append(txt)
<|code_end|>
. Write the next line using the current file imports:
from rpython.rlib.rstring import StringBuilder
from nolang.objects.root import W_Root
from nolang.builtins.spec import TypeSpec, unwrap_spec
and context from other files:
# Path: nolang/objects/root.py
# class W_Root(object):
# cls_w_type = None
#
# def int_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected integer')
#
# def utf8_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected string')
#
# def buffer_w(self, space):
# raise space.apperr(space.w_typeerror, 'expected buffer')
#
# def listview(self, space):
# raise space.apperr(space.w_typeerror, 'expected list')
#
# def dictview(self, space):
# raise space.apperr(space.w_typeerror, 'expected dict')
#
# def hash(self, space):
# raise space.apperr(space.w_typeerror, 'unhashable type')
#
# def iter(self, space):
# raise space.apperr(space.w_typeerror, 'uniterable type')
#
# def iter_next(self, space):
# raise space.apperr(space.w_typeerror, 'object not an iterator')
#
# def getattr(self, space, attrname):
# return space.w_NotImplemented
#
# def bind(self, space, w_obj):
# return self
#
# def gettype(self, space):
# return self.cls_w_type
#
# def str(self, space):
# raise space.apperr(space.w_typeerror,
# 'object cannot be converted to str')
#
# def len(self, space):
# raise space.apperr(space.w_typeerror, 'unsized type')
#
# def is_true(self, space):
# return True
#
# def lt(self, space, w_obj):
# raise space.apperr(space.w_typeerror, 'object not comparable')
#
# def eq(self, space, w_other):
# if self is w_other:
# return True
# if space.type(self) is not space.type(w_other):
# raise NotImplementedOp
# return False
#
# def add(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `+`')
#
# def sub(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `-`')
#
# def mul(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `*`')
#
# def truediv(self, space, w_other):
# raise space.apperr(space.w_typeerror, 'no implementation for `/`')
#
# def call(self, space, interpreter, args, kwargs):
# raise space.apperr(space.w_typeerror, 'object is not callable')
#
# def freeze(self, space):
# if self.is_frozen(space):
# return
# raise space.apperr(space.w_freezeerror, 'object not freezable')
#
# def thaw(self, space):
# raise space.apperr(space.w_freezeerror, 'object does not know '
# 'how to thaw, this should be an internal error')
#
# def is_frozen(self, space):
# return False
#
# Path: nolang/builtins/spec.py
# class TypeSpec(object):
# def __init__(self, name, constructor, methods=None, properties=None,
# parent_name=None, is_subclassable=False):
# self.constructor = constructor
# self.name = name
# if methods is None:
# methods = {}
# self.methods = methods
# if properties is None:
# properties = {}
# self.properties = properties
# self.parent_name = parent_name
# self.is_subclassable = is_subclassable
#
# def unwrap_spec(**spec):
# def wrapper(func):
# func.unwrap_spec = spec
# return func
# return wrapper
, which may include functions, classes, or code. Output only the next line. | def build(self, space): |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
if 'DJANGO_TEST' in os.environ:
else: # pragma: no cover
PAGES_COLORS = {
"A": "green", "B": "deep-orange", "C": "blue-grey", "D": "brown",
"E": "lime", "F": "light-blue", "G": "teal", "H": "deep-purple",
"I": "indigo", "J": "red"
}
USERS = getattr(settings, "DJANGO_AI_EXAMPLES_USERINFO_SIZE", 200)
def another_page(besides):
<|code_end|>
, predict the next line using imports from the current file:
import os
import random
import math
import json
from django.shortcuts import (render, redirect, )
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.db.models import Avg
from django.views.generic import CreateView
from django.urls import reverse_lazy
from .models import (UserInfo, CommentOfMySite, )
from .forms import (CommentOfMySiteForm, )
from django_ai.bayesian_networks.models import BayesianNetwork
from django_ai.systems.spam_filtering.models import SpamFilter
from django_ai.examples import metrics
from bayesian_networks.models import BayesianNetwork
from systems.spam_filtering.models import SpamFilter
from examples import metrics
and context including class names, function names, and sometimes code from other files:
# Path: django_ai/examples/models.py
# class UserInfo(models.Model):
# """
# Example User Information Model
# """
# SEX_CHOICES = [(0, "M"), (1, "F")]
#
# age = models.IntegerField("Age")
# sex = models.SmallIntegerField("Sex", choices=SEX_CHOICES,
# blank=True, null=True)
# # -> Metrics
# avg1 = models.FloatField("Average 1", blank=True, null=True)
# avg_time_pages = models.FloatField("Average Time on Pages",
# default=0, blank=True, null=True)
# visits_pages = models.IntegerField("Visits on Pages (Total)",
# default=0)
# avg_time_pages_a = models.FloatField("Average Time on Pages of type A",
# default=0, blank=True, null=True)
# visits_pages_a = models.IntegerField("Visits on Pages of type A",
# default=0)
# avg_time_pages_b = models.FloatField("Average Time on Pages of type B",
# default=0, blank=True, null=True)
# visits_pages_b = models.IntegerField("Visits on Pages of type B",
# default=0)
# avg_time_pages_c = models.FloatField("Average Time on Pages of type C",
# default=0, blank=True, null=True)
# visits_pages_c = models.IntegerField("Visits on Pages of type C",
# default=0)
# avg_time_pages_d = models.FloatField("Average Time on Pages of type D",
# default=0, blank=True, null=True)
# visits_pages_d = models.IntegerField("Visits on Pages of type D",
# default=0)
# avg_time_pages_e = models.FloatField("Average Time on Pages of type E",
# default=0, blank=True, null=True)
# visits_pages_e = models.IntegerField("Visits on Pages of type E",
# default=0)
# avg_time_pages_f = models.FloatField("Average Time on Pages of type F",
# default=0, blank=True, null=True)
# visits_pages_f = models.IntegerField("Visits on Pages of type F",
# default=0)
# avg_time_pages_g = models.FloatField("Average Time on Pages of type G",
# default=0, blank=True, null=True)
# visits_pages_g = models.IntegerField("Visits on Pages of type G",
# default=0)
# avg_time_pages_h = models.FloatField("Average Time on Pages of type H",
# default=0, blank=True, null=True)
# visits_pages_h = models.IntegerField("Visits on Pages of type H",
# default=0)
# avg_time_pages_i = models.FloatField("Average Time on Pages of type I",
# default=0, blank=True, null=True)
# visits_pages_i = models.IntegerField("Visits on Pages of type I",
# default=0)
# avg_time_pages_j = models.FloatField("Average Time on Pages of type J",
# default=0, blank=True, null=True)
# visits_pages_j = models.IntegerField("Visits on Pages of type J",
# default=0)
# # -> Results
# cluster_1 = models.CharField("Cluster 1", max_length=1,
# blank=True, null=True)
#
# class Meta:
# verbose_name = "User Info"
# verbose_name_plural = "Users Infos"
# app_label = APP_LABEL
#
# def __str__(self):
# return("{} - S: {}, A:{} - Group: {}".format(
# self.id, self.get_sex_display(), self.age, self.cluster_1)
# )
#
# class CommentOfMySite(IsSpammable):
# SPAM_FILTER = "Spam Filter for Comments (example)"
# SPAMMABLE_FIELD = "comment"
#
# comment = models.TextField("Comment")
# user_id = models.SmallIntegerField("User ID")
#
# class Meta:
# verbose_name = "Comment of my Site"
# verbose_name_plural = "Comments of my Site"
# app_label = APP_LABEL
#
# def __str__(self):
# return("[U: {}] {}...".format(self.user_id, self.comment[:20]))
#
# Path: django_ai/examples/forms.py
# class CommentOfMySiteForm(forms.ModelForm):
#
# class Meta:
# model = CommentOfMySite
# fields = ('comment', 'user_id', )
# widgets = {
# 'user_id': forms.HiddenInput(),
# 'comment': forms.Textarea(attrs={'class': 'materialize-textarea'})
# }
. Output only the next line. | other_pages = list(set(PAGES_COLORS.keys()) - set(besides)) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
UserInfo.get_sex_display.short_description = "Sex"
@admin.register(UserInfo)
class UserInfoAdmin(admin.ModelAdmin):
list_display = ['id', 'age', 'get_sex_display', 'avg1',
'avg_time_pages', 'visits_pages', 'avg_time_pages_a',
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib import admin
from .models import (UserInfo, CommentOfMySite, SFPTEnron, SFPTYoutube)
and context (classes, functions, sometimes code) from other files:
# Path: django_ai/examples/models.py
# class UserInfo(models.Model):
# """
# Example User Information Model
# """
# SEX_CHOICES = [(0, "M"), (1, "F")]
#
# age = models.IntegerField("Age")
# sex = models.SmallIntegerField("Sex", choices=SEX_CHOICES,
# blank=True, null=True)
# # -> Metrics
# avg1 = models.FloatField("Average 1", blank=True, null=True)
# avg_time_pages = models.FloatField("Average Time on Pages",
# default=0, blank=True, null=True)
# visits_pages = models.IntegerField("Visits on Pages (Total)",
# default=0)
# avg_time_pages_a = models.FloatField("Average Time on Pages of type A",
# default=0, blank=True, null=True)
# visits_pages_a = models.IntegerField("Visits on Pages of type A",
# default=0)
# avg_time_pages_b = models.FloatField("Average Time on Pages of type B",
# default=0, blank=True, null=True)
# visits_pages_b = models.IntegerField("Visits on Pages of type B",
# default=0)
# avg_time_pages_c = models.FloatField("Average Time on Pages of type C",
# default=0, blank=True, null=True)
# visits_pages_c = models.IntegerField("Visits on Pages of type C",
# default=0)
# avg_time_pages_d = models.FloatField("Average Time on Pages of type D",
# default=0, blank=True, null=True)
# visits_pages_d = models.IntegerField("Visits on Pages of type D",
# default=0)
# avg_time_pages_e = models.FloatField("Average Time on Pages of type E",
# default=0, blank=True, null=True)
# visits_pages_e = models.IntegerField("Visits on Pages of type E",
# default=0)
# avg_time_pages_f = models.FloatField("Average Time on Pages of type F",
# default=0, blank=True, null=True)
# visits_pages_f = models.IntegerField("Visits on Pages of type F",
# default=0)
# avg_time_pages_g = models.FloatField("Average Time on Pages of type G",
# default=0, blank=True, null=True)
# visits_pages_g = models.IntegerField("Visits on Pages of type G",
# default=0)
# avg_time_pages_h = models.FloatField("Average Time on Pages of type H",
# default=0, blank=True, null=True)
# visits_pages_h = models.IntegerField("Visits on Pages of type H",
# default=0)
# avg_time_pages_i = models.FloatField("Average Time on Pages of type I",
# default=0, blank=True, null=True)
# visits_pages_i = models.IntegerField("Visits on Pages of type I",
# default=0)
# avg_time_pages_j = models.FloatField("Average Time on Pages of type J",
# default=0, blank=True, null=True)
# visits_pages_j = models.IntegerField("Visits on Pages of type J",
# default=0)
# # -> Results
# cluster_1 = models.CharField("Cluster 1", max_length=1,
# blank=True, null=True)
#
# class Meta:
# verbose_name = "User Info"
# verbose_name_plural = "Users Infos"
# app_label = APP_LABEL
#
# def __str__(self):
# return("{} - S: {}, A:{} - Group: {}".format(
# self.id, self.get_sex_display(), self.age, self.cluster_1)
# )
#
# class CommentOfMySite(IsSpammable):
# SPAM_FILTER = "Spam Filter for Comments (example)"
# SPAMMABLE_FIELD = "comment"
#
# comment = models.TextField("Comment")
# user_id = models.SmallIntegerField("User ID")
#
# class Meta:
# verbose_name = "Comment of my Site"
# verbose_name_plural = "Comments of my Site"
# app_label = APP_LABEL
#
# def __str__(self):
# return("[U: {}] {}...".format(self.user_id, self.comment[:20]))
#
# class SFPTEnron(SpamFilterPreTraining):
#
# class Meta:
# verbose_name = "Spam Filter Pre-Training: Enron Email Data"
# verbose_name_plural = "Spam Filter Pre-Training: Enron Emails Data"
# app_label = APP_LABEL
#
# class SFPTYoutube(SpamFilterPreTraining):
#
# class Meta:
# verbose_name = "Spam Filter Pre-Training: Youtube Comment Data"
# verbose_name_plural = ("Spam Filter Pre-Training: "
# "Youtube Comments Data")
# app_label = APP_LABEL
. Output only the next line. | 'visits_pages_a', 'cluster_1'] |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
UserInfo.get_sex_display.short_description = "Sex"
@admin.register(UserInfo)
class UserInfoAdmin(admin.ModelAdmin):
list_display = ['id', 'age', 'get_sex_display', 'avg1',
'avg_time_pages', 'visits_pages', 'avg_time_pages_a',
'visits_pages_a', 'cluster_1']
fieldsets = (
(None, {
'fields': ('age', 'sex',)
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from .models import (UserInfo, CommentOfMySite, SFPTEnron, SFPTYoutube)
and context from other files:
# Path: django_ai/examples/models.py
# class UserInfo(models.Model):
# """
# Example User Information Model
# """
# SEX_CHOICES = [(0, "M"), (1, "F")]
#
# age = models.IntegerField("Age")
# sex = models.SmallIntegerField("Sex", choices=SEX_CHOICES,
# blank=True, null=True)
# # -> Metrics
# avg1 = models.FloatField("Average 1", blank=True, null=True)
# avg_time_pages = models.FloatField("Average Time on Pages",
# default=0, blank=True, null=True)
# visits_pages = models.IntegerField("Visits on Pages (Total)",
# default=0)
# avg_time_pages_a = models.FloatField("Average Time on Pages of type A",
# default=0, blank=True, null=True)
# visits_pages_a = models.IntegerField("Visits on Pages of type A",
# default=0)
# avg_time_pages_b = models.FloatField("Average Time on Pages of type B",
# default=0, blank=True, null=True)
# visits_pages_b = models.IntegerField("Visits on Pages of type B",
# default=0)
# avg_time_pages_c = models.FloatField("Average Time on Pages of type C",
# default=0, blank=True, null=True)
# visits_pages_c = models.IntegerField("Visits on Pages of type C",
# default=0)
# avg_time_pages_d = models.FloatField("Average Time on Pages of type D",
# default=0, blank=True, null=True)
# visits_pages_d = models.IntegerField("Visits on Pages of type D",
# default=0)
# avg_time_pages_e = models.FloatField("Average Time on Pages of type E",
# default=0, blank=True, null=True)
# visits_pages_e = models.IntegerField("Visits on Pages of type E",
# default=0)
# avg_time_pages_f = models.FloatField("Average Time on Pages of type F",
# default=0, blank=True, null=True)
# visits_pages_f = models.IntegerField("Visits on Pages of type F",
# default=0)
# avg_time_pages_g = models.FloatField("Average Time on Pages of type G",
# default=0, blank=True, null=True)
# visits_pages_g = models.IntegerField("Visits on Pages of type G",
# default=0)
# avg_time_pages_h = models.FloatField("Average Time on Pages of type H",
# default=0, blank=True, null=True)
# visits_pages_h = models.IntegerField("Visits on Pages of type H",
# default=0)
# avg_time_pages_i = models.FloatField("Average Time on Pages of type I",
# default=0, blank=True, null=True)
# visits_pages_i = models.IntegerField("Visits on Pages of type I",
# default=0)
# avg_time_pages_j = models.FloatField("Average Time on Pages of type J",
# default=0, blank=True, null=True)
# visits_pages_j = models.IntegerField("Visits on Pages of type J",
# default=0)
# # -> Results
# cluster_1 = models.CharField("Cluster 1", max_length=1,
# blank=True, null=True)
#
# class Meta:
# verbose_name = "User Info"
# verbose_name_plural = "Users Infos"
# app_label = APP_LABEL
#
# def __str__(self):
# return("{} - S: {}, A:{} - Group: {}".format(
# self.id, self.get_sex_display(), self.age, self.cluster_1)
# )
#
# class CommentOfMySite(IsSpammable):
# SPAM_FILTER = "Spam Filter for Comments (example)"
# SPAMMABLE_FIELD = "comment"
#
# comment = models.TextField("Comment")
# user_id = models.SmallIntegerField("User ID")
#
# class Meta:
# verbose_name = "Comment of my Site"
# verbose_name_plural = "Comments of my Site"
# app_label = APP_LABEL
#
# def __str__(self):
# return("[U: {}] {}...".format(self.user_id, self.comment[:20]))
#
# class SFPTEnron(SpamFilterPreTraining):
#
# class Meta:
# verbose_name = "Spam Filter Pre-Training: Enron Email Data"
# verbose_name_plural = "Spam Filter Pre-Training: Enron Emails Data"
# app_label = APP_LABEL
#
# class SFPTYoutube(SpamFilterPreTraining):
#
# class Meta:
# verbose_name = "Spam Filter Pre-Training: Youtube Comment Data"
# verbose_name_plural = ("Spam Filter Pre-Training: "
# "Youtube Comments Data")
# app_label = APP_LABEL
, which may include functions, classes, or code. Output only the next line. | }), |
Continue the code snippet: <|code_start|>
@admin.register(UserInfo)
class UserInfoAdmin(admin.ModelAdmin):
list_display = ['id', 'age', 'get_sex_display', 'avg1',
'avg_time_pages', 'visits_pages', 'avg_time_pages_a',
'visits_pages_a', 'cluster_1']
fieldsets = (
(None, {
'fields': ('age', 'sex',)
}),
(None, {
'fields': ('avg1',)
}),
("Pages of Type X", {
'fields': (
('visits_pages_a', 'avg_time_pages_a', ),
('visits_pages_b', 'avg_time_pages_b', ),
('visits_pages_c', 'avg_time_pages_c', ),
('visits_pages_d', 'avg_time_pages_d', ),
('visits_pages_e', 'avg_time_pages_e', ),
('visits_pages_f', 'avg_time_pages_f', ),
('visits_pages_g', 'avg_time_pages_g', ),
('visits_pages_h', 'avg_time_pages_h', ),
('visits_pages_i', 'avg_time_pages_i', ),
('visits_pages_j', 'avg_time_pages_j', ),
),
}),
("Visits and Pages (General)", {
'fields': (
<|code_end|>
. Use current file imports:
from django.contrib import admin
from .models import (UserInfo, CommentOfMySite, SFPTEnron, SFPTYoutube)
and context (classes, functions, or code) from other files:
# Path: django_ai/examples/models.py
# class UserInfo(models.Model):
# """
# Example User Information Model
# """
# SEX_CHOICES = [(0, "M"), (1, "F")]
#
# age = models.IntegerField("Age")
# sex = models.SmallIntegerField("Sex", choices=SEX_CHOICES,
# blank=True, null=True)
# # -> Metrics
# avg1 = models.FloatField("Average 1", blank=True, null=True)
# avg_time_pages = models.FloatField("Average Time on Pages",
# default=0, blank=True, null=True)
# visits_pages = models.IntegerField("Visits on Pages (Total)",
# default=0)
# avg_time_pages_a = models.FloatField("Average Time on Pages of type A",
# default=0, blank=True, null=True)
# visits_pages_a = models.IntegerField("Visits on Pages of type A",
# default=0)
# avg_time_pages_b = models.FloatField("Average Time on Pages of type B",
# default=0, blank=True, null=True)
# visits_pages_b = models.IntegerField("Visits on Pages of type B",
# default=0)
# avg_time_pages_c = models.FloatField("Average Time on Pages of type C",
# default=0, blank=True, null=True)
# visits_pages_c = models.IntegerField("Visits on Pages of type C",
# default=0)
# avg_time_pages_d = models.FloatField("Average Time on Pages of type D",
# default=0, blank=True, null=True)
# visits_pages_d = models.IntegerField("Visits on Pages of type D",
# default=0)
# avg_time_pages_e = models.FloatField("Average Time on Pages of type E",
# default=0, blank=True, null=True)
# visits_pages_e = models.IntegerField("Visits on Pages of type E",
# default=0)
# avg_time_pages_f = models.FloatField("Average Time on Pages of type F",
# default=0, blank=True, null=True)
# visits_pages_f = models.IntegerField("Visits on Pages of type F",
# default=0)
# avg_time_pages_g = models.FloatField("Average Time on Pages of type G",
# default=0, blank=True, null=True)
# visits_pages_g = models.IntegerField("Visits on Pages of type G",
# default=0)
# avg_time_pages_h = models.FloatField("Average Time on Pages of type H",
# default=0, blank=True, null=True)
# visits_pages_h = models.IntegerField("Visits on Pages of type H",
# default=0)
# avg_time_pages_i = models.FloatField("Average Time on Pages of type I",
# default=0, blank=True, null=True)
# visits_pages_i = models.IntegerField("Visits on Pages of type I",
# default=0)
# avg_time_pages_j = models.FloatField("Average Time on Pages of type J",
# default=0, blank=True, null=True)
# visits_pages_j = models.IntegerField("Visits on Pages of type J",
# default=0)
# # -> Results
# cluster_1 = models.CharField("Cluster 1", max_length=1,
# blank=True, null=True)
#
# class Meta:
# verbose_name = "User Info"
# verbose_name_plural = "Users Infos"
# app_label = APP_LABEL
#
# def __str__(self):
# return("{} - S: {}, A:{} - Group: {}".format(
# self.id, self.get_sex_display(), self.age, self.cluster_1)
# )
#
# class CommentOfMySite(IsSpammable):
# SPAM_FILTER = "Spam Filter for Comments (example)"
# SPAMMABLE_FIELD = "comment"
#
# comment = models.TextField("Comment")
# user_id = models.SmallIntegerField("User ID")
#
# class Meta:
# verbose_name = "Comment of my Site"
# verbose_name_plural = "Comments of my Site"
# app_label = APP_LABEL
#
# def __str__(self):
# return("[U: {}] {}...".format(self.user_id, self.comment[:20]))
#
# class SFPTEnron(SpamFilterPreTraining):
#
# class Meta:
# verbose_name = "Spam Filter Pre-Training: Enron Email Data"
# verbose_name_plural = "Spam Filter Pre-Training: Enron Emails Data"
# app_label = APP_LABEL
#
# class SFPTYoutube(SpamFilterPreTraining):
#
# class Meta:
# verbose_name = "Spam Filter Pre-Training: Youtube Comment Data"
# verbose_name_plural = ("Spam Filter Pre-Training: "
# "Youtube Comments Data")
# app_label = APP_LABEL
. Output only the next line. | ('visits_pages', 'avg_time_pages', ), |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
UserInfo.get_sex_display.short_description = "Sex"
@admin.register(UserInfo)
class UserInfoAdmin(admin.ModelAdmin):
list_display = ['id', 'age', 'get_sex_display', 'avg1',
'avg_time_pages', 'visits_pages', 'avg_time_pages_a',
'visits_pages_a', 'cluster_1']
fieldsets = (
(None, {
'fields': ('age', 'sex',)
}),
(None, {
'fields': ('avg1',)
}),
("Pages of Type X", {
'fields': (
('visits_pages_a', 'avg_time_pages_a', ),
('visits_pages_b', 'avg_time_pages_b', ),
('visits_pages_c', 'avg_time_pages_c', ),
('visits_pages_d', 'avg_time_pages_d', ),
('visits_pages_e', 'avg_time_pages_e', ),
('visits_pages_f', 'avg_time_pages_f', ),
<|code_end|>
. Use current file imports:
from django.contrib import admin
from .models import (UserInfo, CommentOfMySite, SFPTEnron, SFPTYoutube)
and context (classes, functions, or code) from other files:
# Path: django_ai/examples/models.py
# class UserInfo(models.Model):
# """
# Example User Information Model
# """
# SEX_CHOICES = [(0, "M"), (1, "F")]
#
# age = models.IntegerField("Age")
# sex = models.SmallIntegerField("Sex", choices=SEX_CHOICES,
# blank=True, null=True)
# # -> Metrics
# avg1 = models.FloatField("Average 1", blank=True, null=True)
# avg_time_pages = models.FloatField("Average Time on Pages",
# default=0, blank=True, null=True)
# visits_pages = models.IntegerField("Visits on Pages (Total)",
# default=0)
# avg_time_pages_a = models.FloatField("Average Time on Pages of type A",
# default=0, blank=True, null=True)
# visits_pages_a = models.IntegerField("Visits on Pages of type A",
# default=0)
# avg_time_pages_b = models.FloatField("Average Time on Pages of type B",
# default=0, blank=True, null=True)
# visits_pages_b = models.IntegerField("Visits on Pages of type B",
# default=0)
# avg_time_pages_c = models.FloatField("Average Time on Pages of type C",
# default=0, blank=True, null=True)
# visits_pages_c = models.IntegerField("Visits on Pages of type C",
# default=0)
# avg_time_pages_d = models.FloatField("Average Time on Pages of type D",
# default=0, blank=True, null=True)
# visits_pages_d = models.IntegerField("Visits on Pages of type D",
# default=0)
# avg_time_pages_e = models.FloatField("Average Time on Pages of type E",
# default=0, blank=True, null=True)
# visits_pages_e = models.IntegerField("Visits on Pages of type E",
# default=0)
# avg_time_pages_f = models.FloatField("Average Time on Pages of type F",
# default=0, blank=True, null=True)
# visits_pages_f = models.IntegerField("Visits on Pages of type F",
# default=0)
# avg_time_pages_g = models.FloatField("Average Time on Pages of type G",
# default=0, blank=True, null=True)
# visits_pages_g = models.IntegerField("Visits on Pages of type G",
# default=0)
# avg_time_pages_h = models.FloatField("Average Time on Pages of type H",
# default=0, blank=True, null=True)
# visits_pages_h = models.IntegerField("Visits on Pages of type H",
# default=0)
# avg_time_pages_i = models.FloatField("Average Time on Pages of type I",
# default=0, blank=True, null=True)
# visits_pages_i = models.IntegerField("Visits on Pages of type I",
# default=0)
# avg_time_pages_j = models.FloatField("Average Time on Pages of type J",
# default=0, blank=True, null=True)
# visits_pages_j = models.IntegerField("Visits on Pages of type J",
# default=0)
# # -> Results
# cluster_1 = models.CharField("Cluster 1", max_length=1,
# blank=True, null=True)
#
# class Meta:
# verbose_name = "User Info"
# verbose_name_plural = "Users Infos"
# app_label = APP_LABEL
#
# def __str__(self):
# return("{} - S: {}, A:{} - Group: {}".format(
# self.id, self.get_sex_display(), self.age, self.cluster_1)
# )
#
# class CommentOfMySite(IsSpammable):
# SPAM_FILTER = "Spam Filter for Comments (example)"
# SPAMMABLE_FIELD = "comment"
#
# comment = models.TextField("Comment")
# user_id = models.SmallIntegerField("User ID")
#
# class Meta:
# verbose_name = "Comment of my Site"
# verbose_name_plural = "Comments of my Site"
# app_label = APP_LABEL
#
# def __str__(self):
# return("[U: {}] {}...".format(self.user_id, self.comment[:20]))
#
# class SFPTEnron(SpamFilterPreTraining):
#
# class Meta:
# verbose_name = "Spam Filter Pre-Training: Enron Email Data"
# verbose_name_plural = "Spam Filter Pre-Training: Enron Emails Data"
# app_label = APP_LABEL
#
# class SFPTYoutube(SpamFilterPreTraining):
#
# class Meta:
# verbose_name = "Spam Filter Pre-Training: Youtube Comment Data"
# verbose_name_plural = ("Spam Filter Pre-Training: "
# "Youtube Comments Data")
# app_label = APP_LABEL
. Output only the next line. | ('visits_pages_g', 'avg_time_pages_g', ), |
Predict the next line for this snippet: <|code_start|> new_thread_count = 0
for sthread in new_threads:
if linked_threads.filter(url=sthread.permalink).exists():
pass
else:
thread_list.append([sthread.title, sthread.permalink])
t = WatchedSubredditThread(parent_subreddit=subreddit, url=sthread.permalink,
title=sthread.title, thread_date=sthread.created)
t.save()
new_thread_count += 1
if new_thread_count == 0:
pass
else:
formatted_thread_titles = ''
limit_threads = 5
for thr in thread_list:
if limit_threads > 0:
formatted_thread_titles += '\n\n' + thr[0] + ' - [Link](https://reddit.com{})'.format(thr[1])
limit_threads -= 1
else:
break
username = subreddit.user.username
notify_user(username, '{} new thread(s) in the subreddit **"{}"** - view subreddit [here.]'
'(https://reddit.com/r/{}) \n\n *** \n *^subreddit ^preview* {} \n *** \n'
'^[[Information]](http://reddit.com/u/reddit_watcher) ^| '
'^[[Code]](https://github.com/ericleepa/watcherforreddit) ^| ^[[Contact]]'
'(https://www.reddit.com/message/compose/?to=ericleepa&subject=watcher)'
.format(new_thread_count, subreddit.name,
subreddit.name, formatted_thread_titles))
<|code_end|>
with the help of current file imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedSubreddit, WatchedSubredditThread
from redditpoller.poller import get_subreddit_threads, notify_user
from datetime import timedelta
and context from other files:
# Path: redditpoller/models.py
# class WatchedSubreddit(models.Model):
# user = models.ForeignKey(User)
# name = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.name
#
# class WatchedSubredditThread(models.Model):
# parent_subreddit = models.ForeignKey(WatchedSubreddit, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_subreddit_threads(subreddit_name, fetch_amount):
# thread = r.subreddit(subreddit_name).new(limit=fetch_amount)
# return thread
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
, which may contain function names, class names, or code. Output only the next line. | notifications_sent += 1 |
Predict the next line for this snippet: <|code_start|>
class Command(BaseCommand):
help = "Checks watched subreddits and notifies users of updates"
def handle(self, *args, **options):
watched_subreddits = WatchedSubreddit.objects.all()
subreddit_count = watched_subreddits.count()
notifications_sent = 0
for subreddit in watched_subreddits:
current_time = timezone.now()
if current_time - timedelta(hours=subreddit.watch_interval) < subreddit.last_checked_date:
pass
else:
subreddit.last_checked_date = current_time
subreddit.save()
new_threads = get_subreddit_threads(subreddit_name=subreddit.name, fetch_amount=50)
linked_threads = WatchedSubredditThread.objects.filter(parent_subreddit=subreddit)
# keep db from growing, only need the newest 100 submissions as a comparison
if linked_threads.count() > 200:
# This works, but probably can be broken up into its own "cleanup function"
number_to_delete = abs(100 - linked_threads.count())
purge = linked_threads.order_by('thread_date')[:number_to_delete].values_list("id", flat=True)
WatchedSubredditThread.objects.filter(pk__in=list(purge)).delete()
thread_list = []
<|code_end|>
with the help of current file imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedSubreddit, WatchedSubredditThread
from redditpoller.poller import get_subreddit_threads, notify_user
from datetime import timedelta
and context from other files:
# Path: redditpoller/models.py
# class WatchedSubreddit(models.Model):
# user = models.ForeignKey(User)
# name = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.name
#
# class WatchedSubredditThread(models.Model):
# parent_subreddit = models.ForeignKey(WatchedSubreddit, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_subreddit_threads(subreddit_name, fetch_amount):
# thread = r.subreddit(subreddit_name).new(limit=fetch_amount)
# return thread
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
, which may contain function names, class names, or code. Output only the next line. | new_thread_count = 0 |
Using the snippet: <|code_start|> if current_time - timedelta(hours=subreddit.watch_interval) < subreddit.last_checked_date:
pass
else:
subreddit.last_checked_date = current_time
subreddit.save()
new_threads = get_subreddit_threads(subreddit_name=subreddit.name, fetch_amount=50)
linked_threads = WatchedSubredditThread.objects.filter(parent_subreddit=subreddit)
# keep db from growing, only need the newest 100 submissions as a comparison
if linked_threads.count() > 200:
# This works, but probably can be broken up into its own "cleanup function"
number_to_delete = abs(100 - linked_threads.count())
purge = linked_threads.order_by('thread_date')[:number_to_delete].values_list("id", flat=True)
WatchedSubredditThread.objects.filter(pk__in=list(purge)).delete()
thread_list = []
new_thread_count = 0
for sthread in new_threads:
if linked_threads.filter(url=sthread.permalink).exists():
pass
else:
thread_list.append([sthread.title, sthread.permalink])
t = WatchedSubredditThread(parent_subreddit=subreddit, url=sthread.permalink,
title=sthread.title, thread_date=sthread.created)
t.save()
new_thread_count += 1
if new_thread_count == 0:
pass
else:
formatted_thread_titles = ''
limit_threads = 5
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedSubreddit, WatchedSubredditThread
from redditpoller.poller import get_subreddit_threads, notify_user
from datetime import timedelta
and context (class names, function names, or code) available:
# Path: redditpoller/models.py
# class WatchedSubreddit(models.Model):
# user = models.ForeignKey(User)
# name = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.name
#
# class WatchedSubredditThread(models.Model):
# parent_subreddit = models.ForeignKey(WatchedSubreddit, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_subreddit_threads(subreddit_name, fetch_amount):
# thread = r.subreddit(subreddit_name).new(limit=fetch_amount)
# return thread
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
. Output only the next line. | for thr in thread_list: |
Using the snippet: <|code_start|> linked_threads = WatchedSubredditThread.objects.filter(parent_subreddit=subreddit)
# keep db from growing, only need the newest 100 submissions as a comparison
if linked_threads.count() > 200:
# This works, but probably can be broken up into its own "cleanup function"
number_to_delete = abs(100 - linked_threads.count())
purge = linked_threads.order_by('thread_date')[:number_to_delete].values_list("id", flat=True)
WatchedSubredditThread.objects.filter(pk__in=list(purge)).delete()
thread_list = []
new_thread_count = 0
for sthread in new_threads:
if linked_threads.filter(url=sthread.permalink).exists():
pass
else:
thread_list.append([sthread.title, sthread.permalink])
t = WatchedSubredditThread(parent_subreddit=subreddit, url=sthread.permalink,
title=sthread.title, thread_date=sthread.created)
t.save()
new_thread_count += 1
if new_thread_count == 0:
pass
else:
formatted_thread_titles = ''
limit_threads = 5
for thr in thread_list:
if limit_threads > 0:
formatted_thread_titles += '\n\n' + thr[0] + ' - [Link](https://reddit.com{})'.format(thr[1])
limit_threads -= 1
else:
break
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedSubreddit, WatchedSubredditThread
from redditpoller.poller import get_subreddit_threads, notify_user
from datetime import timedelta
and context (class names, function names, or code) available:
# Path: redditpoller/models.py
# class WatchedSubreddit(models.Model):
# user = models.ForeignKey(User)
# name = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.name
#
# class WatchedSubredditThread(models.Model):
# parent_subreddit = models.ForeignKey(WatchedSubreddit, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_subreddit_threads(subreddit_name, fetch_amount):
# thread = r.subreddit(subreddit_name).new(limit=fetch_amount)
# return thread
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
. Output only the next line. | username = subreddit.user.username |
Here is a snippet: <|code_start|> for user in watched_users:
current_time = timezone.now()
if current_time - timedelta(hours=user.watch_interval) < user.last_checked_date:
pass
else:
user.last_checked_date = current_time
user.save()
new_threads = get_user_threads(user.watched_username, 10)
linked_threads = WatchedUserThread.objects.filter(parent_user=user)
thread_list = []
new_thread_count = 0
for thread in new_threads:
if linked_threads.filter(url=thread.permalink).exists():
pass
else:
thread_list.append([thread.title, thread.permalink])
t = WatchedUserThread(parent_user=user, url=thread.permalink,
title=thread.title, thread_date=thread.created)
t.save()
new_thread_count += 1
new_comments = get_user_comments(user.watched_username, 10)
linked_comments = WatchedUserComment.objects.filter(parent_user=user)
new_comment_count = 0
comment_list = []
for comment in new_comments:
if linked_comments.filter(url=comment.permalink(fast=True)).exists():
pass
else:
c = WatchedUserComment(parent_user=user, url=comment.permalink(fast=True),
text=comment.body)
<|code_end|>
. Write the next line using the current file imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedUser, WatchedUserComment, WatchedUserThread
from redditpoller.poller import get_user_threads, get_user_comments, notify_user
from datetime import timedelta
and context from other files:
# Path: redditpoller/models.py
# class WatchedUser(models.Model):
# user = models.ForeignKey(User)
# watched_username = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.watched_username
#
# class WatchedUserComment(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# class WatchedUserThread(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_user_threads(username, fetch_amount):
# threads = r.redditor(username).submissions.new(limit=fetch_amount)
# return threads
#
# def get_user_comments(username, fetch_amount):
# comments = r.redditor(username).comments.new(limit=fetch_amount)
# return comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
, which may include functions, classes, or code. Output only the next line. | c.save() |
Given snippet: <|code_start|>
class Command(BaseCommand):
help = "Checks watched users and notifies users of updates"
def handle(self, *args, **options):
watched_users = WatchedUser.objects.all()
user_count = watched_users.count()
notifications_sent = 0
for user in watched_users:
current_time = timezone.now()
if current_time - timedelta(hours=user.watch_interval) < user.last_checked_date:
pass
else:
user.last_checked_date = current_time
user.save()
new_threads = get_user_threads(user.watched_username, 10)
linked_threads = WatchedUserThread.objects.filter(parent_user=user)
thread_list = []
new_thread_count = 0
for thread in new_threads:
if linked_threads.filter(url=thread.permalink).exists():
pass
else:
thread_list.append([thread.title, thread.permalink])
t = WatchedUserThread(parent_user=user, url=thread.permalink,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedUser, WatchedUserComment, WatchedUserThread
from redditpoller.poller import get_user_threads, get_user_comments, notify_user
from datetime import timedelta
and context:
# Path: redditpoller/models.py
# class WatchedUser(models.Model):
# user = models.ForeignKey(User)
# watched_username = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.watched_username
#
# class WatchedUserComment(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# class WatchedUserThread(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_user_threads(username, fetch_amount):
# threads = r.redditor(username).submissions.new(limit=fetch_amount)
# return threads
#
# def get_user_comments(username, fetch_amount):
# comments = r.redditor(username).comments.new(limit=fetch_amount)
# return comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
which might include code, classes, or functions. Output only the next line. | title=thread.title, thread_date=thread.created) |
Using the snippet: <|code_start|> else:
formatted_comments = ''
# only grab 3 comments as to not reach character limit
limit_comments = 3
for comment in comment_list:
if limit_comments > 0:
formatted_comments += '\n\n' + comment[0] + ' - [Link](https://reddit.com{})'.format(
comment[1])
limit_comments -= 1
else:
break
formatted_thread_titles = ''
limit_threads = 3
for thr in thread_list:
if limit_threads > 0:
formatted_thread_titles += '\n\n' + thr[0] + ' - [Link](https://reddit.com{})'.format(
thr[1])
limit_threads -= 1
else:
break
all_formatted = formatted_thread_titles + formatted_comments
username = str(user.user)
notify_user(username,
'{} new comment(s) {} new thread(s) and by the user **"{}"** - view user [here]'
'(https://reddit.com/u/{}) \n\n *** \n *^preview* {} \n *** \n'
'^[[Information]](http://reddit.com/u/reddit_watcher) ^| '
'^[[Code]](https://github.com/ericleepa/watcherforreddit) ^| ^[[Contact]]'
'(https://www.reddit.com/message/compose/?to=ericleepa&subject=watcher)'
.format(new_comment_count, new_thread_count, user.watched_username,
user.watched_username, all_formatted))
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedUser, WatchedUserComment, WatchedUserThread
from redditpoller.poller import get_user_threads, get_user_comments, notify_user
from datetime import timedelta
and context (class names, function names, or code) available:
# Path: redditpoller/models.py
# class WatchedUser(models.Model):
# user = models.ForeignKey(User)
# watched_username = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.watched_username
#
# class WatchedUserComment(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# class WatchedUserThread(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_user_threads(username, fetch_amount):
# threads = r.redditor(username).submissions.new(limit=fetch_amount)
# return threads
#
# def get_user_comments(username, fetch_amount):
# comments = r.redditor(username).comments.new(limit=fetch_amount)
# return comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
. Output only the next line. | notifications_sent += 1 |
Predict the next line after this snippet: <|code_start|> else:
thread_list.append([thread.title, thread.permalink])
t = WatchedUserThread(parent_user=user, url=thread.permalink,
title=thread.title, thread_date=thread.created)
t.save()
new_thread_count += 1
new_comments = get_user_comments(user.watched_username, 10)
linked_comments = WatchedUserComment.objects.filter(parent_user=user)
new_comment_count = 0
comment_list = []
for comment in new_comments:
if linked_comments.filter(url=comment.permalink(fast=True)).exists():
pass
else:
c = WatchedUserComment(parent_user=user, url=comment.permalink(fast=True),
text=comment.body)
c.save()
comment_list.append([comment.body, comment.permalink(fast=True)])
new_comment_count += 1
if new_comment_count == 0 and new_thread_count == 0:
pass
else:
formatted_comments = ''
# only grab 3 comments as to not reach character limit
limit_comments = 3
for comment in comment_list:
if limit_comments > 0:
formatted_comments += '\n\n' + comment[0] + ' - [Link](https://reddit.com{})'.format(
comment[1])
limit_comments -= 1
<|code_end|>
using the current file's imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedUser, WatchedUserComment, WatchedUserThread
from redditpoller.poller import get_user_threads, get_user_comments, notify_user
from datetime import timedelta
and any relevant context from other files:
# Path: redditpoller/models.py
# class WatchedUser(models.Model):
# user = models.ForeignKey(User)
# watched_username = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.watched_username
#
# class WatchedUserComment(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# class WatchedUserThread(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_user_threads(username, fetch_amount):
# threads = r.redditor(username).submissions.new(limit=fetch_amount)
# return threads
#
# def get_user_comments(username, fetch_amount):
# comments = r.redditor(username).comments.new(limit=fetch_amount)
# return comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
. Output only the next line. | else: |
Next line prediction: <|code_start|> linked_threads = WatchedUserThread.objects.filter(parent_user=user)
thread_list = []
new_thread_count = 0
for thread in new_threads:
if linked_threads.filter(url=thread.permalink).exists():
pass
else:
thread_list.append([thread.title, thread.permalink])
t = WatchedUserThread(parent_user=user, url=thread.permalink,
title=thread.title, thread_date=thread.created)
t.save()
new_thread_count += 1
new_comments = get_user_comments(user.watched_username, 10)
linked_comments = WatchedUserComment.objects.filter(parent_user=user)
new_comment_count = 0
comment_list = []
for comment in new_comments:
if linked_comments.filter(url=comment.permalink(fast=True)).exists():
pass
else:
c = WatchedUserComment(parent_user=user, url=comment.permalink(fast=True),
text=comment.body)
c.save()
comment_list.append([comment.body, comment.permalink(fast=True)])
new_comment_count += 1
if new_comment_count == 0 and new_thread_count == 0:
pass
else:
formatted_comments = ''
# only grab 3 comments as to not reach character limit
<|code_end|>
. Use current file imports:
(from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedUser, WatchedUserComment, WatchedUserThread
from redditpoller.poller import get_user_threads, get_user_comments, notify_user
from datetime import timedelta)
and context including class names, function names, or small code snippets from other files:
# Path: redditpoller/models.py
# class WatchedUser(models.Model):
# user = models.ForeignKey(User)
# watched_username = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.watched_username
#
# class WatchedUserComment(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# class WatchedUserThread(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_user_threads(username, fetch_amount):
# threads = r.redditor(username).submissions.new(limit=fetch_amount)
# return threads
#
# def get_user_comments(username, fetch_amount):
# comments = r.redditor(username).comments.new(limit=fetch_amount)
# return comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
. Output only the next line. | limit_comments = 3 |
Given the following code snippet before the placeholder: <|code_start|>
class Command(BaseCommand):
help = "Checks watched users and notifies users of updates"
def handle(self, *args, **options):
watched_users = WatchedUser.objects.all()
user_count = watched_users.count()
notifications_sent = 0
for user in watched_users:
current_time = timezone.now()
if current_time - timedelta(hours=user.watch_interval) < user.last_checked_date:
pass
else:
user.last_checked_date = current_time
user.save()
new_threads = get_user_threads(user.watched_username, 10)
linked_threads = WatchedUserThread.objects.filter(parent_user=user)
thread_list = []
new_thread_count = 0
for thread in new_threads:
if linked_threads.filter(url=thread.permalink).exists():
pass
<|code_end|>
, predict the next line using imports from the current file:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedUser, WatchedUserComment, WatchedUserThread
from redditpoller.poller import get_user_threads, get_user_comments, notify_user
from datetime import timedelta
and context including class names, function names, and sometimes code from other files:
# Path: redditpoller/models.py
# class WatchedUser(models.Model):
# user = models.ForeignKey(User)
# watched_username = models.CharField(max_length=30)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.watched_username
#
# class WatchedUserComment(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# class WatchedUserThread(models.Model):
# parent_user = models.ForeignKey(WatchedUser, on_delete=models.CASCADE)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
#
# def __str__(self):
# return self.title
#
# Path: redditpoller/poller.py
# def get_user_threads(username, fetch_amount):
# threads = r.redditor(username).submissions.new(limit=fetch_amount)
# return threads
#
# def get_user_comments(username, fetch_amount):
# comments = r.redditor(username).comments.new(limit=fetch_amount)
# return comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
. Output only the next line. | else: |
Here is a snippet: <|code_start|> linked_comments = WatchedComment.objects.filter(parent_thread=thread)
new_comments = get_reddit_comments_from_thread(praw_thread)
new_comment_count = 0
comment_list = []
for comment in new_comments:
if linked_comments.filter(url=comment.permalink(fast=True)).exists():
pass
else:
c = WatchedComment(parent_thread=thread, url=comment.permalink(fast=True),
text=comment.body)
c.save()
comment_list.append([comment.body, comment.permalink(fast=True)])
new_comment_count += 1
if new_comment_count == 0:
pass
else:
formatted_comments = ''
# only grab 5 comments as to not reach character limit
limit_comments = 5
for comment in comment_list:
if limit_comments > 0:
formatted_comments += '\n\n' + comment[0] + ' - [Link](https://reddit.com{})'.format(comment[1])
limit_comments -= 1
else:
break
notify_user(username, '{} new comment(s) in the thread **"{}"** - view thread [here.]'
'(https://reddit.com/{}) \n\n *** \n *^comment ^preview* {} \n\n *** \n'
'^[[Information]](http://reddit.com/u/reddit_watcher) ^| '
'^[[Code]](https://github.com/ericleepa/watcherforreddit) ^| ^[[Contact]]'
'(https://www.reddit.com/message/compose/?to=ericleepa&subject=watcher)'
<|code_end|>
. Write the next line using the current file imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedThread, WatchedComment
from redditpoller.poller import get_reddit_thread, get_reddit_comments_from_thread, notify_user
from datetime import timedelta
and context from other files:
# Path: redditpoller/models.py
# class WatchedThread(models.Model):
# user = models.ForeignKey(User)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
# archived = models.BooleanField(default=False)
# self_post = models.BooleanField(default=False)
# self_text = models.CharField(max_length=10000, null=True, blank=True)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.title
#
# class WatchedComment(models.Model):
# parent_thread = models.ForeignKey(WatchedThread, on_delete=models.CASCADE)
# comment_author = models.CharField(max_length=100, null=True, blank=True)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# Path: redditpoller/poller.py
# def get_reddit_thread(reddit_url):
# thread = r.submission(url=reddit_url)
# return thread
#
# def get_reddit_comments_from_thread(thread):
# thread.comments.replace_more(limit=0)
# thread_comments = thread.comments.list()
# return thread_comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
, which may include functions, classes, or code. Output only the next line. | .format(new_comment_count, thread.title, thread.url, formatted_comments)) |
Given the following code snippet before the placeholder: <|code_start|>
def handle(self, *args, **options):
watched_threads = WatchedThread.objects.all()
thread_count = watched_threads.count()
notifications_sent = 0
for thread in watched_threads:
current_time = timezone.now()
if current_time - timedelta(hours=thread.watch_interval) < thread.last_checked_date:
pass
else:
thread.last_checked_date = current_time
thread.save()
praw_thread = get_reddit_thread('https://reddit.com' + thread.url)
username = thread.user.username
if thread.archived != praw_thread.archived:
notify_user(username, 'The thread {} has been archived'
'If you would like to watch another thread go [here.]'
'(http://www.reddit.com'.format(thread.title))
thread.delete()
break
if thread.self_text != praw_thread.selftext:
notify_user(username, 'The author of thread "{}" has changed the submission text.'
' You can view the post [here](https://reddit.com/{})'
.format(thread.title, thread.url))
thread.delete()
break
if praw_thread.num_comments > 500:
notify_user(username, 'The thread {} has reached 500 comments'
' and will no longer be watched. This tool is only designed to watch small'
' threads. If you would like to watch another thread go [here.]'
<|code_end|>
, predict the next line using imports from the current file:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedThread, WatchedComment
from redditpoller.poller import get_reddit_thread, get_reddit_comments_from_thread, notify_user
from datetime import timedelta
and context including class names, function names, and sometimes code from other files:
# Path: redditpoller/models.py
# class WatchedThread(models.Model):
# user = models.ForeignKey(User)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
# archived = models.BooleanField(default=False)
# self_post = models.BooleanField(default=False)
# self_text = models.CharField(max_length=10000, null=True, blank=True)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.title
#
# class WatchedComment(models.Model):
# parent_thread = models.ForeignKey(WatchedThread, on_delete=models.CASCADE)
# comment_author = models.CharField(max_length=100, null=True, blank=True)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# Path: redditpoller/poller.py
# def get_reddit_thread(reddit_url):
# thread = r.submission(url=reddit_url)
# return thread
#
# def get_reddit_comments_from_thread(thread):
# thread.comments.replace_more(limit=0)
# thread_comments = thread.comments.list()
# return thread_comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
. Output only the next line. | '(http://www.reddit.com)'.format(thread.title)) |
Continue the code snippet: <|code_start|> notify_user(username, 'The author of thread "{}" has changed the submission text.'
' You can view the post [here](https://reddit.com/{})'
.format(thread.title, thread.url))
thread.delete()
break
if praw_thread.num_comments > 500:
notify_user(username, 'The thread {} has reached 500 comments'
' and will no longer be watched. This tool is only designed to watch small'
' threads. If you would like to watch another thread go [here.]'
'(http://www.reddit.com)'.format(thread.title))
thread.delete()
break
linked_comments = WatchedComment.objects.filter(parent_thread=thread)
new_comments = get_reddit_comments_from_thread(praw_thread)
new_comment_count = 0
comment_list = []
for comment in new_comments:
if linked_comments.filter(url=comment.permalink(fast=True)).exists():
pass
else:
c = WatchedComment(parent_thread=thread, url=comment.permalink(fast=True),
text=comment.body)
c.save()
comment_list.append([comment.body, comment.permalink(fast=True)])
new_comment_count += 1
if new_comment_count == 0:
pass
else:
formatted_comments = ''
# only grab 5 comments as to not reach character limit
<|code_end|>
. Use current file imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedThread, WatchedComment
from redditpoller.poller import get_reddit_thread, get_reddit_comments_from_thread, notify_user
from datetime import timedelta
and context (classes, functions, or code) from other files:
# Path: redditpoller/models.py
# class WatchedThread(models.Model):
# user = models.ForeignKey(User)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
# archived = models.BooleanField(default=False)
# self_post = models.BooleanField(default=False)
# self_text = models.CharField(max_length=10000, null=True, blank=True)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.title
#
# class WatchedComment(models.Model):
# parent_thread = models.ForeignKey(WatchedThread, on_delete=models.CASCADE)
# comment_author = models.CharField(max_length=100, null=True, blank=True)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# Path: redditpoller/poller.py
# def get_reddit_thread(reddit_url):
# thread = r.submission(url=reddit_url)
# return thread
#
# def get_reddit_comments_from_thread(thread):
# thread.comments.replace_more(limit=0)
# thread_comments = thread.comments.list()
# return thread_comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
. Output only the next line. | limit_comments = 5 |
Based on the snippet: <|code_start|>
class Command(BaseCommand):
help = "Checks watched threads and notifies users of updates"
def handle(self, *args, **options):
watched_threads = WatchedThread.objects.all()
thread_count = watched_threads.count()
notifications_sent = 0
for thread in watched_threads:
current_time = timezone.now()
if current_time - timedelta(hours=thread.watch_interval) < thread.last_checked_date:
pass
else:
thread.last_checked_date = current_time
thread.save()
praw_thread = get_reddit_thread('https://reddit.com' + thread.url)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.management import BaseCommand
from django.utils import timezone
from redditpoller.models import WatchedThread, WatchedComment
from redditpoller.poller import get_reddit_thread, get_reddit_comments_from_thread, notify_user
from datetime import timedelta
and context (classes, functions, sometimes code) from other files:
# Path: redditpoller/models.py
# class WatchedThread(models.Model):
# user = models.ForeignKey(User)
# url = models.CharField(max_length=500)
# title = models.CharField(max_length=500)
# thread_date = models.CharField(max_length=50)
# archived = models.BooleanField(default=False)
# self_post = models.BooleanField(default=False)
# self_text = models.CharField(max_length=10000, null=True, blank=True)
# submitted_date = models.DateTimeField(default=timezone.now)
# last_checked_date = models.DateTimeField(default=timezone.now)
# watch_interval = models.IntegerField(blank=True, null=True)
#
# def __str__(self):
# return self.title
#
# class WatchedComment(models.Model):
# parent_thread = models.ForeignKey(WatchedThread, on_delete=models.CASCADE)
# comment_author = models.CharField(max_length=100, null=True, blank=True)
# url = models.CharField(max_length=500)
# text = models.CharField(max_length=10000)
#
# def __str__(self):
# return self.url
#
# Path: redditpoller/poller.py
# def get_reddit_thread(reddit_url):
# thread = r.submission(url=reddit_url)
# return thread
#
# def get_reddit_comments_from_thread(thread):
# thread.comments.replace_more(limit=0)
# thread_comments = thread.comments.list()
# return thread_comments
#
# def notify_user(redditor, message):
# r.redditor(redditor).message('Reddit Watcher', message)
. Output only the next line. | username = thread.user.username |
Next line prediction: <|code_start|># TODO move this here?
class colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def exec_terraform_apply():
print(
colors.OKBLUE + 'Initializing and running Terraform.\n' + colors.ENDC)
print(
colors.OKBLUE + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
call(['terraform', 'init'], workdir=get_terraform_folder())
# TODO see if we can avoid passing in AWS creds via env vars, if `awscli` is configured Terraform
# will just use those preconfigured creds without any extra effort
tfCommand = [
<|code_end|>
. Use current file imports:
(from pathlib import Path
from installer.configurators.common import get_terraform_folder
from installer.helpers.processwrap import tee_check_output, check_output, call
from collections import OrderedDict
import datetime
import subprocess
import sys
import json
import os)
and context including class names, function names, or small code snippets from other files:
# Path: installer/configurators/common.py
# def get_terraform_folder():
# return get_installer_root() + "/installer/terraform/"
#
# Path: installer/helpers/processwrap.py
# def tee_check_output(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# p = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, bufsize=1, cwd=workdir)
# while p.poll() is None:
# for line in p.stdout:
# sys.stdout.buffer.write(line)
# output.write(line.decode('utf8'))
# return p.returncode == 0
#
# def check_output(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# return subprocess.check_output(args, stderr=output, cwd=workdir)
#
# def call(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# subprocess.call(args, stderr=output, stdout=output, cwd=workdir)
. Output only the next line. | 'terraform', 'apply', '--auto-approve', |
Given snippet: <|code_start|> return check_output(['terraform', 'output', varname], workdir=get_terraform_folder()).rstrip().decode('utf8')
except subprocess.CalledProcessError:
print("Failed getting output variable {0} from terraform!".format(varname))
sys.exit()
# All we're doing here is taking values already stored as output variables
# in terraform and translating them to a specific JSON format
# `terraform output -json` would already do this for us, but we have some internal
# scripts and tools that rely on this specific old format so we still need this translation logic
# If those tools are ever updated to handle the terraform output json directly we can drop this
def generate_stack_details():
# Delete old stack_details.json if it's still
# hanging around from a previous run
stackDetails = get_terraform_folder() + '/stack_details.json'
stackfile = Path(stackDetails)
if stackfile.exists():
stackfile.unlink()
output = OrderedDict()
key_common_list = OrderedDict(
[("jenkinselb", "Jenkins ELB"), ("jenkinsuser", "Jenkins Username"),
("jenkinspasswd", "Jenkins Password"), ("jazzhome", "Jazz Home"),
("jazzusername", "Jazz Admin Username"), ("jazzpassword",
"Jazz Admin Password"),
("region", "Region"), ("apiendpoint", "Jazz API Endpoint")])
output = generate_dict(key_common_list, output)
if get_terraform_output_var("codeq") == "1":
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pathlib import Path
from installer.configurators.common import get_terraform_folder
from installer.helpers.processwrap import tee_check_output, check_output, call
from collections import OrderedDict
import datetime
import subprocess
import sys
import json
import os
and context:
# Path: installer/configurators/common.py
# def get_terraform_folder():
# return get_installer_root() + "/installer/terraform/"
#
# Path: installer/helpers/processwrap.py
# def tee_check_output(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# p = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, bufsize=1, cwd=workdir)
# while p.poll() is None:
# for line in p.stdout:
# sys.stdout.buffer.write(line)
# output.write(line.decode('utf8'))
# return p.returncode == 0
#
# def check_output(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# return subprocess.check_output(args, stderr=output, cwd=workdir)
#
# def call(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# subprocess.call(args, stderr=output, stdout=output, cwd=workdir)
which might include code, classes, or functions. Output only the next line. | key_codeq_list = OrderedDict([("sonarhome", "Sonar Home"), |
Given the following code snippet before the placeholder: <|code_start|># TODO move this here?
class colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
<|code_end|>
, predict the next line using imports from the current file:
from pathlib import Path
from installer.configurators.common import get_terraform_folder
from installer.helpers.processwrap import tee_check_output, check_output, call
from collections import OrderedDict
import datetime
import subprocess
import sys
import json
import os
and context including class names, function names, and sometimes code from other files:
# Path: installer/configurators/common.py
# def get_terraform_folder():
# return get_installer_root() + "/installer/terraform/"
#
# Path: installer/helpers/processwrap.py
# def tee_check_output(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# p = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, bufsize=1, cwd=workdir)
# while p.poll() is None:
# for line in p.stdout:
# sys.stdout.buffer.write(line)
# output.write(line.decode('utf8'))
# return p.returncode == 0
#
# def check_output(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# return subprocess.check_output(args, stderr=output, cwd=workdir)
#
# def call(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# subprocess.call(args, stderr=output, stdout=output, cwd=workdir)
. Output only the next line. | BOLD = '\033[1m' |
Given snippet: <|code_start|> colors.OKBLUE + 'Initializing and running Terraform.\n' + colors.ENDC)
print(
colors.OKBLUE + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
call(['terraform', 'init'], workdir=get_terraform_folder())
# TODO see if we can avoid passing in AWS creds via env vars, if `awscli` is configured Terraform
# will just use those preconfigured creds without any extra effort
tfCommand = [
'terraform', 'apply', '--auto-approve',
'-var', 'aws_access_key=%s' % (os.environ['AWS_ACCESS_KEY_ID']),
'-var', 'aws_secret_key=%s' % (os.environ['AWS_SECRET_ACCESS_KEY'])
]
if not tee_check_output(tfCommand, workdir=get_terraform_folder()):
print(
colors.FAIL + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
print(
colors.FAIL + 'Terraform apply failed!' + colors.ENDC)
print(
colors.WARNING + 'Destroying created AWS resources because of failure' + colors.ENDC)
tee_check_output(['terraform', 'destroy', '--auto-approve'], workdir=get_terraform_folder())
else:
print(colors.OKGREEN + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
print(colors.OKGREEN + 'Install succeded, generating stack_details.json...' + '\n' + colors.ENDC)
generate_stack_details()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pathlib import Path
from installer.configurators.common import get_terraform_folder
from installer.helpers.processwrap import tee_check_output, check_output, call
from collections import OrderedDict
import datetime
import subprocess
import sys
import json
import os
and context:
# Path: installer/configurators/common.py
# def get_terraform_folder():
# return get_installer_root() + "/installer/terraform/"
#
# Path: installer/helpers/processwrap.py
# def tee_check_output(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# p = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, bufsize=1, cwd=workdir)
# while p.poll() is None:
# for line in p.stdout:
# sys.stdout.buffer.write(line)
# output.write(line.decode('utf8'))
# return p.returncode == 0
#
# def check_output(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# return subprocess.check_output(args, stderr=output, cwd=workdir)
#
# def call(args, workdir=None):
# with open(install_logfile, 'a') as output:
# output.write('Invoking command: {0}\n'.format(' '.join(args)))
# output.flush() # Flush to make sure order is maintained
# subprocess.call(args, stderr=output, stdout=output, cwd=workdir)
which might include code, classes, or functions. Output only the next line. | def exec_terraform_destroy(): |
Predict the next line for this snippet: <|code_start|>
# TODO revisit the use of an env var here, only the destroy script uses it, and it probably shouldn't
def get_installer_root():
# Set the repo root path as an env var here,
# so subsequent scripts don't need to hardcode absolute paths.
return os.environ.get('JAZZ_INSTALLER_ROOT', str(Path('.').absolute()))
def get_terraform_folder():
return get_installer_root() + "/installer/terraform/"
def get_tfvars_file():
<|code_end|>
with the help of current file imports:
import os
import re
import secrets
import datetime
import string
import boto3
import in_place
import uuid
from pathlib import Path
from installer.configurators.validate_tags import prepare_tags, validate_replication_tags
and context from other files:
# Path: installer/configurators/validate_tags.py
# def prepare_tags(input_tags_param):
# input_tags = []
# input_tags_rel = " ".join(input_tags_param).split()
# for item in input_tags_rel:
# input_tags.append(dict(item2.split("=", 1) for item2 in item.split(",")))
# return input_tags
#
# def validate_replication_tags(replication_tags):
# """
# Returns validated replication tags or raises an error.
# - 'replication_tags' should be a list of 'tag's.
# - a 'tag' should be dictionary with Keys 'Key' and 'Value'
# - the 'Key' Values should be a string with length between 0 and 127
# - the 'Value' Values should be a string with length between 0 and 255
# - the 'Key' Values should be unique
# - the 'Key' and 'Value' Values must not start with 'aws'
# - the 'Key' and 'Value' should be alphanumeric plus the \
# following special characters: + - = . _ : / @. with spaces
# """
#
# # helper method to validate Keys and Values
# def validate_string(val, s_type, s_max_length):
# if type(val) != str:
# raise ValueError("Non string " + s_type + " found:" + str(val))
# str_val = val.strip()
# if not len(str_val):
# raise ValueError("Empty " + s_type + " found.")
# if len(str_val) > s_max_length:
# raise ValueError("Too long " + s_type + " found: " + str_val)
# if str_val.lower().startswith("aws"):
# raise ValueError(s_type + " starting with aws found: " + str_val)
# return str_val
#
# # helper method to validate spedical characters in Keys or Values
# def validate_special_characters(item):
# if not re.match(r"^[a-zA-Z0-9\s\+\-\=\.\_\:\/\@\.]*$", item):
# raise ValueError("tag encountered with special character: " + item)
#
# if type(replication_tags) != list:
# raise ValueError("replication_tags should be a list")
#
# reserved_tags = ["Name", "Application", "JazzInstance", "Environment", "Exempt", "Owner"]
# unique_tags = []
# new_replication_tags = []
# tag_for_resource = '{'
# for tag in replication_tags:
#
# if not (type(tag) == dict and len(tag) == 2 and
# 'Key' in tag and 'Value' in tag):
# raise ValueError("tags should be dicts with Keys 'Key' and 'Value'")
#
# Key = validate_string(tag['Key'], 'Key', 128)
# Value = validate_string(tag['Value'], 'Value', 256)
#
# validate_special_characters(Key)
# validate_special_characters(Value)
#
# if Key in reserved_tags:
# raise ValueError("tag encountered with reserved Key: " + Key)
#
# if Key in unique_tags:
# raise ValueError("tag encountered with duplicate Key: " + Key)
#
# unique_tags.append(Key)
# new_replication_tags.append({"Key": Key, "Value": Value})
# tag_for_resource += Key+'="'+Value + '", '
# if len(new_replication_tags) > 49:
# raise ValueError("More than 50 tags in replication settings.")
# tag_for_resource += '}'
# return new_replication_tags, tag_for_resource
, which may contain function names, class names, or code. Output only the next line. | return get_terraform_folder() + "terraform.tfvars" |
Given snippet: <|code_start|>
def update_sonarqube_terraform(sonarelb, sonaruserpass, sonarip):
replace_tfvars('sonar_server_elb', sonarelb, get_tfvars_file())
replace_tfvars('sonar_username', sonaruserpass[0], get_tfvars_file())
replace_tfvars('sonar_passwd', sonaruserpass[1], get_tfvars_file())
replace_tfvars('sonar_server_public_ip', sonarip, get_tfvars_file())
replace_tfvars('codequality_type', 'sonarqube', get_tfvars_file())
replace_tfvars('codeq', 1, get_tfvars_file())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import subprocess
from .common import get_tfvars_file, replace_tfvars
and context:
# Path: installer/configurators/common.py
# def get_tfvars_file():
# return get_terraform_folder() + "terraform.tfvars"
#
# def replace_tfvars(key, value, fileName, quoteVal=True):
# with in_place.InPlace(fileName) as fileContent:
# for line in fileContent:
# if quoteVal:
# fileContent.write(re.sub(r'({0} = )(.*)'.format(key), r'\1"{0}"'.format(value), line))
# else:
# fileContent.write(re.sub(r'({0} = )(.*)'.format(key), r'\1{0}'.format(value), line))
which might include code, classes, or functions. Output only the next line. | def check_sonar_user(url, username, passwd, token): |
Continue the code snippet: <|code_start|>
@click.command()
# Sonarqube (container)
@click.option(
'--sonarqube/--no-sonarqube',
default=False
)
<|code_end|>
. Use current file imports:
import click
from installer.cli.click_required import Required
from installer.configurators.jenkins_container import configure_jenkins_container
from installer.configurators.gitlab_container import configure_gitlab_container
from installer.configurators.sonarqube_container import configure_sonarqube_container
from installer.helpers.terraform import exec_terraform_apply
and context (classes, functions, or code) from other files:
# Path: installer/cli/click_required.py
# class Required(click.Option):
# def __init__(self, *args, **kwargs):
# required_if = kwargs.pop('required_if', None)
# required_if_not = kwargs.pop('required_if_not', None)
# assert (required_if or required_if_not), "'required_if/if_not' parameter required"
# if required_if:
# self.required_if = required_if
# kwargs['help'] = (kwargs.get('help', '') +
# ' NOTE: This argument must be provided if %s is specified' %
# self.required_if).strip()
# elif required_if_not:
# self.required_if_not = required_if_not
# kwargs['help'] = (kwargs.get('help', '') +
# ' NOTE: This argument is only required if %s is not specified' %
# self.required_if_not).strip()
# super(Required, self).__init__(*args, **kwargs)
#
# def handle_parse_result(self, ctx, opts, args):
# if hasattr(self, 'required_if'):
# we_are_not_present = self.name not in opts
# other_present = self.required_if in opts
#
# if other_present:
# if we_are_not_present:
# raise click.UsageError(
# "Illegal usage: `%s` must be provided if `%s` is specified" % (
# self.name, self.required_if))
# else:
# self.prompt = None
# elif hasattr(self, 'required_if_not'):
# we_are_present = self.name in opts
# other_present = self.required_if_not in opts
#
# if other_present:
# if we_are_present:
# raise click.UsageError(
# "Illegal usage: `%s` is only required if `%s` is not specified" % (
# self.name, self.required_if_not))
# else:
# self.prompt = None
#
# return super(Required, self).handle_parse_result(
# ctx, opts, args)
#
# Path: installer/configurators/jenkins_container.py
# def configure_jenkins_container(existing_vpc_id, vpc_cidr, ecs_range):
# """
# Launch a containerized Jenkins server.
# """
# if existing_vpc_id:
# replace_tfvars('existing_vpc_ecs', existing_vpc_id, get_tfvars_file())
# else:
# replace_tfvars("autovpc", "true", get_tfvars_file(), False)
# replace_tfvars("vpc_cidr_block", vpc_cidr, get_tfvars_file())
#
# replace_tfvars('network_range', ecs_range, get_tfvars_file())
# replace_tfvars('jenkinsuser', "admin", get_tfvars_file())
# replace_tfvars('jenkinspasswd', passwd_generator(), get_tfvars_file())
#
# Path: installer/configurators/gitlab_container.py
# def configure_gitlab_container():
# # TODO having to explicitly disable each other SCM type by name here is not elegant
# replace_tfvars('scmbb', 'false', get_tfvars_file(), False)
# replace_tfvars("scmgitlab", "true", get_tfvars_file(), False)
# replace_tfvars('scm_type', 'gitlab', get_tfvars_file())
# replace_tfvars('scm_pathext', '/', get_tfvars_file())
#
# Path: installer/configurators/sonarqube_container.py
# def configure_sonarqube_container():
# """
# Configure a containerized Sonar server.
# """
# replace_tfvars("dockerizedSonarqube", "true", get_tfvars_file(), False)
# replace_tfvars('sonar_username', "admin", get_tfvars_file())
# replace_tfvars('sonar_passwd', passwd_generator(), get_tfvars_file())
# replace_tfvars('codequality_type', 'sonarqube', get_tfvars_file())
# replace_tfvars('codeq', 1, get_tfvars_file())
#
# Path: installer/helpers/terraform.py
# def exec_terraform_apply():
# print(
# colors.OKBLUE + 'Initializing and running Terraform.\n' + colors.ENDC)
# print(
# colors.OKBLUE + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
#
# call(['terraform', 'init'], workdir=get_terraform_folder())
#
# # TODO see if we can avoid passing in AWS creds via env vars, if `awscli` is configured Terraform
# # will just use those preconfigured creds without any extra effort
# tfCommand = [
# 'terraform', 'apply', '--auto-approve',
# '-var', 'aws_access_key=%s' % (os.environ['AWS_ACCESS_KEY_ID']),
# '-var', 'aws_secret_key=%s' % (os.environ['AWS_SECRET_ACCESS_KEY'])
# ]
#
# if not tee_check_output(tfCommand, workdir=get_terraform_folder()):
# print(
# colors.FAIL + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
#
# print(
# colors.FAIL + 'Terraform apply failed!' + colors.ENDC)
#
# print(
# colors.WARNING + 'Destroying created AWS resources because of failure' + colors.ENDC)
# tee_check_output(['terraform', 'destroy', '--auto-approve'], workdir=get_terraform_folder())
# else:
# print(colors.OKGREEN + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
# print(colors.OKGREEN + 'Install succeded, generating stack_details.json...' + '\n' + colors.ENDC)
# generate_stack_details()
. Output only the next line. | @click.option( |
Continue the code snippet: <|code_start|>
@click.command()
# Sonarqube (container)
@click.option(
'--sonarqube/--no-sonarqube',
default=False
)
@click.option(
"--vpcid",
<|code_end|>
. Use current file imports:
import click
from installer.cli.click_required import Required
from installer.configurators.jenkins_container import configure_jenkins_container
from installer.configurators.gitlab_container import configure_gitlab_container
from installer.configurators.sonarqube_container import configure_sonarqube_container
from installer.helpers.terraform import exec_terraform_apply
and context (classes, functions, or code) from other files:
# Path: installer/cli/click_required.py
# class Required(click.Option):
# def __init__(self, *args, **kwargs):
# required_if = kwargs.pop('required_if', None)
# required_if_not = kwargs.pop('required_if_not', None)
# assert (required_if or required_if_not), "'required_if/if_not' parameter required"
# if required_if:
# self.required_if = required_if
# kwargs['help'] = (kwargs.get('help', '') +
# ' NOTE: This argument must be provided if %s is specified' %
# self.required_if).strip()
# elif required_if_not:
# self.required_if_not = required_if_not
# kwargs['help'] = (kwargs.get('help', '') +
# ' NOTE: This argument is only required if %s is not specified' %
# self.required_if_not).strip()
# super(Required, self).__init__(*args, **kwargs)
#
# def handle_parse_result(self, ctx, opts, args):
# if hasattr(self, 'required_if'):
# we_are_not_present = self.name not in opts
# other_present = self.required_if in opts
#
# if other_present:
# if we_are_not_present:
# raise click.UsageError(
# "Illegal usage: `%s` must be provided if `%s` is specified" % (
# self.name, self.required_if))
# else:
# self.prompt = None
# elif hasattr(self, 'required_if_not'):
# we_are_present = self.name in opts
# other_present = self.required_if_not in opts
#
# if other_present:
# if we_are_present:
# raise click.UsageError(
# "Illegal usage: `%s` is only required if `%s` is not specified" % (
# self.name, self.required_if_not))
# else:
# self.prompt = None
#
# return super(Required, self).handle_parse_result(
# ctx, opts, args)
#
# Path: installer/configurators/jenkins_container.py
# def configure_jenkins_container(existing_vpc_id, vpc_cidr, ecs_range):
# """
# Launch a containerized Jenkins server.
# """
# if existing_vpc_id:
# replace_tfvars('existing_vpc_ecs', existing_vpc_id, get_tfvars_file())
# else:
# replace_tfvars("autovpc", "true", get_tfvars_file(), False)
# replace_tfvars("vpc_cidr_block", vpc_cidr, get_tfvars_file())
#
# replace_tfvars('network_range', ecs_range, get_tfvars_file())
# replace_tfvars('jenkinsuser', "admin", get_tfvars_file())
# replace_tfvars('jenkinspasswd', passwd_generator(), get_tfvars_file())
#
# Path: installer/configurators/gitlab_container.py
# def configure_gitlab_container():
# # TODO having to explicitly disable each other SCM type by name here is not elegant
# replace_tfvars('scmbb', 'false', get_tfvars_file(), False)
# replace_tfvars("scmgitlab", "true", get_tfvars_file(), False)
# replace_tfvars('scm_type', 'gitlab', get_tfvars_file())
# replace_tfvars('scm_pathext', '/', get_tfvars_file())
#
# Path: installer/configurators/sonarqube_container.py
# def configure_sonarqube_container():
# """
# Configure a containerized Sonar server.
# """
# replace_tfvars("dockerizedSonarqube", "true", get_tfvars_file(), False)
# replace_tfvars('sonar_username', "admin", get_tfvars_file())
# replace_tfvars('sonar_passwd', passwd_generator(), get_tfvars_file())
# replace_tfvars('codequality_type', 'sonarqube', get_tfvars_file())
# replace_tfvars('codeq', 1, get_tfvars_file())
#
# Path: installer/helpers/terraform.py
# def exec_terraform_apply():
# print(
# colors.OKBLUE + 'Initializing and running Terraform.\n' + colors.ENDC)
# print(
# colors.OKBLUE + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
#
# call(['terraform', 'init'], workdir=get_terraform_folder())
#
# # TODO see if we can avoid passing in AWS creds via env vars, if `awscli` is configured Terraform
# # will just use those preconfigured creds without any extra effort
# tfCommand = [
# 'terraform', 'apply', '--auto-approve',
# '-var', 'aws_access_key=%s' % (os.environ['AWS_ACCESS_KEY_ID']),
# '-var', 'aws_secret_key=%s' % (os.environ['AWS_SECRET_ACCESS_KEY'])
# ]
#
# if not tee_check_output(tfCommand, workdir=get_terraform_folder()):
# print(
# colors.FAIL + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
#
# print(
# colors.FAIL + 'Terraform apply failed!' + colors.ENDC)
#
# print(
# colors.WARNING + 'Destroying created AWS resources because of failure' + colors.ENDC)
# tee_check_output(['terraform', 'destroy', '--auto-approve'], workdir=get_terraform_folder())
# else:
# print(colors.OKGREEN + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
# print(colors.OKGREEN + 'Install succeded, generating stack_details.json...' + '\n' + colors.ENDC)
# generate_stack_details()
. Output only the next line. | help='Specify the ID of an existing VPC to use for ECS configuration', |
Given snippet: <|code_start|>
@click.command()
@click.option(
'--mode',
type=click.Choice(['all', 'frameworkonly']),
help='`all` to remove Jazz and all deployed services, \
`frameworkonly` to remove Jazz but leave deployed services alone',
required=True
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import os
from installer.helpers.destroyprep import destroyprep
from installer.helpers.terraform import exec_terraform_destroy, get_terraform_output_var
and context:
# Path: installer/helpers/destroyprep.py
# def destroyprep(stackname, identity, region, all=False):
# # Delete the identity policy - Created in terraform/scripts/ses.sh
# client = boto3.client('ses', region_name=region)
# cloudfront_client = boto3.client('cloudfront', region_name=region)
# lambda_client = boto3.client('lambda', region_name=region)
# cloudformation_client = boto3.client('cloudformation', region_name=region)
# client.delete_identity_policy(
# Identity=identity,
# PolicyName="Policy-{0}".format(stackname)
# )
#
# print("Destroy all: {0} for stack {1}".format(all, stackname))
# # run python scripts to teardown
# if all:
# delete_event_source_mapping(stackname, lambda_client)
# delete_platform_services(stackname, cloudformation_client, True)
# delete_cf_dists(stackname, cloudfront_client, True)
# else:
# delete_event_source_mapping(stackname, lambda_client)
# delete_platform_services(stackname, cloudformation_client, False)
#
# Path: installer/helpers/terraform.py
# def exec_terraform_destroy():
# tfCommand = [
# 'terraform', 'destroy', '--auto-approve'
# ]
#
# if not tee_check_output(tfCommand, workdir=get_terraform_folder()):
# print(
# colors.FAIL + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
#
# print(
# colors.FAIL + 'Terraform destroy failed! You can try re-running the uninstall' + colors.ENDC)
# else:
# print(
# colors.OKGREEN + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
#
# print(
# colors.OKGREEN + 'Terraform finished! AWS resources destroyed\n' + colors.ENDC)
#
# def get_terraform_output_var(varname):
# try:
# return check_output(['terraform', 'output', varname], workdir=get_terraform_folder()).rstrip().decode('utf8')
# except subprocess.CalledProcessError:
# print("Failed getting output variable {0} from terraform!".format(varname))
# sys.exit()
which might include code, classes, or functions. Output only the next line. | @click.option('--aws_access_key', prompt=True, envvar='AWS_ACCESS_KEY_ID') |
Based on the snippet: <|code_start|>
@click.command()
@click.option(
'--mode',
type=click.Choice(['all', 'frameworkonly']),
help='`all` to remove Jazz and all deployed services, \
`frameworkonly` to remove Jazz but leave deployed services alone',
required=True
<|code_end|>
, predict the immediate next line with the help of imports:
import click
import os
from installer.helpers.destroyprep import destroyprep
from installer.helpers.terraform import exec_terraform_destroy, get_terraform_output_var
and context (classes, functions, sometimes code) from other files:
# Path: installer/helpers/destroyprep.py
# def destroyprep(stackname, identity, region, all=False):
# # Delete the identity policy - Created in terraform/scripts/ses.sh
# client = boto3.client('ses', region_name=region)
# cloudfront_client = boto3.client('cloudfront', region_name=region)
# lambda_client = boto3.client('lambda', region_name=region)
# cloudformation_client = boto3.client('cloudformation', region_name=region)
# client.delete_identity_policy(
# Identity=identity,
# PolicyName="Policy-{0}".format(stackname)
# )
#
# print("Destroy all: {0} for stack {1}".format(all, stackname))
# # run python scripts to teardown
# if all:
# delete_event_source_mapping(stackname, lambda_client)
# delete_platform_services(stackname, cloudformation_client, True)
# delete_cf_dists(stackname, cloudfront_client, True)
# else:
# delete_event_source_mapping(stackname, lambda_client)
# delete_platform_services(stackname, cloudformation_client, False)
#
# Path: installer/helpers/terraform.py
# def exec_terraform_destroy():
# tfCommand = [
# 'terraform', 'destroy', '--auto-approve'
# ]
#
# if not tee_check_output(tfCommand, workdir=get_terraform_folder()):
# print(
# colors.FAIL + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
#
# print(
# colors.FAIL + 'Terraform destroy failed! You can try re-running the uninstall' + colors.ENDC)
# else:
# print(
# colors.OKGREEN + datetime.datetime.now().strftime('%c') + '\n' + colors.ENDC)
#
# print(
# colors.OKGREEN + 'Terraform finished! AWS resources destroyed\n' + colors.ENDC)
#
# def get_terraform_output_var(varname):
# try:
# return check_output(['terraform', 'output', varname], workdir=get_terraform_folder()).rstrip().decode('utf8')
# except subprocess.CalledProcessError:
# print("Failed getting output variable {0} from terraform!".format(varname))
# sys.exit()
. Output only the next line. | ) |
Given snippet: <|code_start|>#!/usr/bin/env python
#
# Copyright 2015 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class MetricListTest(TestCase):
def setUp(self):
self.cli = MetricList()
self.text = '''
{
"result": [ { "name": "BOUNDARY_MOCK_METRIC",
"defaultAggregate": "AVG",
"defaultResolutionMS": 1000,
"description": "BOUNDARY_MOCK_METRIC",
"displayName": "BOUNDARY_MOCK_METRIC",
"displayNameShort": "BOUNDARY_MOCK_METRIC",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import TestCase
from boundary.metric_list import MetricList
from io import TextIOWrapper, BytesIO
from cli_test import CLITest
from cli_runner import CLIRunner
import sys
import json
import StringIO
and context:
# Path: boundary/metric_list.py
# class MetricList(MetricCommon):
# def __init__(self):
# MetricCommon.__init__(self)
# self._enabled = None
# self._custom = None
#
# def add_arguments(self):
# MetricCommon.add_arguments(self)
# self.parser.add_argument('-b', '--enabled', dest="enabled", action='store', required=False,
# default=None, choices=['true', 'false'],
# help='Filter the list of metrics to only return enabled metrics')
# self.parser.add_argument('-c', '--custom', dest="custom", action='store', required=False,
# default=None, choices=['true', 'false'],
# help='Filter the list of metrics to only return custom metrics')
#
# def get_arguments(self):
# MetricCommon.get_arguments(self)
# self._enabled = self.args.enabled if self.args.enabled is not None else None
# self._custom = self.args.custom if self.args.custom is not None else None
#
# self.get_api_parameters()
#
# def get_api_parameters(self):
# self.path = "v1/metrics"
# self.method = "GET"
# if self._enabled is not None or self._custom is not None:
# self.url_parameters = {}
# if self._enabled is not None:
# self.url_parameters['enabled'] = self._enabled
# if self._custom is not None:
# self.url_parameters['custom'] = self._custom
#
# def get_description(self):
# """
# Text describing this command
# """
# return "Lists the defined metrics in a {0} account".format(self.product_name)
#
# def _handle_results(self):
# # Only process if we get HTTP result of 200
# if self._api_result.status_code == requests.codes.ok:
# metrics = json.loads(self._api_result.text)
# m = []
# for metric in metrics['result']:
# new_metric = self.extract_fields(metric)
# m.append(new_metric)
#
# metrics['result'] = m
# # pretty print the JSON output
# out = json.dumps(metrics, sort_keys=True, indent=4, separators=(',', ': '))
# print(self.colorize_json(out))
which might include code, classes, or functions. Output only the next line. | "unit": "number", |
Next line prediction: <|code_start|>
while not universal.orphaned_results.empty():
try:
# We want to create a whole new socket everytime so we don't
# stack messages up in the queue. We also don't want to just
# send it once and let ZMQ take care of it because it might
# be eaten by a defunct shepherd and then we'd be stuck forever.
shepherd = universal.context.socket(zmq.DEALER)
shepherd.linger = 0
shepherd.connect(config["shepherd/SHEEP_SOCKET"])
shepherd.send_json(FlockMessage("distress", "").to_dict())
logger.info(
"Sent distress message to shepherd, waiting for response."
)
message = exithelpers.recv_json(shepherd, timeout = 1000 * 60)
message = FlockMessage.from_dict(message)
if message.type == "bloot" and message.body == "":
while not universal.orphaned_results.empty():
result = universal.orphaned_results.get()
try:
shepherd.send_json(
FlockMessage("result", result).to_dict()
)
confirmation = exithelpers.recv_json(
<|code_end|>
. Use current file imports:
(import galah.sheep.utility.universal as universal
import galah.sheep.utility.exithelpers as exithelpers
import threading
import logging
import consumer
import producer
import time
import zmq
import logging
from galah.base.flockmail import FlockMessage
from galah.base.config import load_config)
and context including class names, function names, or small code snippets from other files:
# Path: galah/base/config.py
# def load_config(domain):
# """
# Parses and loads up the Galah configuration file and extracts the
# configuration data for the given domain (ex: "web" or "sheep").
#
# Global configuration options will always be returned, no matter the domain.
#
# The configuration file will only be loaded once per instance of the
# interpreter, so feel free to call this function multiple times in many files
# to avoid ugly dependency issues.
#
# """
#
# global loaded
#
# # Note whether this is the first time we're processing the configuraiton. If
# # it is, we'll want to attach the global log handlers.
# first_load = loaded is None
#
# # Load the configuration if it hasn't been loaded yet. Note this ensures
# # that the configuration is only loaded once per instance of the
# # interpreter
# config_file = os.environ.get("GALAH_CONFIG_PATH",
# "/etc/galah/galah.config")
# if not loaded:
# if os.path.isfile(config_file):
# loaded = imp.load_source(
# "user_config_file", config_file
# )
#
# local_config = {}
#
# # Note we make a **shallow** copy of the defaults here
# user_config = dict(defaults)
#
# # If the configuration didn't load correctly, just use the defaults
# if loaded:
# user_config.update(loaded.config)
#
# # The prefix values we will look for when scanning the configuration file.
# prefix = "%s/" % domain
# global_prefix = "global/"
#
# # Grab all the configuration values for the given domain, and any global
# # configuration values, then place the rest of the configuration values
# # in there as well.
# for k, v in user_config.items():
# if k.startswith(prefix) and len(k) != len(prefix):
# local_key = k[len(prefix):]
#
# local_config[local_key] = v
# elif k.startswith(global_prefix) and len(k) != len(global_prefix):
# global_key = k[len(global_prefix):]
#
# local_config[global_key] = v
# elif "/" in k:
# local_config[k] = v
#
# return local_config
. Output only the next line. | shepherd, timeout = 1000 * 5 |
Predict the next line after this snippet: <|code_start|>
# Load up the configuration for the email validation regular expression
config = load_config("global")
class User(Document):
email = EmailField(unique = True, primary_key = True,
regex = config["EMAIL_VALIDATION_REGEX"])
seal = StringField()
account_type = StringField(choices = ["student", "teaching_assistant",
"teacher", "admin"], required = True)
<|code_end|>
using the current file's imports:
from mongoengine import *
from galah.base.config import load_config
and any relevant context from other files:
# Path: galah/base/config.py
# def load_config(domain):
# """
# Parses and loads up the Galah configuration file and extracts the
# configuration data for the given domain (ex: "web" or "sheep").
#
# Global configuration options will always be returned, no matter the domain.
#
# The configuration file will only be loaded once per instance of the
# interpreter, so feel free to call this function multiple times in many files
# to avoid ugly dependency issues.
#
# """
#
# global loaded
#
# # Note whether this is the first time we're processing the configuraiton. If
# # it is, we'll want to attach the global log handlers.
# first_load = loaded is None
#
# # Load the configuration if it hasn't been loaded yet. Note this ensures
# # that the configuration is only loaded once per instance of the
# # interpreter
# config_file = os.environ.get("GALAH_CONFIG_PATH",
# "/etc/galah/galah.config")
# if not loaded:
# if os.path.isfile(config_file):
# loaded = imp.load_source(
# "user_config_file", config_file
# )
#
# local_config = {}
#
# # Note we make a **shallow** copy of the defaults here
# user_config = dict(defaults)
#
# # If the configuration didn't load correctly, just use the defaults
# if loaded:
# user_config.update(loaded.config)
#
# # The prefix values we will look for when scanning the configuration file.
# prefix = "%s/" % domain
# global_prefix = "global/"
#
# # Grab all the configuration values for the given domain, and any global
# # configuration values, then place the rest of the configuration values
# # in there as well.
# for k, v in user_config.items():
# if k.startswith(prefix) and len(k) != len(prefix):
# local_key = k[len(prefix):]
#
# local_config[local_key] = v
# elif k.startswith(global_prefix) and len(k) != len(global_prefix):
# global_key = k[len(global_prefix):]
#
# local_config[global_key] = v
# elif "/" in k:
# local_config[k] = v
#
# return local_config
. Output only the next line. | classes = ListField(ObjectIdField()) |
Predict the next line after this snippet: <|code_start|>
# Load Galah's configuration.
config = load_config("shepherd")
class FlockManager:
class SheepInfo:
<|code_end|>
using the current file's imports:
from galah.base.prioritydict import PriorityDict
from collections import namedtuple
from galah.base.flockmail import InternalTestRequest
from galah.base.config import load_config
import datetime
import heapq
and any relevant context from other files:
# Path: galah/base/prioritydict.py
# class PriorityDict(dict):
# """Dictionary that can be used as a priority queue.
#
# Keys of the dictionary are items to be put into the queue, and values
# are their respective priorities. All dictionary methods work as expected.
# The advantage over a standard heapq-based priority queue is
# that priorities of items can be efficiently updated (amortized O(1))
# using code as 'thedict[item] = new_priority.'
#
# The 'smallest' method can be used to return the object with lowest
# priority, and 'pop_smallest' also removes it.
#
# The 'sorted_iter' method provides a destructive sorted iterator.
# """
#
# def __init__(self, *args, **kwargs):
# super(PriorityDict, self).__init__(*args, **kwargs)
# self._rebuild_heap()
#
# def _rebuild_heap(self):
# self._heap = [(v, k) for k, v in self.iteritems()]
# heapify(self._heap)
#
# def smallest(self):
# """
# Return the item with the lowest priority as a named tuple
# (priority, value).
#
# Raises IndexError if the object is empty.
#
# """
#
# heap = self._heap
# v, k = heap[0]
# while k not in self or self[k] != v:
# heappop(heap)
# v, k = heap[0]
# return PriorityValuePair(v, k)
#
# def pop_smallest(self):
# """
# Return the item as a named tuple (priority, value) with the lowest
# priority and remove it.
#
# Raises IndexError if the object is empty.
#
# """
#
# heap = self._heap
# v, k = heappop(heap)
# while k not in self or self[k] != v:
# v, k = heappop(heap)
# del self[k]
# return PriorityValuePair(v, k)
#
# def __setitem__(self, key, val):
# # We are not going to remove the previous value from the heap,
# # since this would have a cost O(n).
#
# super(PriorityDict, self).__setitem__(key, val)
#
# if len(self._heap) < 2 * len(self):
# heappush(self._heap, (val, key))
# else:
# # When the heap grows larger than 2 * len(self), we rebuild it
# # from scratch to avoid wasting too much memory.
# self._rebuild_heap()
#
# def setdefault(self, key, val):
# if key not in self:
# self[key] = val
# return val
# return self[key]
#
# def update(self, *args, **kwargs):
# # Reimplementing dict.update is tricky -- see e.g.
# # http://mail.python.org/pipermail/python-ideas/2007-May/000744.html
# # We just rebuild the heap from scratch after passing to super.
#
# super(PriorityDict, self).update(*args, **kwargs)
# self._rebuild_heap()
#
# def sorted_iter(self):
# """Sorted iterator of the priority dictionary items.
#
# Beware: this will destroy elements as they are returned.
# """
#
# while self:
# yield self.pop_smallest()
#
# Path: galah/base/config.py
# def load_config(domain):
# """
# Parses and loads up the Galah configuration file and extracts the
# configuration data for the given domain (ex: "web" or "sheep").
#
# Global configuration options will always be returned, no matter the domain.
#
# The configuration file will only be loaded once per instance of the
# interpreter, so feel free to call this function multiple times in many files
# to avoid ugly dependency issues.
#
# """
#
# global loaded
#
# # Note whether this is the first time we're processing the configuraiton. If
# # it is, we'll want to attach the global log handlers.
# first_load = loaded is None
#
# # Load the configuration if it hasn't been loaded yet. Note this ensures
# # that the configuration is only loaded once per instance of the
# # interpreter
# config_file = os.environ.get("GALAH_CONFIG_PATH",
# "/etc/galah/galah.config")
# if not loaded:
# if os.path.isfile(config_file):
# loaded = imp.load_source(
# "user_config_file", config_file
# )
#
# local_config = {}
#
# # Note we make a **shallow** copy of the defaults here
# user_config = dict(defaults)
#
# # If the configuration didn't load correctly, just use the defaults
# if loaded:
# user_config.update(loaded.config)
#
# # The prefix values we will look for when scanning the configuration file.
# prefix = "%s/" % domain
# global_prefix = "global/"
#
# # Grab all the configuration values for the given domain, and any global
# # configuration values, then place the rest of the configuration values
# # in there as well.
# for k, v in user_config.items():
# if k.startswith(prefix) and len(k) != len(prefix):
# local_key = k[len(prefix):]
#
# local_config[local_key] = v
# elif k.startswith(global_prefix) and len(k) != len(global_prefix):
# global_key = k[len(global_prefix):]
#
# local_config[global_key] = v
# elif "/" in k:
# local_config[k] = v
#
# return local_config
. Output only the next line. | __slots__ = ("environment", "servicing_request") |
Given snippet: <|code_start|>
# Load Galah's configuration.
config = load_config("sheep/vz")
vzctlPath = "/usr/sbin/vzctl"
vzlistPath = "/usr/sbin/vzlist"
containerDirectory = None
nullFile = open("/dev/null", "w")
def check_call(*args, **kwargs):
"Essentially subprocess.check_call. Added for compatibilty with <v2.5."
returnValue = subprocess.call(*args, **kwargs)
if returnValue != 0:
raise SystemError((return_value, str(zparams[0])))
else:
return 0
def run_vzctl(zparams, timeout = config["VZCTL_RETRY_TIMEOUT"]):
cmd = [vzctlPath] + zparams
deadline = datetime.datetime.today() + timeout
while True:
return_value = subprocess.call(
cmd, stdout = nullFile, stderr = nullFile
)
if return_value == 9 and datetime.datetime.today() < deadline:
continue
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import subprocess, ConfigParser, sys, os, datetime
from galah.base.magic import memoize
from galah.base.config import load_config
and context:
# Path: galah/base/magic.py
# class memoize(object):
# """
# Decorator. Caches a function's return value each time it is called.
# If called later with the same arguments, the cached value is returned
# (not reevaluated).
#
# """
#
# def __init__(self, func):
# self.func = func
# self.cache = {}
#
# def __call__(self, *args):
# if not isinstance(args, collections.Hashable):
# # uncacheable. a list, for instance.
# # better to not cache than blow up.
# return self.func(*args)
#
# if args in self.cache:
# return self.cache[args]
# else:
# value = self.func(*args)
# self.cache[args] = value
# return value
#
# def __repr__(self):
# "Return the function's docstring."
#
# return self.func.__doc__
#
# def __get__(self, obj, objtype):
# "Support instance methods."
#
# return functools.partial(self.__call__, obj)
#
# Path: galah/base/config.py
# def load_config(domain):
# """
# Parses and loads up the Galah configuration file and extracts the
# configuration data for the given domain (ex: "web" or "sheep").
#
# Global configuration options will always be returned, no matter the domain.
#
# The configuration file will only be loaded once per instance of the
# interpreter, so feel free to call this function multiple times in many files
# to avoid ugly dependency issues.
#
# """
#
# global loaded
#
# # Note whether this is the first time we're processing the configuraiton. If
# # it is, we'll want to attach the global log handlers.
# first_load = loaded is None
#
# # Load the configuration if it hasn't been loaded yet. Note this ensures
# # that the configuration is only loaded once per instance of the
# # interpreter
# config_file = os.environ.get("GALAH_CONFIG_PATH",
# "/etc/galah/galah.config")
# if not loaded:
# if os.path.isfile(config_file):
# loaded = imp.load_source(
# "user_config_file", config_file
# )
#
# local_config = {}
#
# # Note we make a **shallow** copy of the defaults here
# user_config = dict(defaults)
#
# # If the configuration didn't load correctly, just use the defaults
# if loaded:
# user_config.update(loaded.config)
#
# # The prefix values we will look for when scanning the configuration file.
# prefix = "%s/" % domain
# global_prefix = "global/"
#
# # Grab all the configuration values for the given domain, and any global
# # configuration values, then place the rest of the configuration values
# # in there as well.
# for k, v in user_config.items():
# if k.startswith(prefix) and len(k) != len(prefix):
# local_key = k[len(prefix):]
#
# local_config[local_key] = v
# elif k.startswith(global_prefix) and len(k) != len(global_prefix):
# global_key = k[len(global_prefix):]
#
# local_config[global_key] = v
# elif "/" in k:
# local_config[k] = v
#
# return local_config
which might include code, classes, or functions. Output only the next line. | elif return_value != 0: |
Given the code snippet: <|code_start|>
# Load Galah's configuration.
config = load_config("sheep/vz")
vzctlPath = "/usr/sbin/vzctl"
vzlistPath = "/usr/sbin/vzlist"
containerDirectory = None
<|code_end|>
, generate the next line using the imports in this file:
import subprocess, ConfigParser, sys, os, datetime
from galah.base.magic import memoize
from galah.base.config import load_config
and context (functions, classes, or occasionally code) from other files:
# Path: galah/base/magic.py
# class memoize(object):
# """
# Decorator. Caches a function's return value each time it is called.
# If called later with the same arguments, the cached value is returned
# (not reevaluated).
#
# """
#
# def __init__(self, func):
# self.func = func
# self.cache = {}
#
# def __call__(self, *args):
# if not isinstance(args, collections.Hashable):
# # uncacheable. a list, for instance.
# # better to not cache than blow up.
# return self.func(*args)
#
# if args in self.cache:
# return self.cache[args]
# else:
# value = self.func(*args)
# self.cache[args] = value
# return value
#
# def __repr__(self):
# "Return the function's docstring."
#
# return self.func.__doc__
#
# def __get__(self, obj, objtype):
# "Support instance methods."
#
# return functools.partial(self.__call__, obj)
#
# Path: galah/base/config.py
# def load_config(domain):
# """
# Parses and loads up the Galah configuration file and extracts the
# configuration data for the given domain (ex: "web" or "sheep").
#
# Global configuration options will always be returned, no matter the domain.
#
# The configuration file will only be loaded once per instance of the
# interpreter, so feel free to call this function multiple times in many files
# to avoid ugly dependency issues.
#
# """
#
# global loaded
#
# # Note whether this is the first time we're processing the configuraiton. If
# # it is, we'll want to attach the global log handlers.
# first_load = loaded is None
#
# # Load the configuration if it hasn't been loaded yet. Note this ensures
# # that the configuration is only loaded once per instance of the
# # interpreter
# config_file = os.environ.get("GALAH_CONFIG_PATH",
# "/etc/galah/galah.config")
# if not loaded:
# if os.path.isfile(config_file):
# loaded = imp.load_source(
# "user_config_file", config_file
# )
#
# local_config = {}
#
# # Note we make a **shallow** copy of the defaults here
# user_config = dict(defaults)
#
# # If the configuration didn't load correctly, just use the defaults
# if loaded:
# user_config.update(loaded.config)
#
# # The prefix values we will look for when scanning the configuration file.
# prefix = "%s/" % domain
# global_prefix = "global/"
#
# # Grab all the configuration values for the given domain, and any global
# # configuration values, then place the rest of the configuration values
# # in there as well.
# for k, v in user_config.items():
# if k.startswith(prefix) and len(k) != len(prefix):
# local_key = k[len(prefix):]
#
# local_config[local_key] = v
# elif k.startswith(global_prefix) and len(k) != len(global_prefix):
# global_key = k[len(global_prefix):]
#
# local_config[global_key] = v
# elif "/" in k:
# local_config[k] = v
#
# return local_config
. Output only the next line. | nullFile = open("/dev/null", "w") |
Based on the snippet: <|code_start|> # FASTA style names
assert parse_region("gb|accession|locus") == ("gb|accession|locus", 0, None)
assert parse_region("gb|accession|locus:1000-2000") == (
"gb|accession|locus",
1000,
2000,
)
assert parse_region("gb|accession|locus:1,000-2,000") == (
"gb|accession|locus",
1000,
2000,
)
# Punctuation in names (aside from :)
assert parse_region("name-with-hyphens-") == ("name-with-hyphens-", 0, None)
assert parse_region("GL000207.1") == ("GL000207.1", 0, None)
assert parse_region("GL000207.1:1000-2000") == ("GL000207.1", 1000, 2000)
# Trailing dash
assert parse_region("chr21:1000-") == ("chr21", 1000, None)
# Humanized units
assert parse_region("6:1kb-2kb") == ("6", 1000, 2000)
assert parse_region("6:1k-2000") == ("6", 1000, 2000)
assert parse_region("6:1kb-2M") == ("6", 1000, 2000000)
assert parse_region("6:1Gb-") == ("6", 1000000000, None)
with pytest.raises(ValueError):
parse_region("chr1:2,000-1,000") # reverse selection
<|code_end|>
, predict the immediate next line with the help of imports:
import pandas as pd
import numpy as np
import pytest
from bioframe.core import stringops
from bioframe.core.stringops import parse_region
and context (classes, functions, sometimes code) from other files:
# Path: bioframe/core/stringops.py
# def to_ucsc_string(triplet):
# def _parse_humanized(s):
# def parse_region_string(s):
# def _tokenize(s):
# def _check_token(typ, token, expected):
# def _expect(tokens):
# def is_complete_ucsc_string(mystring):
# def parse_region(reg, chromsizes=None):
# _NUMERIC_RE = re.compile("([0-9,.]+)")
#
# Path: bioframe/core/stringops.py
# def parse_region(reg, chromsizes=None):
# """
# Coerce a genomic region string or sequence into a triple (chrom, start, end).
#
# Genomic regions are represented as half-open intervals (0-based starts,
# 1-based ends) along the length coordinate of a contig/scaffold/chromosome.
# Start must be >= 0, and end coordinate must be >= start.
#
# Parameters
# ----------
# reg : str or tuple
# UCSC-style genomic region string, or
# Triple (chrom, start, end), where ``start`` or ``end`` may be ``None``.
# Quadriple (chrom, start, end, name) (name is ignored).
# chromsizes : mapping, optional
# Lookup table of scaffold lengths to check against ``chrom`` and the
# ``end`` coordinate. Required if ``end`` is not supplied.
#
# Returns
# -------
# triple : (str, int, int)
# A well-formed genomic region triple (str, int, int)
#
# """
# if isinstance(reg, str):
# chrom, start, end = parse_region_string(reg)
# else:
# if len(reg) not in [3, 4]:
# raise ValueError("length of a region should be 3 or 4")
# chrom, start, end = reg[:3]
# start = int(start) if start is not None else start
# end = int(end) if end is not None else end
#
# try:
# clen = chromsizes[chrom] if chromsizes is not None else None
# except KeyError:
# raise ValueError("Unknown sequence label: {}".format(chrom))
#
# start = 0 if start is None else start
# if end is None:
# end = clen # if clen is None, end is None too!
#
# if (end is not None) and (end < start):
# raise ValueError("End cannot be less than start")
#
# if start < 0 or (clen is not None and end > clen):
# raise ValueError("Genomic region out of bounds: [{}, {})".format(start, end))
#
# return chrom, start, end
. Output only the next line. | with pytest.raises(ValueError): |
Predict the next line for this snippet: <|code_start|>
def test_to_ucsc_string():
assert stringops.to_ucsc_string(("chr21", 1, 4)) == "chr21:1-4"
def test_parse_region():
# UCSC-style names
assert parse_region("chr21") == ("chr21", 0, None)
assert parse_region("chr21:1000-2000") == ("chr21", 1000, 2000)
assert parse_region("chr21:1,000-2,000") == ("chr21", 1000, 2000)
# Ensembl style names
assert parse_region("6") == ("6", 0, None)
assert parse_region("6:1000-2000") == ("6", 1000, 2000)
assert parse_region("6:1,000-2,000") == ("6", 1000, 2000)
# FASTA style names
assert parse_region("gb|accession|locus") == ("gb|accession|locus", 0, None)
assert parse_region("gb|accession|locus:1000-2000") == (
"gb|accession|locus",
1000,
2000,
)
assert parse_region("gb|accession|locus:1,000-2,000") == (
"gb|accession|locus",
1000,
2000,
<|code_end|>
with the help of current file imports:
import pandas as pd
import numpy as np
import pytest
from bioframe.core import stringops
from bioframe.core.stringops import parse_region
and context from other files:
# Path: bioframe/core/stringops.py
# def to_ucsc_string(triplet):
# def _parse_humanized(s):
# def parse_region_string(s):
# def _tokenize(s):
# def _check_token(typ, token, expected):
# def _expect(tokens):
# def is_complete_ucsc_string(mystring):
# def parse_region(reg, chromsizes=None):
# _NUMERIC_RE = re.compile("([0-9,.]+)")
#
# Path: bioframe/core/stringops.py
# def parse_region(reg, chromsizes=None):
# """
# Coerce a genomic region string or sequence into a triple (chrom, start, end).
#
# Genomic regions are represented as half-open intervals (0-based starts,
# 1-based ends) along the length coordinate of a contig/scaffold/chromosome.
# Start must be >= 0, and end coordinate must be >= start.
#
# Parameters
# ----------
# reg : str or tuple
# UCSC-style genomic region string, or
# Triple (chrom, start, end), where ``start`` or ``end`` may be ``None``.
# Quadriple (chrom, start, end, name) (name is ignored).
# chromsizes : mapping, optional
# Lookup table of scaffold lengths to check against ``chrom`` and the
# ``end`` coordinate. Required if ``end`` is not supplied.
#
# Returns
# -------
# triple : (str, int, int)
# A well-formed genomic region triple (str, int, int)
#
# """
# if isinstance(reg, str):
# chrom, start, end = parse_region_string(reg)
# else:
# if len(reg) not in [3, 4]:
# raise ValueError("length of a region should be 3 or 4")
# chrom, start, end = reg[:3]
# start = int(start) if start is not None else start
# end = int(end) if end is not None else end
#
# try:
# clen = chromsizes[chrom] if chromsizes is not None else None
# except KeyError:
# raise ValueError("Unknown sequence label: {}".format(chrom))
#
# start = 0 if start is None else start
# if end is None:
# end = clen # if clen is None, end is None too!
#
# if (end is not None) and (end < start):
# raise ValueError("End cannot be less than start")
#
# if start < 0 or (clen is not None and end > clen):
# raise ValueError("Genomic region out of bounds: [{}, {})".format(start, end))
#
# return chrom, start, end
, which may contain function names, class names, or code. Output only the next line. | ) |
Here is a snippet: <|code_start|>
DEFAULT_FACECOLOR = "skyblue"
DEFAULT_EDGECOLOR = "dimgray"
__all__ = ["plot_intervals"]
def _plot_interval(
start, end, level, facecolor=None, edgecolor=None, height=0.6, ax=None
):
facecolor = DEFAULT_FACECOLOR if facecolor is None else facecolor
edgecolor = DEFAULT_EDGECOLOR if edgecolor is None else edgecolor
ax = plt.gca() if ax is None else ax
ax.add_patch(
matplotlib.patches.Rectangle(
(start, level - height / 2),
end - start,
height,
<|code_end|>
. Write the next line using the current file imports:
import itertools
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from .core import arrops
and context from other files:
# Path: bioframe/core/arrops.py
# def natsort_key(s, _NS_REGEX=re.compile(r"(\d+)", re.U)):
# def natsorted(iterable):
# def argnatsort(array):
# def _find_block_span(arr, val):
# def interweave(a, b):
# def sum_slices(arr, starts, ends):
# def arange_multi(starts, stops=None, lengths=None):
# def _check_overlap(starts1, ends1, starts2, ends2, closed=False):
# def _size_overlap(starts1, ends1, starts2, ends2):
# def _overlap_intervals_legacy(starts1, ends1, starts2, ends2, closed=False, sort=False):
# def overlap_intervals(starts1, ends1, starts2, ends2, closed=False, sort=False):
# def overlap_intervals_outer(starts1, ends1, starts2, ends2, closed=False):
# def merge_intervals(starts, ends, min_dist=0):
# def complement_intervals(
# starts,
# ends,
# bounds=(0, np.iinfo(np.int64).max),
# ):
# def _closest_intervals_nooverlap(
# starts1, ends1, starts2, ends2, tie_arr=None, k_upstream=1, k_downstream=1
# ):
# def closest_intervals(
# starts1,
# ends1,
# starts2=None,
# ends2=None,
# k=1,
# tie_arr=None,
# ignore_overlaps=False,
# ignore_upstream=False,
# ignore_downstream=False,
# ):
# def coverage_intervals_rle(starts, ends, weights=None):
# def stack_intervals(starts, ends):
, which may include functions, classes, or code. Output only the next line. | facecolor=facecolor, |
Predict the next line after this snippet: <|code_start|> ["chr1", 10, 20],
[pd.NA, pd.NA, pd.NA],
[pd.NA, pd.NA, pd.NA],
],
columns=["chrom", "start", "end"],
)
sanitized_df1 = sanitized_df1.astype(
{"chrom": object, "start": pd.Int64Dtype(), "end": pd.Int64Dtype()}
)
pd.testing.assert_frame_equal(
sanitized_df1.fillna(-1), construction.sanitize_bedframe(df1).fillna(-1)
)
# flip intervals as well as drop NA
df1 = pd.DataFrame(
[
["chr1", 20, 10],
["chr1", pd.NA, 25],
],
columns=["chrom", "start", "end"],
)
sanitized_df1 = pd.DataFrame([["chr1", 10, 20]], columns=["chrom", "start", "end"])
sanitized_df1 = sanitized_df1.astype(
{"chrom": str, "start": pd.Int64Dtype(), "end": pd.Int64Dtype()}
)
pd.testing.assert_frame_equal(
sanitized_df1,
construction.sanitize_bedframe(
df1, start_exceed_end_action="fLiP", drop_null=True
),
<|code_end|>
using the current file's imports:
from io import StringIO
from bioframe.core.construction import from_any
from bioframe.core import construction
import pandas as pd
import numpy as np
import pytest
and any relevant context from other files:
# Path: bioframe/core/construction.py
# def from_any(regions, fill_null=False, name_col="name", cols=None):
# """
# Attempts to make a genomic interval dataframe with columns [chr, start, end, name_col] from a variety of input types.
#
# Parameters
# ----------
# regions : supported input
# Currently supported inputs:
#
# - dataframe
# - series of UCSC strings
# - dictionary of {str:int} key value pairs
# - pandas series where the index is interpreted as chromosomes and values are interpreted as end
# - list of tuples or lists, either [(chrom,start,end)] or [(chrom,start,end,name)]
# - tuple of tuples or lists, either [(chrom,start,end)] or [(chrom,start,end,name)]
#
# fill_null : False or dictionary
# Accepts a dictionary of {str:int} pairs, interpreted as chromosome sizes.
# Kept or backwards compatibility. Default False.
#
# name_col : str
# Column name. Only used if 4 column list is provided. Default "name".
#
# cols : (str,str,str)
# Names for dataframe columns.
# Default None sets them with get_default_colnames().
#
# Returns
# -------
# out_df:dataframe
#
# """
# ck1, sk1, ek1 = _get_default_colnames() if cols is None else cols
#
# if type(regions) is pd.core.frame.DataFrame:
# if set([ck1, sk1, ek1]).issubset(regions.columns):
# out_df = regions.copy()
# elif (len(regions[name_col].values.shape) == 1) and is_complete_ucsc_string(
# regions[name_col].values[0]
# ):
# out_df = from_ucsc_string_list(
# regions[name_col].values, cols=[ck1, sk1, ek1]
# )
# else:
# raise ValueError("Unknown dataFrame format: check column names")
#
# elif type(regions) is dict:
# out_df = from_dict(regions, cols=[ck1, sk1, ek1])
#
# elif type(regions) is pd.core.series.Series:
# out_df = from_series(regions, cols=[ck1, sk1, ek1])
#
# elif type(regions) is tuple:
# if np.shape(regions) == (3,):
# out_df = from_list([regions], name_col=name_col, cols=[ck1, sk1, ek1])
#
# elif len(np.shape(regions)) == 1 and type(regions[0]) is str:
# out_df = from_ucsc_string_list(regions, cols=[ck1, sk1, ek1])
# else:
# out_df = from_list(list(regions), name_col=name_col, cols=[ck1, sk1, ek1])
#
# elif type(regions) is list:
# if np.shape(regions) == (3,):
# out_df = from_list([regions], name_col=name_col, cols=[ck1, sk1, ek1])
# elif len(np.shape(regions)) == 1 and type(regions[0]) is str:
# out_df = from_ucsc_string_list(regions, cols=[ck1, sk1, ek1])
# else:
# out_df = from_list(regions, name_col=name_col, cols=[ck1, sk1, ek1])
# else:
# raise ValueError(f"Unknown input format: {type(regions)}")
#
# if fill_null:
# try:
# out_df[sk1].fillna(0, inplace=True)
# ends = []
# for i in range(len(out_df)):
# if out_df[ek1].values[i] is None:
# ends.append(fill_null[out_df[ck1].values[i]])
# else:
# ends.append(out_df[ek1].values[i])
# out_df[ek1] = ends
# except:
# raise ValueError("could not fill ends with provided chromsizes")
#
# return out_df
#
# Path: bioframe/core/construction.py
# def from_dict(regions, cols=None):
# def from_series(regions, cols=None):
# def from_list(regions, name_col="name", cols=None):
# def from_ucsc_string_list(region_list, cols=None):
# def from_any(regions, fill_null=False, name_col="name", cols=None):
# def add_ucsc_name_column(reg_df, name_col="name", cols=None):
# def make_viewframe(
# regions,
# check_bounds=None,
# name_style=None,
# view_name_col="name",
# cols=None,
# ):
# def sanitize_bedframe(
# df1,
# recast_dtypes=True,
# drop_null=False,
# start_exceed_end_action=None,
# cols=None,
# ):
. Output only the next line. | ) |
Continue the code snippet: <|code_start|> d = """ chrom_1 start_1 end_1 chrom_2 start_2 end_2 distance
0 chrX 1 8 chrX 2 10 0
1 chrX 2 10 chrX 1 8 0"""
df_closest = pd.read_csv(StringIO(d), sep=r"\s+")
df_cat = pd.CategoricalDtype(categories=["chrX", "chr1"], ordered=True)
df = df.astype({"chrom": df_cat})
pd.testing.assert_frame_equal(
df_closest,
bioframe.closest(df, suffixes=("_1", "_2")),
check_dtype=False,
check_categorical=False,
)
# closest should ignore null rows: code will need to be modified
# as for overlap if an on=[] option is added
df1 = pd.DataFrame(
[
[pd.NA, pd.NA, pd.NA],
["chr1", 1, 5],
],
columns=["chrom", "start", "end"],
).astype({"start": pd.Int64Dtype(), "end": pd.Int64Dtype()})
df2 = pd.DataFrame(
[
[pd.NA, pd.NA, pd.NA],
["chr1", 4, 8],
[pd.NA, pd.NA, pd.NA],
["chr1", 10, 11],
],
<|code_end|>
. Use current file imports:
from io import StringIO
from bioframe.core.construction import make_viewframe
import pandas as pd
import numpy as np
import pytest
import bioframe
import bioframe.core.checks as checks
and context (classes, functions, or code) from other files:
# Path: bioframe/core/construction.py
# def make_viewframe(
# regions,
# check_bounds=None,
# name_style=None,
# view_name_col="name",
# cols=None,
# ):
# """
# Makes and validates a dataframe `view_df` out of regions.
#
# Parameters
# ----------
# regions : supported input type
# Currently supported input types:
#
# - a dictionary where keys are strings and values are integers {str:int}, specifying regions (chrom, 0, end, chrom)
# - a pandas series of chromosomes lengths with index specifying region names
# - a list of tuples [(chrom,start,end), ...] or [(chrom,start,end,name), ...]
# - a pandas DataFrame, skips to validation step
#
# name_style : None or "ucsc"
# If None and no column view_name_col, propagate values from cols[0]
# If "ucsc" and no column view_name_col, create UCSC style names
#
# check_bounds : None, or chromosome sizes provided as any of valid formats above
# Optional, if provided checks if regions in the view are contained by regions
# supplied in check_bounds, typically provided as a series of chromosome sizes.
# Default None.
#
# view_name_col : str
# Specifies column name of the view regions. Default 'name'.
#
# cols : (str, str, str) or None
# The names of columns containing the chromosome, start and end of the
# genomic intervals, provided separately for each set. The default
# values are 'chrom', 'start', 'end'.
#
# Returns
# -------
# view_df:dataframe satisfying properties of a view
#
# """
# ck1, sk1, ek1 = _get_default_colnames() if cols is None else cols
#
# view_df = from_any(regions, name_col=view_name_col, cols=cols)
#
# if check_bounds is not None:
# bounds_df = from_any(check_bounds, name_col="bounds", cols=cols)
# if not checks.is_contained(
# view_df,
# bounds_df,
# df_view_col=None,
# view_name_col="bounds",
# cols=cols,
# ):
# raise ValueError(
# "Invalid input to make a viewFrame, regions not contained by bounds"
# )
#
# if not view_name_col in view_df.columns:
# if name_style is None:
# view_df[view_name_col] = view_df[ck1].values
# elif name_style.lower() == "ucsc":
# view_df = add_ucsc_name_column(view_df, name_col=view_name_col, cols=cols)
# else:
# raise ValueError("unknown value for name_style")
#
# if checks.is_viewframe(
# view_df, view_name_col=view_name_col, cols=cols, raise_errors=True
# ):
# return view_df
# else:
# raise ValueError("could not make valid viewFrame, retry with new input")
. Output only the next line. | columns=["chrom", "start", "end"], |
Given snippet: <|code_start|>
def test_is_cataloged():
### chr2q is not in view
view_df = pd.DataFrame(
[
["chr1", 0, 12, "chr1p"],
["chr1", 13, 26, "chr1q"],
["chrX", 1, 8, "chrX_0"],
],
columns=["chrom", "start", "end", "name"],
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from io import StringIO
from bioframe.core.checks import *
from bioframe.ops import sort_bedframe
import pandas as pd
import numpy as np
import pytest
and context:
# Path: bioframe/ops.py
# def sort_bedframe(
# df,
# view_df=None,
# reset_index=True,
# df_view_col=None,
# view_name_col="name",
# cols=None,
# cols_view=None,
# ):
# """
# Sorts a bedframe 'df'.
#
# If 'view_df' is not provided, sorts by ``cols`` (e.g. "chrom", "start", "end").
# If 'view_df' is provided and 'df_view_col' is not provided, uses
# :func:`bioframe.ops.assign_view` with ``df_view_col='view_region'``
# to assign intervals to the view regions with the largest overlap and then sorts.
# If 'view_df' and 'df_view_col' are both provided, checks if the latter
# are cataloged in 'view_name_col', and then sorts.
#
# df : pandas.DataFrame
# Valid bedframe.
#
# view_df : pandas.DataFrame | dict-like
# Valid input to make a viewframe. When it is dict-like
# :func:'bioframe.make_viewframe' will be used to convert
# to viewframe. If view_df is not provided df is sorted by chrom and start.
#
# reset_index : bool
# Default True.
#
# df_view_col: None | str
# Column from 'df' used to associate intervals with view regions.
# The associated region in 'view_df' is then used for sorting.
# If None, :func:'bioframe.assign_view' will be used to assign view regions.
# Default None.
#
# view_name_col: str
# Column from view_df with names of regions.
# Default `name`.
#
# cols : (str, str, str) or None
# The names of columns containing the chromosome, start and end of the
# genomic intervals. The default values are 'chrom', 'start', 'end'.
#
# cols_view : (str, str, str) or None
# The names of columns containing the chromosome, start and end of the
# genomic intervals in the view. The default values are 'chrom', 'start', 'end'.
#
# Returns
# -------
# out_df : sorted bedframe
#
# Notes
# -------
# df_view_col is currently returned as an ordered categorical
#
# """
# ck1, sk1, ek1 = _get_default_colnames() if cols is None else cols
#
# if not checks.is_bedframe(df, cols=cols):
# raise ValueError("not a valid bedframe, cannot sort")
#
# out_df = df.copy()
# if view_df is None:
# out_df.sort_values([ck1, sk1, ek1], inplace=True)
#
# else:
# ckv, skv, ekv = _get_default_colnames() if cols_view is None else cols_view
# view_df = construction.make_viewframe(
# view_df, view_name_col=view_name_col, cols=[ckv, skv, ekv]
# ).rename(columns=dict(zip([ckv, skv, ekv], [ck1, sk1, ek1])))
#
# if df_view_col is None:
# if _verify_columns(out_df, ["view_region"], return_as_bool=True):
# raise ValueError("column view_region already exists in input df")
# df_view_col = "view_region"
# out_df = assign_view(
# out_df,
# view_df,
# df_view_col=df_view_col,
# view_name_col=view_name_col,
# cols=cols,
# cols_view=cols,
# )
#
# else:
# if not _verify_columns(out_df, [df_view_col], return_as_bool=True):
# raise ValueError(
# "column 'df_view_col' not in input df, cannot sort by view"
# )
# if not checks.is_cataloged(
# out_df[pd.isna(out_df[df_view_col].values) == False],
# view_df,
# df_view_col=df_view_col,
# view_name_col=view_name_col,
# ):
# raise ValueError(
# "intervals in df not cataloged in view_df, cannot sort by view"
# )
#
# view_cat = pd.CategoricalDtype(
# categories=view_df[view_name_col].values, ordered=True
# )
# out_df[df_view_col] = out_df[df_view_col].astype({df_view_col: view_cat})
# out_df.sort_values([df_view_col, ck1, sk1, ek1], inplace=True)
#
# # make sure no columns get appended and dtypes are preserved
# out_df = out_df[df.columns].astype(df.dtypes)
#
# if reset_index:
# out_df.reset_index(inplace=True, drop=True)
#
# return out_df
which might include code, classes, or functions. Output only the next line. | df = pd.DataFrame( |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
bbi = None
try:
except ImportError:
pyBigWig = None
__all__ = [
"read_table",
"read_chromsizes",
"read_tabix",
<|code_end|>
with the help of current file imports:
from collections import OrderedDict
from contextlib import closing
from ..core.stringops import parse_region
from ..core.arrops import argnatsort
from .schemas import SCHEMAS, BAM_FIELDS
import subprocess
import tempfile
import json
import io
import numpy as np
import pandas as pd
import bbi
import pyBigWig
import pysam
import pypairix
import cytoolz as toolz
import pysam
import pysam
import pyfaidx
and context from other files:
# Path: bioframe/core/stringops.py
# def parse_region(reg, chromsizes=None):
# """
# Coerce a genomic region string or sequence into a triple (chrom, start, end).
#
# Genomic regions are represented as half-open intervals (0-based starts,
# 1-based ends) along the length coordinate of a contig/scaffold/chromosome.
# Start must be >= 0, and end coordinate must be >= start.
#
# Parameters
# ----------
# reg : str or tuple
# UCSC-style genomic region string, or
# Triple (chrom, start, end), where ``start`` or ``end`` may be ``None``.
# Quadriple (chrom, start, end, name) (name is ignored).
# chromsizes : mapping, optional
# Lookup table of scaffold lengths to check against ``chrom`` and the
# ``end`` coordinate. Required if ``end`` is not supplied.
#
# Returns
# -------
# triple : (str, int, int)
# A well-formed genomic region triple (str, int, int)
#
# """
# if isinstance(reg, str):
# chrom, start, end = parse_region_string(reg)
# else:
# if len(reg) not in [3, 4]:
# raise ValueError("length of a region should be 3 or 4")
# chrom, start, end = reg[:3]
# start = int(start) if start is not None else start
# end = int(end) if end is not None else end
#
# try:
# clen = chromsizes[chrom] if chromsizes is not None else None
# except KeyError:
# raise ValueError("Unknown sequence label: {}".format(chrom))
#
# start = 0 if start is None else start
# if end is None:
# end = clen # if clen is None, end is None too!
#
# if (end is not None) and (end < start):
# raise ValueError("End cannot be less than start")
#
# if start < 0 or (clen is not None and end > clen):
# raise ValueError("Genomic region out of bounds: [{}, {})".format(start, end))
#
# return chrom, start, end
#
# Path: bioframe/core/arrops.py
# def argnatsort(array):
# array = np.asarray(array)
# if not len(array):
# return np.array([], dtype=int)
# cols = tuple(zip(*(natsort_key(x) for x in array)))
# return np.lexsort(cols[::-1]) # numpy's lexsort is ass-backwards
#
# Path: bioframe/io/schemas.py
# SCHEMAS = {
# "bed": BED_FIELDS,
# "bed3": BED_FIELDS[:3],
# "bed4": BED_FIELDS[:4],
# "bedGraph": BEDGRAPH_FIELDS,
# "bed5": BED_FIELDS[:5],
# "bed6": BED_FIELDS,
# "bed9": BED12_FIELDS[:9],
# "bed12": BED12_FIELDS,
# "bedpe": BEDPE_FIELDS,
# "gff": GFF_FIELDS,
# "gtf": GFF_FIELDS,
# "bedRnaElements": BEDRNAELEMENTS_FIELDS,
# "narrowPeak": NARROWPEAK_FIELDS,
# "broadPeak": BROADPEAK_FIELDS,
# "gappedPeak": GAPPEDPEAK_FIELDS,
# "centromeres": CENTROMERES_FIELDS,
# "cytoband": CYTOBAND_FIELDS,
# "sam": BAM_FIELDS,
# "vcf": VCF_FIELDS,
# "jaspar": JASPAR_FIELDS,
# "gap": GAP_FIELDS,
# "UCSCmRNA": UCSC_MRNA_FIELDS,
# "pgsnp": PGSNP_FIELDS,
# }
#
# BAM_FIELDS = [
# "QNAME",
# "FLAG",
# "RNAME",
# "POS",
# "MAPQ",
# "CIGAR",
# "RNEXT",
# "PNEXT",
# "TLEN",
# "SEQ",
# "QUAL",
# "TAGs",
# ]
, which may contain function names, class names, or code. Output only the next line. | "read_pairix", |
Next line prediction: <|code_start|>
try:
except ImportError:
bbi = None
try:
except ImportError:
<|code_end|>
. Use current file imports:
(from collections import OrderedDict
from contextlib import closing
from ..core.stringops import parse_region
from ..core.arrops import argnatsort
from .schemas import SCHEMAS, BAM_FIELDS
import subprocess
import tempfile
import json
import io
import numpy as np
import pandas as pd
import bbi
import pyBigWig
import pysam
import pypairix
import cytoolz as toolz
import pysam
import pysam
import pyfaidx)
and context including class names, function names, or small code snippets from other files:
# Path: bioframe/core/stringops.py
# def parse_region(reg, chromsizes=None):
# """
# Coerce a genomic region string or sequence into a triple (chrom, start, end).
#
# Genomic regions are represented as half-open intervals (0-based starts,
# 1-based ends) along the length coordinate of a contig/scaffold/chromosome.
# Start must be >= 0, and end coordinate must be >= start.
#
# Parameters
# ----------
# reg : str or tuple
# UCSC-style genomic region string, or
# Triple (chrom, start, end), where ``start`` or ``end`` may be ``None``.
# Quadriple (chrom, start, end, name) (name is ignored).
# chromsizes : mapping, optional
# Lookup table of scaffold lengths to check against ``chrom`` and the
# ``end`` coordinate. Required if ``end`` is not supplied.
#
# Returns
# -------
# triple : (str, int, int)
# A well-formed genomic region triple (str, int, int)
#
# """
# if isinstance(reg, str):
# chrom, start, end = parse_region_string(reg)
# else:
# if len(reg) not in [3, 4]:
# raise ValueError("length of a region should be 3 or 4")
# chrom, start, end = reg[:3]
# start = int(start) if start is not None else start
# end = int(end) if end is not None else end
#
# try:
# clen = chromsizes[chrom] if chromsizes is not None else None
# except KeyError:
# raise ValueError("Unknown sequence label: {}".format(chrom))
#
# start = 0 if start is None else start
# if end is None:
# end = clen # if clen is None, end is None too!
#
# if (end is not None) and (end < start):
# raise ValueError("End cannot be less than start")
#
# if start < 0 or (clen is not None and end > clen):
# raise ValueError("Genomic region out of bounds: [{}, {})".format(start, end))
#
# return chrom, start, end
#
# Path: bioframe/core/arrops.py
# def argnatsort(array):
# array = np.asarray(array)
# if not len(array):
# return np.array([], dtype=int)
# cols = tuple(zip(*(natsort_key(x) for x in array)))
# return np.lexsort(cols[::-1]) # numpy's lexsort is ass-backwards
#
# Path: bioframe/io/schemas.py
# SCHEMAS = {
# "bed": BED_FIELDS,
# "bed3": BED_FIELDS[:3],
# "bed4": BED_FIELDS[:4],
# "bedGraph": BEDGRAPH_FIELDS,
# "bed5": BED_FIELDS[:5],
# "bed6": BED_FIELDS,
# "bed9": BED12_FIELDS[:9],
# "bed12": BED12_FIELDS,
# "bedpe": BEDPE_FIELDS,
# "gff": GFF_FIELDS,
# "gtf": GFF_FIELDS,
# "bedRnaElements": BEDRNAELEMENTS_FIELDS,
# "narrowPeak": NARROWPEAK_FIELDS,
# "broadPeak": BROADPEAK_FIELDS,
# "gappedPeak": GAPPEDPEAK_FIELDS,
# "centromeres": CENTROMERES_FIELDS,
# "cytoband": CYTOBAND_FIELDS,
# "sam": BAM_FIELDS,
# "vcf": VCF_FIELDS,
# "jaspar": JASPAR_FIELDS,
# "gap": GAP_FIELDS,
# "UCSCmRNA": UCSC_MRNA_FIELDS,
# "pgsnp": PGSNP_FIELDS,
# }
#
# BAM_FIELDS = [
# "QNAME",
# "FLAG",
# "RNAME",
# "POS",
# "MAPQ",
# "CIGAR",
# "RNEXT",
# "PNEXT",
# "TLEN",
# "SEQ",
# "QUAL",
# "TAGs",
# ]
. Output only the next line. | pyBigWig = None |
Next line prediction: <|code_start|>
try:
except ImportError:
bbi = None
try:
except ImportError:
pyBigWig = None
__all__ = [
"read_table",
"read_chromsizes",
"read_tabix",
"read_pairix",
"read_bam",
<|code_end|>
. Use current file imports:
(from collections import OrderedDict
from contextlib import closing
from ..core.stringops import parse_region
from ..core.arrops import argnatsort
from .schemas import SCHEMAS, BAM_FIELDS
import subprocess
import tempfile
import json
import io
import numpy as np
import pandas as pd
import bbi
import pyBigWig
import pysam
import pypairix
import cytoolz as toolz
import pysam
import pysam
import pyfaidx)
and context including class names, function names, or small code snippets from other files:
# Path: bioframe/core/stringops.py
# def parse_region(reg, chromsizes=None):
# """
# Coerce a genomic region string or sequence into a triple (chrom, start, end).
#
# Genomic regions are represented as half-open intervals (0-based starts,
# 1-based ends) along the length coordinate of a contig/scaffold/chromosome.
# Start must be >= 0, and end coordinate must be >= start.
#
# Parameters
# ----------
# reg : str or tuple
# UCSC-style genomic region string, or
# Triple (chrom, start, end), where ``start`` or ``end`` may be ``None``.
# Quadriple (chrom, start, end, name) (name is ignored).
# chromsizes : mapping, optional
# Lookup table of scaffold lengths to check against ``chrom`` and the
# ``end`` coordinate. Required if ``end`` is not supplied.
#
# Returns
# -------
# triple : (str, int, int)
# A well-formed genomic region triple (str, int, int)
#
# """
# if isinstance(reg, str):
# chrom, start, end = parse_region_string(reg)
# else:
# if len(reg) not in [3, 4]:
# raise ValueError("length of a region should be 3 or 4")
# chrom, start, end = reg[:3]
# start = int(start) if start is not None else start
# end = int(end) if end is not None else end
#
# try:
# clen = chromsizes[chrom] if chromsizes is not None else None
# except KeyError:
# raise ValueError("Unknown sequence label: {}".format(chrom))
#
# start = 0 if start is None else start
# if end is None:
# end = clen # if clen is None, end is None too!
#
# if (end is not None) and (end < start):
# raise ValueError("End cannot be less than start")
#
# if start < 0 or (clen is not None and end > clen):
# raise ValueError("Genomic region out of bounds: [{}, {})".format(start, end))
#
# return chrom, start, end
#
# Path: bioframe/core/arrops.py
# def argnatsort(array):
# array = np.asarray(array)
# if not len(array):
# return np.array([], dtype=int)
# cols = tuple(zip(*(natsort_key(x) for x in array)))
# return np.lexsort(cols[::-1]) # numpy's lexsort is ass-backwards
#
# Path: bioframe/io/schemas.py
# SCHEMAS = {
# "bed": BED_FIELDS,
# "bed3": BED_FIELDS[:3],
# "bed4": BED_FIELDS[:4],
# "bedGraph": BEDGRAPH_FIELDS,
# "bed5": BED_FIELDS[:5],
# "bed6": BED_FIELDS,
# "bed9": BED12_FIELDS[:9],
# "bed12": BED12_FIELDS,
# "bedpe": BEDPE_FIELDS,
# "gff": GFF_FIELDS,
# "gtf": GFF_FIELDS,
# "bedRnaElements": BEDRNAELEMENTS_FIELDS,
# "narrowPeak": NARROWPEAK_FIELDS,
# "broadPeak": BROADPEAK_FIELDS,
# "gappedPeak": GAPPEDPEAK_FIELDS,
# "centromeres": CENTROMERES_FIELDS,
# "cytoband": CYTOBAND_FIELDS,
# "sam": BAM_FIELDS,
# "vcf": VCF_FIELDS,
# "jaspar": JASPAR_FIELDS,
# "gap": GAP_FIELDS,
# "UCSCmRNA": UCSC_MRNA_FIELDS,
# "pgsnp": PGSNP_FIELDS,
# }
#
# BAM_FIELDS = [
# "QNAME",
# "FLAG",
# "RNAME",
# "POS",
# "MAPQ",
# "CIGAR",
# "RNEXT",
# "PNEXT",
# "TLEN",
# "SEQ",
# "QUAL",
# "TAGs",
# ]
. Output only the next line. | "load_fasta", |
Continue the code snippet: <|code_start|>
try:
except ImportError:
bbi = None
try:
except ImportError:
pyBigWig = None
__all__ = [
<|code_end|>
. Use current file imports:
from collections import OrderedDict
from contextlib import closing
from ..core.stringops import parse_region
from ..core.arrops import argnatsort
from .schemas import SCHEMAS, BAM_FIELDS
import subprocess
import tempfile
import json
import io
import numpy as np
import pandas as pd
import bbi
import pyBigWig
import pysam
import pypairix
import cytoolz as toolz
import pysam
import pysam
import pyfaidx
and context (classes, functions, or code) from other files:
# Path: bioframe/core/stringops.py
# def parse_region(reg, chromsizes=None):
# """
# Coerce a genomic region string or sequence into a triple (chrom, start, end).
#
# Genomic regions are represented as half-open intervals (0-based starts,
# 1-based ends) along the length coordinate of a contig/scaffold/chromosome.
# Start must be >= 0, and end coordinate must be >= start.
#
# Parameters
# ----------
# reg : str or tuple
# UCSC-style genomic region string, or
# Triple (chrom, start, end), where ``start`` or ``end`` may be ``None``.
# Quadriple (chrom, start, end, name) (name is ignored).
# chromsizes : mapping, optional
# Lookup table of scaffold lengths to check against ``chrom`` and the
# ``end`` coordinate. Required if ``end`` is not supplied.
#
# Returns
# -------
# triple : (str, int, int)
# A well-formed genomic region triple (str, int, int)
#
# """
# if isinstance(reg, str):
# chrom, start, end = parse_region_string(reg)
# else:
# if len(reg) not in [3, 4]:
# raise ValueError("length of a region should be 3 or 4")
# chrom, start, end = reg[:3]
# start = int(start) if start is not None else start
# end = int(end) if end is not None else end
#
# try:
# clen = chromsizes[chrom] if chromsizes is not None else None
# except KeyError:
# raise ValueError("Unknown sequence label: {}".format(chrom))
#
# start = 0 if start is None else start
# if end is None:
# end = clen # if clen is None, end is None too!
#
# if (end is not None) and (end < start):
# raise ValueError("End cannot be less than start")
#
# if start < 0 or (clen is not None and end > clen):
# raise ValueError("Genomic region out of bounds: [{}, {})".format(start, end))
#
# return chrom, start, end
#
# Path: bioframe/core/arrops.py
# def argnatsort(array):
# array = np.asarray(array)
# if not len(array):
# return np.array([], dtype=int)
# cols = tuple(zip(*(natsort_key(x) for x in array)))
# return np.lexsort(cols[::-1]) # numpy's lexsort is ass-backwards
#
# Path: bioframe/io/schemas.py
# SCHEMAS = {
# "bed": BED_FIELDS,
# "bed3": BED_FIELDS[:3],
# "bed4": BED_FIELDS[:4],
# "bedGraph": BEDGRAPH_FIELDS,
# "bed5": BED_FIELDS[:5],
# "bed6": BED_FIELDS,
# "bed9": BED12_FIELDS[:9],
# "bed12": BED12_FIELDS,
# "bedpe": BEDPE_FIELDS,
# "gff": GFF_FIELDS,
# "gtf": GFF_FIELDS,
# "bedRnaElements": BEDRNAELEMENTS_FIELDS,
# "narrowPeak": NARROWPEAK_FIELDS,
# "broadPeak": BROADPEAK_FIELDS,
# "gappedPeak": GAPPEDPEAK_FIELDS,
# "centromeres": CENTROMERES_FIELDS,
# "cytoband": CYTOBAND_FIELDS,
# "sam": BAM_FIELDS,
# "vcf": VCF_FIELDS,
# "jaspar": JASPAR_FIELDS,
# "gap": GAP_FIELDS,
# "UCSCmRNA": UCSC_MRNA_FIELDS,
# "pgsnp": PGSNP_FIELDS,
# }
#
# BAM_FIELDS = [
# "QNAME",
# "FLAG",
# "RNAME",
# "POS",
# "MAPQ",
# "CIGAR",
# "RNEXT",
# "PNEXT",
# "TLEN",
# "SEQ",
# "QUAL",
# "TAGs",
# ]
. Output only the next line. | "read_table", |
Next line prediction: <|code_start|>
def test_get_default_colnames():
assert specs._get_default_colnames() == ("chrom", "start", "end")
def test_update_default_colnames():
new_names = ("C", "chromStart", "chromStop")
specs.update_default_colnames(new_names)
assert specs._get_default_colnames() == new_names
# test that with updated default column names, bioframe.ops recognizes df1
df1 = pd.DataFrame(
[["chr1", 1, 5], ["chr1", 3, 8], ["chr1", 8, 10], ["chr1", 12, 14]],
columns=list(new_names),
<|code_end|>
. Use current file imports:
(from io import StringIO
from bioframe.core import specs
import pandas as pd
import numpy as np
import pytest
import bioframe)
and context including class names, function names, or small code snippets from other files:
# Path: bioframe/core/specs.py
# def _get_default_colnames():
# def __init__(self, new_colnames):
# def __enter__(self):
# def __exit__(self, *args):
# def _verify_columns(df, colnames, return_as_bool=False):
# def _verify_column_dtypes(df, cols=None, return_as_bool=False):
# def is_chrom_dtype(chrom_dtype):
# class update_default_colnames:
. Output only the next line. | ) |
Based on the snippet: <|code_start|>
def test_01():
data = loadfile(TESTDIR + "test01.21")
cn, c1, yd, yo, zd, zo = calccumsum(data)
<|code_end|>
, predict the immediate next line with the help of imports:
from nose.tools import assert_equal, assert_almost_equal, assert_true, \
assert_false, assert_raises, assert_is_instance
from subprocess import call
from ksatools.ksatools import loadfile, calcmedian, calccumsum, TESTDIR
from numpy import array
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: ksatools/ksatools.py
# def loadfile(filename):
# '''Loads file, returns two-column ndarray or None on
# failure. Uses filename to guess format.'''
# try:
# # parse velvet contig stats format
# if filename.find("stats.txt") >= 0:
# matrix = np.loadtxt(filename, usecols=(5, 1), skiprows=1)
# elif filename.find(".npo") == len(filename) - 4:
# matrix = np.loadtxt(filename, usecols=(0, 1), skiprows=6)
# L = getlength(filename)
# matrix[:, 0] = matrix[:, 0] * L
# else: # default bare-bones spectrum format
# try:
# matrix = np.loadtxt(filename, comments="#")
# except ValueError:
# matrix = np.loadtxt(filename, skiprows=1,
# delimiter=",", usecols=(0, 1))
# # return None if the file is empty
# matrix[np.isinf(matrix)] = 0
# matrix = np.atleast_2d(matrix)
# if matrix.shape[1] == 0:
# return []
# else:
# return matrix
# except IOError:
# sys.stderr.write("ERROR: Can't find file %s\n" % filename)
# return []
#
# def calcmedian(yd, y, num):
# '''wrapper for np.interp; interpolates to return the value of yd corresponding to num on y
# sorts the data and prepends a 0,0 to get smooth behavior for entire range 0,1.'''
# ya = np.argsort(y)
# y2 = np.hstack(([0], y[ya]))
# y2d = np.hstack(([0], yd[ya]))
# r = np.interp(num, y2, y2d)
# return r
#
# def calccumsum(a):
# '''Calcaulates the cumulative-sum vectors from a 2d numpy array
# of [cov, num]. Note depends on upstream sort '''
# cn = a[:, 0] # Coverage
# c1 = a[:, 1] # number of distinct kmers.
# cp = cn * c1 # elementwise multiply observed kmers by abundance
# # cumul number of distinct kmers (top to bottom)
# yd = np.flipud(np.flipud(c1).cumsum())
# # cumul number of observed kmers (top to bottom)
# yo = np.flipud(np.flipud(cp).cumsum())
# # cumul number of distinct kmers (bottom to top)
# zd = np.cumsum(c1)
# # cumul number of observed kmers (bottom to top)
# zo = np.cumsum(cp)
# if zo.max() == 0:
# raise ValueError # There should be data here
# return(cn, c1, yd, yo, zd, zo)
#
# TESTDIR = "tests/data/"
. Output only the next line. | pass |
Given the following code snippet before the placeholder: <|code_start|>
def test_01():
data = loadfile(TESTDIR + "test01.21")
cn, c1, yd, yo, zd, zo = calccumsum(data)
<|code_end|>
, predict the next line using imports from the current file:
from nose.tools import assert_equal, assert_almost_equal, assert_true, \
assert_false, assert_raises, assert_is_instance
from subprocess import call
from ksatools.ksatools import loadfile, calcmedian, calccumsum, TESTDIR
from numpy import array
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: ksatools/ksatools.py
# def loadfile(filename):
# '''Loads file, returns two-column ndarray or None on
# failure. Uses filename to guess format.'''
# try:
# # parse velvet contig stats format
# if filename.find("stats.txt") >= 0:
# matrix = np.loadtxt(filename, usecols=(5, 1), skiprows=1)
# elif filename.find(".npo") == len(filename) - 4:
# matrix = np.loadtxt(filename, usecols=(0, 1), skiprows=6)
# L = getlength(filename)
# matrix[:, 0] = matrix[:, 0] * L
# else: # default bare-bones spectrum format
# try:
# matrix = np.loadtxt(filename, comments="#")
# except ValueError:
# matrix = np.loadtxt(filename, skiprows=1,
# delimiter=",", usecols=(0, 1))
# # return None if the file is empty
# matrix[np.isinf(matrix)] = 0
# matrix = np.atleast_2d(matrix)
# if matrix.shape[1] == 0:
# return []
# else:
# return matrix
# except IOError:
# sys.stderr.write("ERROR: Can't find file %s\n" % filename)
# return []
#
# def calcmedian(yd, y, num):
# '''wrapper for np.interp; interpolates to return the value of yd corresponding to num on y
# sorts the data and prepends a 0,0 to get smooth behavior for entire range 0,1.'''
# ya = np.argsort(y)
# y2 = np.hstack(([0], y[ya]))
# y2d = np.hstack(([0], yd[ya]))
# r = np.interp(num, y2, y2d)
# return r
#
# def calccumsum(a):
# '''Calcaulates the cumulative-sum vectors from a 2d numpy array
# of [cov, num]. Note depends on upstream sort '''
# cn = a[:, 0] # Coverage
# c1 = a[:, 1] # number of distinct kmers.
# cp = cn * c1 # elementwise multiply observed kmers by abundance
# # cumul number of distinct kmers (top to bottom)
# yd = np.flipud(np.flipud(c1).cumsum())
# # cumul number of observed kmers (top to bottom)
# yo = np.flipud(np.flipud(cp).cumsum())
# # cumul number of distinct kmers (bottom to top)
# zd = np.cumsum(c1)
# # cumul number of observed kmers (bottom to top)
# zo = np.cumsum(cp)
# if zo.max() == 0:
# raise ValueError # There should be data here
# return(cn, c1, yd, yo, zd, zo)
#
# TESTDIR = "tests/data/"
. Output only the next line. | pass |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
'''This is a curve-fitting tool for interpreting kmer spectra'''
mpl.use('Agg')
def weightedleastsquares(parameters, yvalues, xvalues, order=None):
'''Returns vector of weighted residuals. Used for initial fits.'''
err = (yvalues - fitfn(xvalues, parameters, order)) / np.sqrt(yvalues + 1)
if OPTS.constrained:
err = err + \
np.ones(err.shape) * \
sum(parameters[2:] * parameters[2:] * (parameters[2:] < 0))
return err
def loglikelihood(parameters, yvalues, xvalues, order=None):
'''Calculate poisson likelihood given the data and a call to fitfn.
Returns a vector of quasi-residuals'''
err2 = stats.poisson.logpmf(yvalues, fitfn(xvalues, parameters, order))
for i in range(0, len(err2)):
if err2[i] < -1000:
err2[i] = -1000
if np.isnan(err2[i]) or np.isinf(err2[i]):
err2[i] = -1001
<|code_end|>
. Use current file imports:
import sys
import os
import argparse
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import numdifftools as nd
from scipy import stats
from scipy.optimize import leastsq
from ksatools.ksatools import pad
and context (classes, functions, or code) from other files:
# Path: ksatools/ksatools.py
# def pad(xvalues, yvalues, fill=True):
# '''Adds missing integer values to x and corresponding zeros to y.'''
# yout = []
# xout = []
# xv = np.arange(1, int(1.5 * max(xvalues)))
# yv = np.zeros(shape=int(1.5 * max(xvalues) - 1), dtype=int)
#
# if fill is True:
# for i, x in enumerate(xvalues):
# yv[np.where(xv == x)[0][0]] = yvalues[i]
# xout = list(xv)
# yout = list(yv)
# else:
# for i, x in enumerate(xvalues):
# if (x - 1 not in xvalues) and (x - 1) not in xout:
# xout.append(x - 1)
# yout.append(0)
# if yvalues[xvalues.index(x)] > 0:
# xout.append(xvalues[xvalues.index(x)])
# yout.append(yvalues[xvalues.index(x)])
# if (x + 1 not in xvalues) and (x + 1) not in xout:
# xout.append(x + 1)
# yout.append(0)
# return(xout, yout)
. Output only the next line. | sqerr2 = np.sqrt(-err2) |
Given the code snippet: <|code_start|>
class DBHandler(logging.Handler):
def emit(self, record):
if type(record.msg) is dict:
# Pull the project name, hostname, and revision out of the record
filters = {}
for key in ('project_name', 'hostname', 'revision'):
if record.msg.has_key(key):
<|code_end|>
, generate the next line using the imports in this file:
import logging
from debug_logging.models import TestRun, DebugLogRecord
and context (functions, classes, or occasionally code) from other files:
# Path: debug_logging/models.py
# class TestRun(models.Model):
# """Captures overall statistics about a single test run."""
# start = models.DateTimeField()
# end = models.DateTimeField(blank=True, null=True)
#
# name = models.CharField(max_length=255, blank=True, null=True)
# description = models.TextField(blank=True, null=True)
#
# project_name = models.CharField(max_length=255, blank=True, null=True)
# hostname = models.CharField(max_length=255, blank=True, null=True)
# revision = models.CharField(max_length=40, blank=True, null=True)
#
# # Some of these fields aren't used yet, since they are not represented in
# # the UI. Once they are added to the UI, they'll be added to the
# # set_aggregates method below.
# total_requests = models.IntegerField(blank=True, null=True)
# avg_time = models.FloatField(blank=True, null=True)
# total_time = models.FloatField(blank=True, null=True)
# avg_cpu_time = models.FloatField(blank=True, null=True)
# total_cpu_time = models.FloatField(blank=True, null=True)
#
# avg_sql_time = models.FloatField(blank=True, null=True)
# total_sql_time = models.FloatField(blank=True, null=True)
# avg_sql_queries = models.FloatField(blank=True, null=True)
# total_sql_queries = models.IntegerField(blank=True, null=True)
# max_sql_queries = models.IntegerField(blank=True, null=True)
#
# avg_cache_hits = models.FloatField(blank=True, null=True)
# total_cache_hits = models.IntegerField(blank=True, null=True)
# avg_cache_misses = models.FloatField(blank=True, null=True)
# total_cache_misses = models.IntegerField(blank=True, null=True)
#
# def __unicode__(self):
# date_format = 'n/j/Y g:i a'
# if self.name:
# return '%s (%s)' % (name, date_filter(self.start, date_format))
# return date_filter(self.start, date_format)
#
# def get_absolute_url(self):
# return reverse('debug_logging_run_detail', args=[self.id])
#
# def set_aggregates(self, force=False):
# """
# Sets any aggregates that haven't been generated yet, or recalculates
# them if the force option is indicated.
# """
# aggregates = {}
#
# if not self.avg_time or force:
# aggregates["avg_time"] = models.Avg('timer_total')
# if not self.avg_cpu_time or force:
# aggregates["avg_cpu_time"] = models.Avg('timer_cputime')
# if not self.avg_sql_time or force:
# aggregates["avg_sql_time"] = models.Avg('sql_time')
# if not self.avg_sql_queries or force:
# aggregates["avg_sql_queries"] = models.Avg('sql_num_queries')
# if not self.total_sql_queries or force:
# aggregates["total_sql_queries"] = models.Sum('sql_num_queries')
# if not self.max_sql_queries or force:
# aggregates["max_sql_queries"] = models.Max('sql_num_queries')
# if not self.total_requests or force:
# aggregates["total_requests"] = models.Count('pk')
#
# if aggregates:
# aggregated = self.records.aggregate(**aggregates)
#
# for key, value in aggregated.items():
# setattr(self, key, value)
#
# class DebugLogRecord(models.Model):
# """Captures statistics for individual requests."""
# timestamp = models.DateTimeField(auto_now_add=True)
# test_run = models.ForeignKey(TestRun, related_name='records')
#
# request_path = models.CharField(max_length=255)
# settings = PickledObjectField(compress=True, blank=True, null=True)
#
# # Timer stats
# timer_utime = models.FloatField(blank=True, null=True)
# timer_stime = models.FloatField(blank=True, null=True)
# timer_cputime = models.FloatField(blank=True, null=True)
# timer_total = models.FloatField(blank=True, null=True)
# timer_vcsw = models.IntegerField(blank=True, null=True)
# timer_ivcsw = models.IntegerField(blank=True, null=True)
#
# # Sql stats
# sql_num_queries = models.IntegerField(blank=True, null=True)
# sql_time = models.FloatField(blank=True, null=True)
# sql_queries = PickledObjectField(compress=True, blank=True, null=True)
#
# # Cache stats
# cache_num_calls = models.IntegerField(blank=True, null=True)
# cache_time = models.FloatField(blank=True, null=True)
# cache_hits = models.IntegerField(blank=True, null=True)
# cache_misses = models.IntegerField(blank=True, null=True)
# cache_sets = models.IntegerField(blank=True, null=True)
# cache_gets = models.IntegerField(blank=True, null=True)
# cache_get_many = models.IntegerField(blank=True, null=True)
# cache_deletes = models.IntegerField(blank=True, null=True)
# cache_calls = PickledObjectField(compress=True, blank=True, null=True)
#
# def __unicode__(self):
# return u'DebugLogRecord from %s' % self.timestamp
. Output only the next line. | filters[key] = record.msg.pop(key) |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger('debug.logger')
for HandlerClass in LOGGING_CONFIG["LOGGING_HANDLERS"]:
logger.addHandler(HandlerClass)
<|code_end|>
using the current file's imports:
import logging
from django.conf import settings
from django.core.urlresolvers import reverse, NoReverseMatch
from debug_toolbar.toolbar.loader import DebugToolbar
from debug_toolbar.middleware import DebugToolbarMiddleware
from debug_logging.settings import LOGGING_CONFIG
and any relevant context from other files:
# Path: debug_logging/settings.py
# LOGGING_CONFIG = _get_logging_config()
. Output only the next line. | class DebugLoggingMiddleware(DebugToolbarMiddleware): |
Given the code snippet: <|code_start|>
if options['sitemap']:
sitemaps = import_from_string(options['sitemap'])
if isinstance(sitemaps, dict):
for sitemap in sitemaps.values():
urls.extend(map(sitemap.location, sitemap.items()))
elif isinstance(sitemaps, Sitemap):
urls.extend(map(sitemaps.location, sitemaps.items()))
else:
raise CommandError(
'Sitemaps should be a Sitemap object or a dict, got %s '
'instead' % type(sitemaps)
)
self.status_update('Beginning debug logging run...')
client = Client()
if options['username'] and options['password']:
client.login(username=options['username'],
password=options['password'])
for url in urls:
try:
response = client.get(url, DJANGO_DEBUG_LOGGING=True)
except KeyboardInterrupt as e:
if self.has_dbhandler:
# Close out the log entry
test_run.end = datetime.now()
<|code_end|>
, generate the next line using the imports in this file:
import sys
from datetime import datetime
from optparse import make_option
from django.test.client import Client
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sitemaps import Sitemap
from debug_logging.settings import LOGGING_CONFIG
from debug_logging.handlers import DBHandler
from debug_logging.utils import import_from_string
from django.conf import settings
from debug_logging.models import TestRun
from debug_logging.utils import (get_project_name, get_hostname,
get_revision)
and context (functions, classes, or occasionally code) from other files:
# Path: debug_logging/settings.py
# LOGGING_CONFIG = _get_logging_config()
#
# Path: debug_logging/handlers.py
# class DBHandler(logging.Handler):
#
# def emit(self, record):
# if type(record.msg) is dict:
# # Pull the project name, hostname, and revision out of the record
# filters = {}
# for key in ('project_name', 'hostname', 'revision'):
# if record.msg.has_key(key):
# filters[key] = record.msg.pop(key)
#
# # Find the open test run for this project
# try:
# test_run = TestRun.objects.get(end__isnull=True, **filters)
# except TestRun.DoesNotExist:
# # Don't log this request if there isn't an open TestRun
# return
# record.msg['test_run'] = test_run
#
# instance = DebugLogRecord(**record.msg)
# instance.save()
#
# Path: debug_logging/utils.py
# def import_from_string(path):
# i = path.rfind('.')
# module, attr = path[:i], path[i + 1:]
# try:
# mod = import_module(module)
# except ImportError, e:
# raise ImproperlyConfigured(
# 'Error importing module %s: "%s"' % (module, e)
# )
# try:
# instance = getattr(mod, attr)
# except AttributeError:
# raise ImproperlyConfigured(
# 'Module "%s" does not define a "%s" attribute' % (module, attr)
# )
# return instance
. Output only the next line. | test_run.save() |
Next line prediction: <|code_start|> verbosity = int(options.get('verbosity', 1))
self.quiet = verbosity < 1
self.verbose = verbosity > 1
# Dtermine if the DBHandler is used
if True in [isinstance(handler, DBHandler) for handler in
LOGGING_CONFIG["LOGGING_HANDLERS"]]:
self.has_dbhandler = True
else:
self.has_dbhandler = False
# Check for a username without a password, or vice versa
if options['username'] and not options['password']:
raise CommandError('If a username is provided, a password must '
'also be provided.')
if options['password'] and not options['username']:
raise CommandError('If a password is provided, a username must '
'also be provided.')
# Create a TestRun object to track this run
filters = {}
panels = settings.DEBUG_TOOLBAR_PANELS
if 'debug_logging.panels.identity.IdentityLoggingPanel' in panels:
filters['project_name'] = get_project_name()
filters['hostname'] = get_hostname()
if 'debug_logging.panels.revision.RevisionLoggingPanel' in panels:
filters['revision'] = get_revision()
if self.has_dbhandler:
# Check to see if there is already a TestRun object open
<|code_end|>
. Use current file imports:
(import sys
from datetime import datetime
from optparse import make_option
from django.test.client import Client
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sitemaps import Sitemap
from debug_logging.settings import LOGGING_CONFIG
from debug_logging.handlers import DBHandler
from debug_logging.utils import import_from_string
from django.conf import settings
from debug_logging.models import TestRun
from debug_logging.utils import (get_project_name, get_hostname,
get_revision))
and context including class names, function names, or small code snippets from other files:
# Path: debug_logging/settings.py
# LOGGING_CONFIG = _get_logging_config()
#
# Path: debug_logging/handlers.py
# class DBHandler(logging.Handler):
#
# def emit(self, record):
# if type(record.msg) is dict:
# # Pull the project name, hostname, and revision out of the record
# filters = {}
# for key in ('project_name', 'hostname', 'revision'):
# if record.msg.has_key(key):
# filters[key] = record.msg.pop(key)
#
# # Find the open test run for this project
# try:
# test_run = TestRun.objects.get(end__isnull=True, **filters)
# except TestRun.DoesNotExist:
# # Don't log this request if there isn't an open TestRun
# return
# record.msg['test_run'] = test_run
#
# instance = DebugLogRecord(**record.msg)
# instance.save()
#
# Path: debug_logging/utils.py
# def import_from_string(path):
# i = path.rfind('.')
# module, attr = path[:i], path[i + 1:]
# try:
# mod = import_module(module)
# except ImportError, e:
# raise ImproperlyConfigured(
# 'Error importing module %s: "%s"' % (module, e)
# )
# try:
# instance = getattr(mod, attr)
# except AttributeError:
# raise ImproperlyConfigured(
# 'Module "%s" does not define a "%s" attribute' % (module, attr)
# )
# return instance
. Output only the next line. | existing_runs = TestRun.objects.filter(end__isnull=True, **filters) |
Predict the next line after this snippet: <|code_start|> dest='manual_end',
help='End a TestRun that was started manually.'
),
make_option('-n', '--name',
action='store',
dest='name',
metavar='NAME',
help='Add a name to the test run.'
),
make_option('', '--sitemap',
action='store',
dest='sitemap',
metavar='SITEMAP',
help='Load urls from a django sitemap object or dict of sitemaps.'
),
make_option('-d', '--description',
action='store',
dest='description',
metavar='DESC',
help='Add a description to the test run.'
),
make_option('-u', '--username',
action='store',
dest='username',
metavar='USERNAME',
help='Run the test authenticated with the USERNAME provided.'
),
make_option('-p', '--password',
action='store',
dest='password',
<|code_end|>
using the current file's imports:
import sys
from datetime import datetime
from optparse import make_option
from django.test.client import Client
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sitemaps import Sitemap
from debug_logging.settings import LOGGING_CONFIG
from debug_logging.handlers import DBHandler
from debug_logging.utils import import_from_string
from django.conf import settings
from debug_logging.models import TestRun
from debug_logging.utils import (get_project_name, get_hostname,
get_revision)
and any relevant context from other files:
# Path: debug_logging/settings.py
# LOGGING_CONFIG = _get_logging_config()
#
# Path: debug_logging/handlers.py
# class DBHandler(logging.Handler):
#
# def emit(self, record):
# if type(record.msg) is dict:
# # Pull the project name, hostname, and revision out of the record
# filters = {}
# for key in ('project_name', 'hostname', 'revision'):
# if record.msg.has_key(key):
# filters[key] = record.msg.pop(key)
#
# # Find the open test run for this project
# try:
# test_run = TestRun.objects.get(end__isnull=True, **filters)
# except TestRun.DoesNotExist:
# # Don't log this request if there isn't an open TestRun
# return
# record.msg['test_run'] = test_run
#
# instance = DebugLogRecord(**record.msg)
# instance.save()
#
# Path: debug_logging/utils.py
# def import_from_string(path):
# i = path.rfind('.')
# module, attr = path[:i], path[i + 1:]
# try:
# mod = import_module(module)
# except ImportError, e:
# raise ImproperlyConfigured(
# 'Error importing module %s: "%s"' % (module, e)
# )
# try:
# instance = getattr(mod, attr)
# except AttributeError:
# raise ImproperlyConfigured(
# 'Module "%s" does not define a "%s" attribute' % (module, attr)
# )
# return instance
. Output only the next line. | metavar='PASSWORD', |
Predict the next line after this snippet: <|code_start|>
DEBUG=False
class Skeleton(Actor):
def __init__(self,
<|code_end|>
using the current file's imports:
import numpy as np
import fos.util
from pyglet.gl import *
from PySide.QtGui import QMatrix4x4
from fos.shader.lib import *
from fos.vsml import vsml
from .base import *
and any relevant context from other files:
# Path: fos/vsml.py
# DEBUG = False
# MODELVIEW = 0
# PROJECTION = 1
# def normalize(vectarr):
# def __new__(cls, *args, **kwargs):
# def __init__(self):
# def setSize(self, width, height):
# def loadIdentity(self, aType):
# def pushMatrix(self, aType):
# def popMatrix(self, aType):
# def multMatrix(self, aType, aMatrix):
# def get_modelview_matrix(self, array_type=c_float, glGetMethod=glGetFloatv):
# def get_projection_matrix(self, array_type=c_float, glGetMethod=glGetFloatv):
# def get_viewport(self):
# def get_projection(self):
# def get_modelview(self):
# def initUniformLocs(sefl, modelviewLoc, projLoc):
# def initUniformBlock(self, buf, modelviewOffset, projOffset):
# def translate(self, x, y, z, aType = MatrixTypes.MODELVIEW ):
# def scale(self, x, y, z, aType = MatrixTypes.MODELVIEW ):
# def rotate(self, angle, x, y, z, aType = MatrixTypes.MODELVIEW ):
# def loadMatrix(self, aMatrix, aType = MatrixTypes.MODELVIEW ):
# def lookAt(self, xPos, yPos, zPos, xLook, yLook, zLook, xUp, yUp, zUp):
# def perspective(self, fov, ratio, nearp, farp):
# def ortho(self, left, right, top, bottom, nearp=-1.0, farp=1.0):
# def frustum(self, left, right, bottom, top, nearp, farp):
# def matrixToBuffer(self, aType):
# def matrixToUniform(self, aType):
# def matrixToGL(self, aType):
# class VSML(object):
# class MatrixTypes(object):
. Output only the next line. | name, |
Predict the next line after this snippet: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
'''
Wammu - Phone manager
SMS composer
'''
from __future__ import print_function
if Wammu.gammu_error is None:
class MessagePreview(wx.Dialog):
text = '''
<html>
<body>
%s
<center>
<p><wxp module="wx" class="Button">
<param name="id" value="ID_OK">
</wxp></p>
</center>
<|code_end|>
using the current file's imports:
import wx
import wx.lib.editor.editor
import wx.lib.mixins.listctrl
import Wammu
import Wammu.Data
import Wammu.MessageDisplay
import Wammu.Utils
import Wammu.PhoneValidator
import Wammu.Select
import Wammu.EditContactList
import gammu
import Wammu.Locales
from Wammu.Locales import ugettext as _
and any relevant context from other files:
# Path: Wammu/Locales.py
# def ugettext(message):
# if _TRANSLATION:
# if six.PY2:
# return _TRANSLATION.ugettext(message)
# return _TRANSLATION.gettext(message)
# return message
. Output only the next line. | </body> |
Using the snippet: <|code_start|><br><br>
%s
<br><br>
%s
</font>
</p>
<p>
<wxp module="wx" class="Button">
<param name="id" value="ID_OK">
</wxp>
</p>
</center>
</body>
</html>
''' % (colours, '''<img src="%s"><br><h2> Wammu %s</h2>
%s<br>
%s<br>
%s<br>
''' % (Wammu.Paths.AppIconPath('wammu'),
Wammu.__version__,
_('Running on Python %s') % sys.version.split()[0],
_('Using wxPython %s') % wx.VERSION_STRING,
_('Using python-gammu %(python_gammu_version)s and Gammu %(gammu_version)s') % {
'python_gammu_version': gammu.Version()[1],
'gammu_version': gammu.Version()[0]
}),
_('<b>Wammu</b> is a wxPython based GUI for Gammu.'),
copyrightline,
_('''
<|code_end|>
, determine the next line of code. You have imports:
import wx
import wx.html
import wx.lib.wxpTag
import sys
import Wammu
import gammu
import Wammu.Utils
import Wammu.Paths
from Wammu.Locales import ugettext as _
and context (class names, function names, or code) available:
# Path: Wammu/Locales.py
# def ugettext(message):
# if _TRANSLATION:
# if six.PY2:
# return _TRANSLATION.ugettext(message)
# return _TRANSLATION.gettext(message)
# return message
. Output only the next line. | This program is free software: you can redistribute it and/or modify |
Next line prediction: <|code_start|># -*- coding: UTF-8 -*-
#
# Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com>
#
# This file is part of Wammu <https://wammu.eu/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from __future__ import unicode_literals
TEST = 'Příšerně žluťoučký kůň úpěl ďábelské ódy'
class IMAPTest(TestCase):
def test_encode(self):
self.assertEqual(
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from Wammu.IMAP import decoder, encoder)
and context including class names, function names, or small code snippets from other files:
# Path: Wammu/IMAP.py
# def decoder(s):
# r = []
# decode = []
# for c in s:
# if c == '&' and not decode:
# decode.append('&')
# elif c == '-' and decode:
# if len(decode) == 1:
# r.append('&')
# else:
# r.append(modified_unbase64(''.join(decode[1:])))
# decode = []
# elif decode:
# decode.append(c)
# else:
# r.append(c)
# if decode:
# r.append(modified_unbase64(''.join(decode[1:])))
# return (''.join(r), len(s))
#
# def encoder(s):
# r = []
# _in = []
# for c in s:
# if ord(c) in (list(range(0x20, 0x26)) + list(range(0x27, 0x7f))):
# if _in:
# r.extend(['&', modified_base64(''.join(_in)), '-'])
# del _in[:]
# r.append(str(c))
# elif c == '&':
# if _in:
# r.extend(['&', modified_base64(''.join(_in)), '-'])
# del _in[:]
# r.append('&-')
# else:
# _in.append(c)
# if _in:
# r.extend(['&', modified_base64(''.join(_in)), '-'])
# return (''.join(r), len(s))
. Output only the next line. | ('P&AVkA7QFh-ern&ARs- &AX4-lu&AWU-ou&AQ0-k&AP0- k&AW8BSA- &APo-p&ARs-l &AQ8A4Q-belsk&AOk- &APM-dy', 40), |
Predict the next line for this snippet: <|code_start|>
def log_message(agent, message):
agent.log_info('Received: %s' % message)
def annoy(agent, say, more=None):
message = say if not more else say + ' ' + more + '!'
agent.send('annoy', message)
if __name__ == '__main__':
ns = run_nameserver()
orange = run_agent('Orange')
apple = run_agent('Apple')
addr = orange.bind('PUSH', alias='annoy')
apple.connect(addr, handler=log_message)
# Multiple timers with parameters
orange.each(1.0, annoy, 'Hey')
<|code_end|>
with the help of current file imports:
import time
from osbrain import run_agent
from osbrain import run_nameserver
and context from other files:
# Path: osbrain/agent.py
# def run_agent(
# name='',
# nsaddr=None,
# addr=None,
# base=Agent,
# serializer=None,
# transport=None,
# safe=None,
# attributes=None,
# ):
# """
# Ease the agent creation process.
#
# This function will create a new agent, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# name : str, default is ''
# Agent name or alias.
# nsaddr : SocketAddress, default is None
# Name server address.
# addr : SocketAddress, default is None
# New agent address, if it is to be fixed.
# transport : str, AgentAddressTransport, default is None
# Transport protocol.
# safe : bool, default is None
# Use safe calls by default from the Proxy.
# attributes : dict, default is None
# A dictionary that defines initial attributes for the agent.
#
# Returns
# -------
# proxy
# A proxy to the new agent.
# """
# if not nsaddr:
# nsaddr = os.environ.get('OSBRAIN_NAMESERVER_ADDRESS')
# agent = AgentProcess(
# name=name,
# nsaddr=nsaddr,
# addr=addr,
# base=base,
# serializer=serializer,
# transport=transport,
# attributes=attributes,
# )
# agent_name = agent.start()
#
# proxy = Proxy(agent_name, nsaddr, safe=safe)
# proxy.run()
# proxy.wait_for_running()
#
# return proxy
#
# Path: osbrain/nameserver.py
# def run_nameserver(addr=None, base=NameServer):
# """
# Ease the name server creation process.
#
# This function will create a new nameserver, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# addr : SocketAddress, default is None
# Name server address.
#
# Returns
# -------
# proxy
# A proxy to the name server.
# """
# if not addr:
# addr = random_nameserver_process(base=base).addr
# else:
# NameServerProcess(addr, base=base).start()
# return NSProxy(addr)
, which may contain function names, class names, or code. Output only the next line. | orange.each(1.4142, annoy, 'Apple') |
Given snippet: <|code_start|>
def log_a(agent, message):
agent.log_info('Log a: %s' % message)
def log_b(agent, message):
agent.log_info('Log b: %s' % message)
def send_messages(agent):
agent.send('main', 'Apple', topic='a')
agent.send('main', 'Banana', topic='b')
if __name__ == '__main__':
# System deployment
ns = run_nameserver()
alice = run_agent('Alice')
bob = run_agent('Bob')
# System configuration
addr = alice.bind('PUB', alias='main')
alice.each(0.5, send_messages)
bob.connect(addr, alias='listener', handler={'a': log_a})
time.sleep(2)
bob.unsubscribe('listener', 'a')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
from osbrain import run_agent
from osbrain import run_nameserver
and context:
# Path: osbrain/agent.py
# def run_agent(
# name='',
# nsaddr=None,
# addr=None,
# base=Agent,
# serializer=None,
# transport=None,
# safe=None,
# attributes=None,
# ):
# """
# Ease the agent creation process.
#
# This function will create a new agent, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# name : str, default is ''
# Agent name or alias.
# nsaddr : SocketAddress, default is None
# Name server address.
# addr : SocketAddress, default is None
# New agent address, if it is to be fixed.
# transport : str, AgentAddressTransport, default is None
# Transport protocol.
# safe : bool, default is None
# Use safe calls by default from the Proxy.
# attributes : dict, default is None
# A dictionary that defines initial attributes for the agent.
#
# Returns
# -------
# proxy
# A proxy to the new agent.
# """
# if not nsaddr:
# nsaddr = os.environ.get('OSBRAIN_NAMESERVER_ADDRESS')
# agent = AgentProcess(
# name=name,
# nsaddr=nsaddr,
# addr=addr,
# base=base,
# serializer=serializer,
# transport=transport,
# attributes=attributes,
# )
# agent_name = agent.start()
#
# proxy = Proxy(agent_name, nsaddr, safe=safe)
# proxy.run()
# proxy.wait_for_running()
#
# return proxy
#
# Path: osbrain/nameserver.py
# def run_nameserver(addr=None, base=NameServer):
# """
# Ease the name server creation process.
#
# This function will create a new nameserver, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# addr : SocketAddress, default is None
# Name server address.
#
# Returns
# -------
# proxy
# A proxy to the name server.
# """
# if not addr:
# addr = random_nameserver_process(base=base).addr
# else:
# NameServerProcess(addr, base=base).start()
# return NSProxy(addr)
which might include code, classes, or functions. Output only the next line. | bob.subscribe('listener', handler={'b': log_b}) |
Predict the next line after this snippet: <|code_start|>
def log_a(agent, message):
agent.log_info('Log a: %s' % message)
def log_b(agent, message):
agent.log_info('Log b: %s' % message)
def send_messages(agent):
agent.send('main', 'Apple', topic='a')
agent.send('main', 'Banana', topic='b')
if __name__ == '__main__':
# System deployment
ns = run_nameserver()
alice = run_agent('Alice')
bob = run_agent('Bob')
# System configuration
addr = alice.bind('PUB', alias='main')
alice.each(0.5, send_messages)
bob.connect(addr, alias='listener', handler={'a': log_a})
time.sleep(2)
bob.unsubscribe('listener', 'a')
<|code_end|>
using the current file's imports:
import time
from osbrain import run_agent
from osbrain import run_nameserver
and any relevant context from other files:
# Path: osbrain/agent.py
# def run_agent(
# name='',
# nsaddr=None,
# addr=None,
# base=Agent,
# serializer=None,
# transport=None,
# safe=None,
# attributes=None,
# ):
# """
# Ease the agent creation process.
#
# This function will create a new agent, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# name : str, default is ''
# Agent name or alias.
# nsaddr : SocketAddress, default is None
# Name server address.
# addr : SocketAddress, default is None
# New agent address, if it is to be fixed.
# transport : str, AgentAddressTransport, default is None
# Transport protocol.
# safe : bool, default is None
# Use safe calls by default from the Proxy.
# attributes : dict, default is None
# A dictionary that defines initial attributes for the agent.
#
# Returns
# -------
# proxy
# A proxy to the new agent.
# """
# if not nsaddr:
# nsaddr = os.environ.get('OSBRAIN_NAMESERVER_ADDRESS')
# agent = AgentProcess(
# name=name,
# nsaddr=nsaddr,
# addr=addr,
# base=base,
# serializer=serializer,
# transport=transport,
# attributes=attributes,
# )
# agent_name = agent.start()
#
# proxy = Proxy(agent_name, nsaddr, safe=safe)
# proxy.run()
# proxy.wait_for_running()
#
# return proxy
#
# Path: osbrain/nameserver.py
# def run_nameserver(addr=None, base=NameServer):
# """
# Ease the name server creation process.
#
# This function will create a new nameserver, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# addr : SocketAddress, default is None
# Name server address.
#
# Returns
# -------
# proxy
# A proxy to the name server.
# """
# if not addr:
# addr = random_nameserver_process(base=base).addr
# else:
# NameServerProcess(addr, base=base).start()
# return NSProxy(addr)
. Output only the next line. | bob.subscribe('listener', handler={'b': log_b}) |
Continue the code snippet: <|code_start|>
def log_a(agent, message):
agent.log_info('Log a: %s' % message)
def log_b(agent, message):
agent.log_info('Log b: %s' % message)
if __name__ == '__main__':
# System deployment
ns = run_nameserver()
alice = run_agent('Alice')
bob = run_agent('Bob')
eve = run_agent('Eve')
dave = run_agent('Dave')
# System configuration
addr = alice.bind('PUB', alias='main')
bob.connect(addr, handler={'a': log_a, 'b': log_b})
<|code_end|>
. Use current file imports:
import random
import time
from osbrain import run_agent
from osbrain import run_nameserver
and context (classes, functions, or code) from other files:
# Path: osbrain/agent.py
# def run_agent(
# name='',
# nsaddr=None,
# addr=None,
# base=Agent,
# serializer=None,
# transport=None,
# safe=None,
# attributes=None,
# ):
# """
# Ease the agent creation process.
#
# This function will create a new agent, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# name : str, default is ''
# Agent name or alias.
# nsaddr : SocketAddress, default is None
# Name server address.
# addr : SocketAddress, default is None
# New agent address, if it is to be fixed.
# transport : str, AgentAddressTransport, default is None
# Transport protocol.
# safe : bool, default is None
# Use safe calls by default from the Proxy.
# attributes : dict, default is None
# A dictionary that defines initial attributes for the agent.
#
# Returns
# -------
# proxy
# A proxy to the new agent.
# """
# if not nsaddr:
# nsaddr = os.environ.get('OSBRAIN_NAMESERVER_ADDRESS')
# agent = AgentProcess(
# name=name,
# nsaddr=nsaddr,
# addr=addr,
# base=base,
# serializer=serializer,
# transport=transport,
# attributes=attributes,
# )
# agent_name = agent.start()
#
# proxy = Proxy(agent_name, nsaddr, safe=safe)
# proxy.run()
# proxy.wait_for_running()
#
# return proxy
#
# Path: osbrain/nameserver.py
# def run_nameserver(addr=None, base=NameServer):
# """
# Ease the name server creation process.
#
# This function will create a new nameserver, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# addr : SocketAddress, default is None
# Name server address.
#
# Returns
# -------
# proxy
# A proxy to the name server.
# """
# if not addr:
# addr = random_nameserver_process(base=base).addr
# else:
# NameServerProcess(addr, base=base).start()
# return NSProxy(addr)
. Output only the next line. | eve.connect(addr, handler={'a': log_a}) |
Predict the next line after this snippet: <|code_start|>
def log_a(agent, message):
agent.log_info('Log a: %s' % message)
def log_b(agent, message):
agent.log_info('Log b: %s' % message)
if __name__ == '__main__':
# System deployment
ns = run_nameserver()
alice = run_agent('Alice')
bob = run_agent('Bob')
eve = run_agent('Eve')
dave = run_agent('Dave')
# System configuration
addr = alice.bind('PUB', alias='main')
bob.connect(addr, handler={'a': log_a, 'b': log_b})
<|code_end|>
using the current file's imports:
import random
import time
from osbrain import run_agent
from osbrain import run_nameserver
and any relevant context from other files:
# Path: osbrain/agent.py
# def run_agent(
# name='',
# nsaddr=None,
# addr=None,
# base=Agent,
# serializer=None,
# transport=None,
# safe=None,
# attributes=None,
# ):
# """
# Ease the agent creation process.
#
# This function will create a new agent, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# name : str, default is ''
# Agent name or alias.
# nsaddr : SocketAddress, default is None
# Name server address.
# addr : SocketAddress, default is None
# New agent address, if it is to be fixed.
# transport : str, AgentAddressTransport, default is None
# Transport protocol.
# safe : bool, default is None
# Use safe calls by default from the Proxy.
# attributes : dict, default is None
# A dictionary that defines initial attributes for the agent.
#
# Returns
# -------
# proxy
# A proxy to the new agent.
# """
# if not nsaddr:
# nsaddr = os.environ.get('OSBRAIN_NAMESERVER_ADDRESS')
# agent = AgentProcess(
# name=name,
# nsaddr=nsaddr,
# addr=addr,
# base=base,
# serializer=serializer,
# transport=transport,
# attributes=attributes,
# )
# agent_name = agent.start()
#
# proxy = Proxy(agent_name, nsaddr, safe=safe)
# proxy.run()
# proxy.wait_for_running()
#
# return proxy
#
# Path: osbrain/nameserver.py
# def run_nameserver(addr=None, base=NameServer):
# """
# Ease the name server creation process.
#
# This function will create a new nameserver, start the process and then run
# its main loop through a proxy.
#
# Parameters
# ----------
# addr : SocketAddress, default is None
# Name server address.
#
# Returns
# -------
# proxy
# A proxy to the name server.
# """
# if not addr:
# addr = random_nameserver_process(base=base).addr
# else:
# NameServerProcess(addr, base=base).start()
# return NSProxy(addr)
. Output only the next line. | eve.connect(addr, handler={'a': log_a}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.