Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|> def push(register_str, stack_pointer):
register_obj = self.register_str2object[register_str]
data = register_obj.value
# log.debug("\tpush %s with data $%x", register_obj.name, data)
if register_obj.WIDTH == 8:
... | push(REG_CC, register) # 8 bit condition code register |
Next line prediction: <|code_start|> ->
CC bits "HNZVC": -----
"""
assert register in (self.system_stack_pointer, self.user_stack_pointer)
def push(register_str, stack_pointer):
register_obj = self.register_str2object[register_str]
data = register_obj.val... | push(REG_DP, register) # 8 bit direct page register |
Predict the next line for this snippet: <|code_start|> """
All, some, or none of the processor registers are pushed onto stack
(with the exception of stack pointer itself).
A single register may be placed on the stack with the condition codes
set by doing an autodecrement store o... | push(REG_PC, register) # 16 bit program counter register |
Continue the code snippet: <|code_start|> (with the exception of stack pointer itself).
A single register may be placed on the stack with the condition codes
set by doing an autodecrement store onto the stack (example: STX ,--S).
source code forms: b7 b6 b5 b4 b3 b2 b1 b0 PC U Y X DP B ... | push(REG_U, register) # 16 bit user-stack pointer |
Using the snippet: <|code_start|>
source code forms: b7 b6 b5 b4 b3 b2 b1 b0 PC U Y X DP B A CC push order
->
CC bits "HNZVC": -----
"""
assert register in (self.system_stack_pointer, self.user_stack_pointer)
def push(register_str, stack_pointer):
register_o... | push(REG_X, register) # 16 bit index register |
Next line prediction: <|code_start|> A single register may be placed on the stack with the condition codes
set by doing an autodecrement store onto the stack (example: STX ,--S).
source code forms: b7 b6 b5 b4 b3 b2 b1 b0 PC U Y X DP B A CC push order
->
CC bits "HNZVC": -----
... | push(REG_Y, register) # 16 bit index register |
Next line prediction: <|code_start|>
def get_ea_direct(self):
op_addr, m = self.read_pc_byte()
dp = self.direct_page.value
ea = dp << 8 | m
# log.debug("\tget_ea_direct(): ea = dp << 8 | m => $%x=$%x<<8|$%x", ea, dp, m)
return ea
def get_ea_m_direct(self):
ea = ... | 0x03: REG_S, # 16 bit system-stack pointer |
Predict the next line after this snippet: <|code_start|> return m
def get_ea_direct(self):
op_addr, m = self.read_pc_byte()
dp = self.direct_page.value
ea = dp << 8 | m
# log.debug("\tget_ea_direct(): ea = dp << 8 | m => $%x=$%x<<8|$%x", ea, dp, m)
return ea
def... | 0x02: REG_U, # 16 bit user-stack pointer |
Here is a snippet: <|code_start|> ea, m = self.read_pc_word()
# log.debug("\tget_m_immediate_word(): $%x from $%x", m, ea)
return m
def get_ea_direct(self):
op_addr, m = self.read_pc_byte()
dp = self.direct_page.value
ea = dp << 8 | m
# log.debug("\tget_ea_direc... | 0x00: REG_X, # 16 bit index register |
Given the code snippet: <|code_start|># log.debug("\tget_m_immediate_word(): $%x from $%x", m, ea)
return m
def get_ea_direct(self):
op_addr, m = self.read_pc_byte()
dp = self.direct_page.value
ea = dp << 8 | m
# log.debug("\tget_ea_direct(): ea = dp << 8 | m => $%x=... | 0x01: REG_Y, # 16 bit index register |
Given snippet: <|code_start|> return m
INDEX_POSTBYTE2STR = {
0x00: REG_X, # 16 bit index register
0x01: REG_Y, # 16 bit index register
0x02: REG_U, # 16 bit user-stack pointer
0x03: REG_S, # 16 bit system-stack pointer
}
def get_ea_indexed(self):
"""
... | if not is_bit_set(postbyte, bit=7): # bit 7 == 0 |
Predict the next line after this snippet: <|code_start|> INDEX_POSTBYTE2STR = {
0x00: REG_X, # 16 bit index register
0x01: REG_Y, # 16 bit index register
0x02: REG_U, # 16 bit user-stack pointer
0x03: REG_S, # 16 bit system-stack pointer
}
def get_ea_indexed(self):
... | offset = signed5(postbyte & 0x1f) |
Predict the next line after this snippet: <|code_start|># )
return ea
addr_mode = postbyte & 0x0f
self.cycles += 1
offset = None
# TODO: Optimized this, maybe use a dict mapping...
if addr_mode == 0x0:
# log.debug("\t0000 0x0 | ,R+... | offset = signed8(self.accu_b.value) |
Using the snippet: <|code_start|> ea = register_value
register_obj.increment(1)
elif addr_mode == 0x1:
# log.debug("\t0001 0x1 | ,R++ | increment by 2")
ea = register_value
register_obj.increment(2)
self.cycles += 1
elif ... | offset = signed16(self.read_pc_word()[1]) |
Here is a snippet: <|code_start|>#!/usr/bin/env python
"""
MC6809 - 6809 CPU emulator in Python
=======================================
6809 is Big-Endian
Links:
http://dragondata.worldofdragon.org/Publications/inside-dragon.htm
http://www.burgins.com/m6809.html
http://koti.mb... | @opcode( # AND memory with accumulator |
Based on the snippet: <|code_start|># self.program_counter,
# m, r, ea,
# self.cfg.mem_info.get_shortest(ea)
# ))
return ea, r & 0xff
@opcode(0x48, 0x58) # LSLA/ASLA / LSLB/ASLB (inherent)
def instruction_LSL_register(self, opcode, register):
"""
... | self.C = get_bit(a, bit=0) # same as: self.C |= (a & 1) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
"""
DragonPy - Dragon 32 emulator in Python
=======================================
:copyleft: 2013-2015 by the DragonPy team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
... | result = runner.invoke(cli, args) |
Using the snippet: <|code_start|>#!/usr/bin/env python
"""
6809 unittests
~~~~~~~~~~~~~~
:created: 2013-2014 by Jens Diemer - www.jensdiemer.de
:copyleft: 2013-2015 by the MC6809 team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
log = logging... | class Test6809_BranchInstructions(BaseCPUTestCase): |
Given snippet: <|code_start|>#!/usr/bin/env python
"""
6809 unittests
~~~~~~~~~~~~~~
:created: 2013 by Jens Diemer - www.jensdiemer.de
:copyleft: 2013-2014 by the MC6809 team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
log = logging.getLogge... | class Test6809_Register(BaseCPUTestCase): |
Predict the next line after this snippet: <|code_start|> ])
self.assertTST(i)
def test_TSTA(self):
for i in range(255):
self.cpu.accu_a.set(i)
self.cpu.set_cc(0xff) # Set all CC flags
self.cpu_test_run(start=0x1000, end=None, mem=[
... | class Test6809_Stack(BaseStackTestCase): |
Given snippet: <|code_start|>#!/usr/bin/env python
"""
MC6809 - 6809 CPU emulator in Python
=======================================
6809 is Big-Endian
Links:
http://dragondata.worldofdragon.org/Publications/inside-dragon.htm
http://www.burgins.com/m6809.html
http://koti.mbnet.... | @opcode( # Load register from memory |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
MC6809 - 6809 CPU emulator in Python
=======================================
6809 is Big-Endian
Links:
http://dragondata.worldofdragon.org/Publications/inside-dragon.htm
http://www.burgins.com/m6809.html
http://ko... | @opcode( # Jump |
Based on the snippet: <|code_start|>#!/usr/bin/env python
"""
6809 unittests
~~~~~~~~~~~~~~
:created: 2013 by Jens Diemer - www.jensdiemer.de
:copyleft: 2013-2014 by the MC6809 team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
<|code_end|>
, ... | class CCTestCase(BaseCPUTestCase): |
Given the following code snippet before the placeholder: <|code_start|>
class CCTestCase(BaseCPUTestCase):
def test_set_get(self):
for i in range(256):
self.cpu.set_cc(i)
status_byte = self.cpu.get_cc_value()
self.assertEqual(status_byte, i)
def test_HNZVC_8(self):... | if signed8(r) == 0: |
Next line prediction: <|code_start|> self.H = 0 # H - 0x20 - bit 5 - Half-Carry
self.I = 0 # I - 0x10 - bit 4 - IRQ interrupt masked
self.N = 0 # N - 0x08 - bit 3 - Negative result (twos complement)
self.Z = 0 # Z - 0x04 - bit 2 - Zero result
self.V = 0 # V - 0x02 - bit 1 - O... | return cc_value2txt(self.get_cc_value()) |
Next line prediction: <|code_start|>#!/usr/bin/env python
"""
6809 unittests
~~~~~~~~~~~~~~
Test shift / rotate
:created: 2013-2014 by Jens Diemer - www.jensdiemer.de
:copyleft: 2013-2015 by the MC6809 team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more det... | class Test6809_LogicalShift(BaseCPUTestCase): |
Predict the next line for this snippet: <|code_start|> 0x44, # LSRA/ASRA Inherent
])
r = self.cpu.accu_a.value
# print "%02x %s > ASRA > %02x %s -> %s" % (
# i, '{0:08b}'.format(i),
# r, '{0:08b}'.format(r),
# self.cpu.g... | source_bit0 = get_bit(i, bit=0) |
Predict the next line for this snippet: <|code_start|># src, src_bit_str,
# dst, dst_bit_str,
# self.cpu.get_cc_info()
# )
# Bit seven is held constant.
if src_bit_str[0] == "1":
excpeted_bits = f"1{src_bit_str[:-1]}"
... | source_bit0 = is_bit_set(src, bit=0) |
Here is a snippet: <|code_start|>"""
This file was generated with: "Instruction_generator.py"
Please don't change it directly ;)
:copyleft: 2013-2015 by the MC6809 team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
<|code_end|>
. Write the next li... | class PrepagedInstructions(InstructionBase): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
"""
MC6809 - 6809 CPU emulator in Python
=======================================
6809 is Big-Endian
Links:
http://dragondata.worldofdragon.org/Publications/inside-dragon.htm
http://www.burgins.com/m6809.html
http:/... | @opcode( # Compare memory from stack pointer |
Here is a snippet: <|code_start|> """ :returns: basic site properties """
if not hasattr(request, '__main_site_url'):
try:
dom = Site.objects.values_list('domain', flat=True).get(pk=1)
request.__main_site_url = 'http://' + dom
except Site.DoesNotExist:
return {... | request.__homepage_header = get_homepage_header() |
Continue the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
def site_properties(request):
""" :returns: basic site properties """
if not hasattr(request, '__main_site_url'):
try:
dom = Site.objects.values_list('domain', flat=True).get(pk=1)
request.__main_... | if Footer.objects.exists(): |
Predict the next line for this snippet: <|code_start|>urlpatterns += patterns(
'',
# We don't want to presume how your homepage works, so here are a
# few patterns you can use to set it up.
# HOMEPAGE AS STATIC TEMPLATE
# ---------------------------
# This pattern simply loads the index.html t... | url(r'^events/event/(?P<event_slug>[\w-]+)/(?P<pk>\d+)/$', OccuranceJDView.as_view(), name='fullcalendar-occurrence'), |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger(__name__)
def get_homepage_id():
homepage = HomePage.objects.values_list('id').first()
if homepage is not None:
return homepage[0]
pages = RichTextPage.objects.filter(slug='/')
if pages.exists():
ret... | image = PageHeaderImage.objects.filter(page=page).order_by('?').first() |
Predict the next line for this snippet: <|code_start|>"""
Mezzanine page processors for jdpages.
Read the mezzanine documentation for more info.
"""
logger = logging.getLogger(__name__)
@processor_for(Form)
@processor_for(HomePage)
@processor_for(VisionPage)
@processor_for(VisionsPage)
@processor_for(OrganisationP... | @processor_for(BlogCategoryPage) |
Given the code snippet: <|code_start|>"""
Mezzanine page processors for jdpages.
Read the mezzanine documentation for more info.
"""
logger = logging.getLogger(__name__)
@processor_for(Form)
<|code_end|>
, generate the next line using the imports in this file:
import logging
from mezzanine.blog.views import blog_... | @processor_for(HomePage) |
Continue the code snippet: <|code_start|>"""
Mezzanine page processors for jdpages.
Read the mezzanine documentation for more info.
"""
logger = logging.getLogger(__name__)
@processor_for(Form)
@processor_for(HomePage)
@processor_for(VisionPage)
@processor_for(VisionsPage)
<|code_end|>
. Use current file imports:
... | @processor_for(OrganisationPage) |
Given snippet: <|code_start|>"""
Mezzanine page processors for jdpages.
Read the mezzanine documentation for more info.
"""
logger = logging.getLogger(__name__)
@processor_for(Form)
@processor_for(HomePage)
@processor_for(VisionPage)
@processor_for(VisionsPage)
@processor_for(OrganisationPage)
<|code_end|>
, conti... | @processor_for(OrganisationPartPage) |
Based on the snippet: <|code_start|>"""
Mezzanine page processors for jdpages.
Read the mezzanine documentation for more info.
"""
logger = logging.getLogger(__name__)
@processor_for(Form)
@processor_for(HomePage)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from mezzani... | @processor_for(VisionPage) |
Here is a snippet: <|code_start|>"""
Mezzanine page processors for jdpages.
Read the mezzanine documentation for more info.
"""
logger = logging.getLogger(__name__)
@processor_for(Form)
@processor_for(HomePage)
@processor_for(VisionPage)
<|code_end|>
. Write the next line using the current file imports:
import lo... | @processor_for(VisionsPage) |
Given the following code snippet before the placeholder: <|code_start|>"""
Mezzanine page processors for jdpages.
Read the mezzanine documentation for more info.
"""
logger = logging.getLogger(__name__)
@processor_for(Form)
@processor_for(HomePage)
@processor_for(VisionPage)
@processor_for(VisionsPage)
@processor_... | @processor_for(WordLidPage) |
Using the snippet: <|code_start|>"""
Mezzanine page processors for jdpages.
Read the mezzanine documentation for more info.
"""
logger = logging.getLogger(__name__)
@processor_for(Form)
@processor_for(HomePage)
@processor_for(VisionPage)
@processor_for(VisionsPage)
@processor_for(OrganisationPage)
@processor_for(O... | page_header = get_page_header(page) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
session = Table("webtools_session", Base.metadata,
Column("id", Integer, primary_key=True, autoincrement=False),
Column("last_modify", DateTime(timezone=True), index=True),
Column("key", Unicode(length=100), unique=True, index=True),
Column("d... | class DatabaseEngine(BaseSessionEngine): |
Given the code snippet: <|code_start|>
Developers creating new command base classes (such as
:class:`Lister` and :class:`ShowOne`) should override this
method to wrap :meth:`take_action`.
"""
self.take_action(parsed_args)
return 0
class CommandManager(object):
comma... | klass = load_class(class_path) |
Based on the snippet: <|code_start|> """
if default is None:
default = self.conf.I18N_DEFAULT_LANG
return super(I18nMixin, self).get_browser_locale(default=default)
def get_user_locale(self):
if "webtools_locale" in self.session:
return locale.get(self.session... | return get_timezone(self.session["webtools_timezone"]) |
Given snippet: <|code_start|>def get_app():
global _global_app
if _global_app is None:
raise RuntimeError("Application is not initialized")
return _global_app
def set_app(_app):
global _global_app
_global_app = _app
def del_app():
global _global_app
_global_app = None
class Appl... | handlers = load_class(handlers + ".patterns") |
Given snippet: <|code_start|>
if not self.conf.INSTALLED_MODULES:
raise RuntimeError("INSTALLED_MODULES is mandatory setting.")
# setup module template loader
for module_path in self.conf.INSTALLED_MODULES:
print("Setup {0} module...".format(module_path))
mo... | if Library._instance: |
Next line prediction: <|code_start|>
class RunserverCommand(Command):
def take_action(self, options):
if not options.settings:
raise RuntimeError("For start serverm --settings parameter"
" is mandatory!")
try:
<|code_end|>
. Use current file imports:
(f... | settings_cls = load_class(options.settings) |
Predict the next line for this snippet: <|code_start|>
@jinja2.contextfunction
def ugettext(context, message, plural_message=None, count=None):
"""
Translate template text tu current locale.
"""
handler = context["handler"]
return handler.locale.translate(message, plural_message=plural_message, cou... | return as_localtime(value, timezone) |
Here is a snippet: <|code_start|>
@jinja2.contextfunction
def ugettext(context, message, plural_message=None, count=None):
"""
Translate template text tu current locale.
"""
handler = context["handler"]
return handler.locale.translate(message, plural_message=plural_message, count=count)
@jinja2.c... | if is_naive(value): |
Given snippet: <|code_start|>
@jinja2.contextfunction
def ugettext(context, message, plural_message=None, count=None):
"""
Translate template text tu current locale.
"""
handler = context["handler"]
return handler.locale.translate(message, plural_message=plural_message, count=count)
@jinja2.conte... | value = make_aware(value, get_default_timezone(handler.application)) |
Given the code snippet: <|code_start|>
@jinja2.contextfunction
def ugettext(context, message, plural_message=None, count=None):
"""
Translate template text tu current locale.
"""
handler = context["handler"]
return handler.locale.translate(message, plural_message=plural_message, count=count)
@jin... | timezone = get_timezone(tz) |
Predict the next line for this snippet: <|code_start|>
@jinja2.contextfunction
def ugettext(context, message, plural_message=None, count=None):
"""
Translate template text tu current locale.
"""
handler = context["handler"]
return handler.locale.translate(message, plural_message=plural_message, cou... | value = make_aware(value, get_default_timezone(handler.application)) |
Based on the snippet: <|code_start|>
class BaseAuthenticationBackend(object):
def __init__(self, application):
self.application = application
def authenticate(self, username=None, password=None):
raise NotImplementedError()
class DatabaseAuthenticationBackend(BaseAuthenticationBackend):
... | user = self.application.db.query(User).filter(User.username == username).one() |
Based on the snippet: <|code_start|>
class BaseAuthenticationBackend(object):
def __init__(self, application):
self.application = application
def authenticate(self, username=None, password=None):
raise NotImplementedError()
class DatabaseAuthenticationBackend(BaseAuthenticationBackend):
... | return user if check_password(password, user.password) else None |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(Unicode(200), nullable=False, index=True)
first_name = Column(Unicode(200), nullable=False)
last... | self.password = make_password(password) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(Unicode(200), nullable=False, index=True)
first_name = Column(Unicode(200), nullable=False)
last_name = Column(Unico... | def check_password(self, password): |
Given the code snippet: <|code_start|> return super(FormDataMeta, cls).__new__(cls, name, bases, attrs)
class FormDataBase(object):
def __init__(self, handler=None, initial={}, prefix=None):
self.handler = handler
self.initial = initial
self.prefix = None
self.errors = {}
... | except ValidateError as e: |
Given snippet: <|code_start|> self.errors[field_name] = list(e.args)
def _form_validate(self):
try:
self.cleaned_data = self.clean()
except ValidateError as e:
self.errors["__global__"] = list(e.args)
def clean(self):
return self.cleaned_data
... | return BoundField(name, self.with_prefix(name), self.base_fields[name], self) |
Predict the next line for this snippet: <|code_start|>
class Field(object):
def __init__(self, datatype, widget=None, required=True, default=None):
assert isinstance(datatype, data_types.Type), "datatype must be a instance of Type"
self.datatype = datatype
self.default = default
self... | assert isinstance(self.widget, Widget), "widget must be a instance of Widget" |
Predict the next line for this snippet: <|code_start|>
class Field(object):
def __init__(self, datatype, widget=None, required=True, default=None):
assert isinstance(datatype, data_types.Type), "datatype must be a instance of Type"
self.datatype = datatype
self.default = default
self... | raise ValidateError("this field is required") |
Continue the code snippet: <|code_start|>
def locale_to_code(locale):
"""
Get main code from locale object.
"""
code = locale.code
return code.split("_")[0]
class LocaleService(object):
def get_format(self, format_name, lang=None, handler=None):
"""
Get format by name from glo... | format_name = smart_text(format_name) |
Given the following code snippet before the placeholder: <|code_start|>
class AuthDatabaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = Application(TestOverwriteSettings())
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from webtools.... | Base.metadata.create_all(cls.app.engine) |
Given the following code snippet before the placeholder: <|code_start|>
class AuthDatabaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = Application(TestOverwriteSettings())
Base.metadata.create_all(cls.app.engine)
@classmethod
def tearDownClass(cls):
Ba... | self.app.db.query(User).delete() |
Predict the next line for this snippet: <|code_start|>
class AuthDatabaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
<|code_end|>
with the help of current file imports:
import unittest
from webtools.database import Base
from webtools.auth.models import User
from .settings import TestOverwrit... | cls.app = Application(TestOverwriteSettings()) |
Here is a snippet: <|code_start|>
class HandlerMock(object):
def __init__(self, arguments):
self.arguments = arguments
def get_arguments(self, name):
if name not in self.arguments:
return []
value = self.arguments[name]
if not isinstance(value, (list, tuple)):
... | class TestForm1(FormData): |
Given the code snippet: <|code_start|>
class HandlerMock(object):
def __init__(self, arguments):
self.arguments = arguments
def get_arguments(self, name):
if name not in self.arguments:
return []
value = self.arguments[name]
if not isinstance(value, (list, tuple)):
... | field1 = Field(types.Unicode()) |
Based on the snippet: <|code_start|>
class HandlerMock(object):
def __init__(self, arguments):
self.arguments = arguments
def get_arguments(self, name):
if name not in self.arguments:
return []
value = self.arguments[name]
if not isinstance(value, (list, tuple)):
... | field1 = Field(types.Unicode()) |
Continue the code snippet: <|code_start|> self.assertFalse(form.errors)
self.assertTrue(form.is_valid())
def test_simple_validate_02(self):
handler = HandlerMock({"field1": "Hola", "field2": "A"})
form = TestForm1(handler)
form.validate()
self.assertTrue(form._valida... | fl1 = Field(types.Unicode(), widget=widgets.InputText) |
Predict the next line for this snippet: <|code_start|> def write(self, chuck):
self.buffer.write(chuck)
def get_current_user(self):
return None
class DefaultTemplateTests(TestCase):
@classmethod
def setUpClass(cls):
cls.app = Application(TestOverwriteSettings())
def setUp(... | Base.metadata.create_all(cls.app.engine) |
Continue the code snippet: <|code_start|>
def test_render(self):
self.handler.render("test.html", {"name":"foo"})
result = self.handler.buffer.getvalue()
self.assertEqual(result, "Hello foo")
def test_render_to_string(self):
result = self.handler.render_to_string("test.html", {"... | now_value = timezone.now() |
Predict the next line after this snippet: <|code_start|>
class ResponseMock(ResponseHandlerMixin, I18nMixin, TimezoneMixin, BaseHandler):
buffer = io.StringIO()
context_processors = []
def __init__(self):
pass
def write(self, chuck):
self.buffer.write(chuck)
def get_current_use... | cls.app = Application(TestOverwriteSettings()) |
Next line prediction: <|code_start|>
class Type(object):
"""
Base class for all type conversion
for a formdata.
"""
def to_python(self, value, field):
return value
def from_python(self, value):
return value
class Integer(Type):
def to_python(self, value, field):
i... | raise ValidateError("Invalid data") |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class AuthHandlerMixin(object):
def authenticate(self, username, password):
user = self.application.authenticate(username=username, password=password)
if user is not None:
self.session["user_id"] = user.id... | self._user = self.db.query(User).filter(User.id == self.session["user_id"]).one() |
Given the following code snippet before the placeholder: <|code_start|> """
algorithm = "bcrypt"
library = ("py-bcrypt", "bcrypt")
rounds = 12
def salt(self):
bcrypt = self._load_library()
return bcrypt.gensalt(self.rounds)
def encode(self, password, salt):
bcrypt = self... | hash = hashlib.sha1(smart_bytes(salt + password)).hexdigest() |
Using the snippet: <|code_start|> """
raise NotImplementedError()
def encode(self, password, salt):
"""
Creates an encoded database value
The result is normally formatted as "algorithm$salt$hash" and
must be fewer than 128 characters.
"""
raise NotImp... | hash = pbkdf2(password, salt, iterations, digest=self.digest) |
Next line prediction: <|code_start|> must be fewer than 128 characters.
"""
raise NotImplementedError()
class PBKDF2PasswordHasher(BasePasswordHasher):
"""
Secure password hashing using the PBKDF2 algorithm (recommended)
Configured to use PBKDF2 + HMAC + SHA256 with 10000 iteration... | return constant_time_compare(encoded, encoded_2) |
Given the following code snippet before the placeholder: <|code_start|> """
Abstract base class for password hashers
When creating your own hasher, you need to override algorithm,
verify(), encode() and safe_summary().
PasswordHasher objects are immutable.
"""
algorithm = None
library =... | return get_random_string() |
Given snippet: <|code_start|>
class DatabaseSessionTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = Application(TestOverwriteSettings())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import copy
from webtools.database import ... | Base.metadata.create_all(cls.app.engine) |
Given snippet: <|code_start|>
class DatabaseSessionTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import copy
from webtools.database import Base
from ..settings import TestOverwriteSettings
... | cls.app = Application(TestOverwriteSettings()) |
Using the snippet: <|code_start|>
class SyncdbCommand(Command):
"""
Syncronize all available sqlalchemy defined tables
to a database server.
"""
def take_action(self, options):
if not self.cmdapp.conf:
raise RuntimeError("For start serverm --settings parameter"
... | for tbl in Base.metadata.sorted_tables: |
Given the code snippet: <|code_start|>except NotImplementedError:
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
_trans_5c = bytearray([(x ^ 0x5C) for x in range(256)])
_trans_36 = bytear... | return hmac.new(key, msg=smart_bytes(value), digestmod=hashlib.sha1) |
Given the code snippet: <|code_start|>"""Test QtPrintSupport."""
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert... | sys.platform.startswith('linux') and not_using_conda(), |
Here is a snippet: <|code_start|>
class TestXSettings(TestWithSession):
def test_basic_set_get(self):
blob = "asdfwheeeee"
<|code_end|>
. Write the next line using the current file imports:
from wimpiggy.test import *
from xpra.xposix.xsettings import XSettingsManager, XSettingsWatcher
import gtk
and con... | manager = XSettingsManager(blob) |
Using the snippet: <|code_start|>
class TestXSettings(TestWithSession):
def test_basic_set_get(self):
blob = "asdfwheeeee"
manager = XSettingsManager(blob)
<|code_end|>
, determine the next line of code. You have imports:
from wimpiggy.test import *
from xpra.xposix.xsettings import XSettingsManag... | watcher = XSettingsWatcher() |
Continue the code snippet: <|code_start|># This file is part of Parti.
# Copyright (C) 2008, 2009 Nathaniel Smith <njs@pobox.com>
# Parti is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
def spawn_repl_window(wm, namespace):
window = Pseudoc... | view = IPythonView() |
Given snippet: <|code_start|> for var, value in os.environ.iteritems():
# :-separated envvars that people might change while their server is
# going:
if var in ("PATH", "LD_LIBRARY_PATH", "PYTHONPATH"):
script.append("%s=%s:\"$%s\"; export %s\n"
% (var, s... | dotxpra = DotXpra() |
Given the code snippet: <|code_start|> print "--exit-with-children specified without any children to spawn; exiting immediately"
return
atexit.register(run_cleanups)
signal.signal(signal.SIGINT, deadly_signal)
signal.signal(signal.SIGTERM, deadly_signal)
assert mode in ("start", "upgrad... | except ServerSockInUse: |
Given snippet: <|code_start|># This file is part of Parti.
# Copyright (C) 2008, 2009 Nathaniel Smith <njs@pobox.com>
# Parti is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
class TestSelection(TestWithSession, MockEventReceiver):
def test... | m1 = ManagerSelection(d1, "WM_S0") |
Next line prediction: <|code_start|># This file is part of Parti.
# Copyright (C) 2008, 2009 Nathaniel Smith <njs@pobox.com>
# Parti is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
class TestSelection(TestWithSession, MockEventReceiver):
d... | assert_raises(AlreadyOwned, m2.acquire, m2.IF_UNOWNED) |
Given the following code snippet before the placeholder: <|code_start|> if default_display is not None:
default_display.close()
# This line is critical, because many gtk functions (even
# _for_display/_for_screen functions) actually use the default
# display, even if only temp... | "child-map-request-event": one_arg_signal, |
Using the snippet: <|code_start|> self.logger.error("Unable to connect to couchpotato")
self.logger.debug("connection-URL: " + url)
return
@cherrypy.expose()
@require()
@cherrypy.tools.json_out()
def getapikey(self, couchpotato_username, couchpotato_password, couchpot... | return get_image(url, h, w, o) |
Given the code snippet: <|code_start|>
if 'addedAt'in album:
jalbum['addedAt'] = album["addedAt"]
albums.append(jalbum)
return {'albums': sorted(albums, key=lambda k: k['addedAt'], reverse=True)[:int(limit)]}
except Except... | return get_image(url, h, w, o, headers=self.getHeaders()) |
Predict the next line after this snippet: <|code_start|> return
@cherrypy.expose()
@require()
@cherrypy.tools.json_out()
def changeserver(self, id=0):
try:
self.current = XbmcServers.selectBy(id=id).getOne()
htpc.settings.set('xbmc_current_server', str(id))
... | return get_image(url, h, w, o, self.auth()) |
Using the snippet: <|code_start|> self.git = htpc.settings.get('git_path', 'git')
self.logger = logging.getLogger('htpc.updater')
def current(self):
""" Get hash of current Git commit """
self.logger.debug('Getting current version.')
output = self.git_exec('rev-parse HEAD')
... | do_restart() |
Given snippet: <|code_start|>
class Search:
def __init__(self):
self.logger = logging.getLogger('modules.search')
htpc.MODULES.append({
'name': 'Newznab',
'id': 'nzbsearch',
'fields': [
{'type':'bool', 'label':'Enable', 'name':'nzbsearch_... | return get_image(url, h, w, o)
|
Given snippet: <|code_start|>
def send_email(to_email, subject, body):
try:
logging.debug('send_email start...')
msg = MIMEMultipart()
msg['From'] = config.self_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
if conf... | raise CusException('send_email', 'send_email error msg:%s' % e) |
Here is a snippet: <|code_start|>#-*- coding: utf-8 -*-
matplotlib.use('Agg')
# 注意考虑到多个商品对比的情况
class Analysis(object):
def __init__(self, **kwargs):
self.sql = kwargs.get('sql')
self.guid = kwargs.get('guid')
self.product_id = kwargs.get('product_id')
self.url = kwargs.get('url... | self.font_path = '%s/font/%s' % (settings.BASE_DIR, self.font_name) |
Next line prediction: <|code_start|> self.guid = kwargs.get('guid')
self.product_id = kwargs.get('product_id')
self.url = kwargs.get('url')
# self.product_id = '3995645'
# self.product_id = '10213303572'
self.font_name = 'DroidSansFallback.ttf'
self.font_path = '%s... | raise CusException('analysis_init', 'analysis_init error:%s' % e) |
Using the snippet: <|code_start|>#-*- coding: utf-8 -*-
class JDVisitMiddleware(MiddlewareMixin):
def process_request(self, request):
page = request.path
if 'runspider' in page and request.method == 'POST':
ip = utils.get_visiter_ip(request)
user_agent = request.META.get(... | visit = JDVisit(id = None, ip = ip, ip_address = '', visit_time = vt, user_agent = user_agent, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.