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:
self.push_byte(register, data)
else:
assert register_obj.WIDTH == 16
self.push_word(register, data)
# log.debug("$%x PSH%s post byte: $%x", self.program_counter, register.name, m)
# m = postbyte
if m & 0x80:
push(REG_PC, register) # 16 bit program counter register
if m & 0x40:
push(REG_U, register) # 16 bit user-stack pointer
if m & 0x20:
push(REG_Y, register) # 16 bit index register
if m & 0x10:
push(REG_X, register) # 16 bit index register
if m & 0x08:
push(REG_DP, register) # 8 bit direct page register
if m & 0x04:
push(REG_B, register) # 8 bit accumulator
if m & 0x02:
push(REG_A, register) # 8 bit accumulator
if m & 0x01:
<|code_end|>
. Use current file imports:
(from MC6809.components.cpu_utils.instruction_caller import opcode
from MC6809.components.MC6809data.MC6809_op_data import REG_A, REG_B, REG_CC, REG_DP, REG_PC, REG_U, REG_X, REG_Y)
and context including class names, function names, or small code snippets from other files:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
#
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_A = "A"
#
# REG_B = "B"
#
# REG_CC = "CC"
#
# REG_DP = "DP"
#
# REG_PC = "PC"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
. Output only the next line. | 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.value
# log.debug("\tpush %s with data $%x", register_obj.name, data)
if register_obj.WIDTH == 8:
self.push_byte(register, data)
else:
assert register_obj.WIDTH == 16
self.push_word(register, data)
# log.debug("$%x PSH%s post byte: $%x", self.program_counter, register.name, m)
# m = postbyte
if m & 0x80:
push(REG_PC, register) # 16 bit program counter register
if m & 0x40:
push(REG_U, register) # 16 bit user-stack pointer
if m & 0x20:
push(REG_Y, register) # 16 bit index register
if m & 0x10:
push(REG_X, register) # 16 bit index register
if m & 0x08:
<|code_end|>
. Use current file imports:
(from MC6809.components.cpu_utils.instruction_caller import opcode
from MC6809.components.MC6809data.MC6809_op_data import REG_A, REG_B, REG_CC, REG_DP, REG_PC, REG_U, REG_X, REG_Y)
and context including class names, function names, or small code snippets from other files:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
#
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_A = "A"
#
# REG_B = "B"
#
# REG_CC = "CC"
#
# REG_DP = "DP"
#
# REG_PC = "PC"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
. Output only the next line. | 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 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": -----
"""
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.value
# log.debug("\tpush %s with data $%x", register_obj.name, data)
if register_obj.WIDTH == 8:
self.push_byte(register, data)
else:
assert register_obj.WIDTH == 16
self.push_word(register, data)
# log.debug("$%x PSH%s post byte: $%x", self.program_counter, register.name, m)
# m = postbyte
if m & 0x80:
<|code_end|>
with the help of current file imports:
from MC6809.components.cpu_utils.instruction_caller import opcode
from MC6809.components.MC6809data.MC6809_op_data import REG_A, REG_B, REG_CC, REG_DP, REG_PC, REG_U, REG_X, REG_Y
and context from other files:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
#
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_A = "A"
#
# REG_B = "B"
#
# REG_CC = "CC"
#
# REG_DP = "DP"
#
# REG_PC = "PC"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
, which may contain function names, class names, or code. Output only the next line. | 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 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_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:
self.push_byte(register, data)
else:
assert register_obj.WIDTH == 16
self.push_word(register, data)
# log.debug("$%x PSH%s post byte: $%x", self.program_counter, register.name, m)
# m = postbyte
if m & 0x80:
push(REG_PC, register) # 16 bit program counter register
if m & 0x40:
<|code_end|>
. Use current file imports:
from MC6809.components.cpu_utils.instruction_caller import opcode
from MC6809.components.MC6809data.MC6809_op_data import REG_A, REG_B, REG_CC, REG_DP, REG_PC, REG_U, REG_X, REG_Y
and context (classes, functions, or code) from other files:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
#
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_A = "A"
#
# REG_B = "B"
#
# REG_CC = "CC"
#
# REG_DP = "DP"
#
# REG_PC = "PC"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
. Output only the next line. | 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_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:
self.push_byte(register, data)
else:
assert register_obj.WIDTH == 16
self.push_word(register, data)
# log.debug("$%x PSH%s post byte: $%x", self.program_counter, register.name, m)
# m = postbyte
if m & 0x80:
push(REG_PC, register) # 16 bit program counter register
if m & 0x40:
push(REG_U, register) # 16 bit user-stack pointer
if m & 0x20:
push(REG_Y, register) # 16 bit index register
if m & 0x10:
<|code_end|>
, determine the next line of code. You have imports:
from MC6809.components.cpu_utils.instruction_caller import opcode
from MC6809.components.MC6809data.MC6809_op_data import REG_A, REG_B, REG_CC, REG_DP, REG_PC, REG_U, REG_X, REG_Y
and context (class names, function names, or code) available:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
#
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_A = "A"
#
# REG_B = "B"
#
# REG_CC = "CC"
#
# REG_DP = "DP"
#
# REG_PC = "PC"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
. Output only the next line. | 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": -----
"""
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.value
# log.debug("\tpush %s with data $%x", register_obj.name, data)
if register_obj.WIDTH == 8:
self.push_byte(register, data)
else:
assert register_obj.WIDTH == 16
self.push_word(register, data)
# log.debug("$%x PSH%s post byte: $%x", self.program_counter, register.name, m)
# m = postbyte
if m & 0x80:
push(REG_PC, register) # 16 bit program counter register
if m & 0x40:
push(REG_U, register) # 16 bit user-stack pointer
if m & 0x20:
<|code_end|>
. Use current file imports:
(from MC6809.components.cpu_utils.instruction_caller import opcode
from MC6809.components.MC6809data.MC6809_op_data import REG_A, REG_B, REG_CC, REG_DP, REG_PC, REG_U, REG_X, REG_Y)
and context including class names, function names, or small code snippets from other files:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
#
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_A = "A"
#
# REG_B = "B"
#
# REG_CC = "CC"
#
# REG_DP = "DP"
#
# REG_PC = "PC"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
. Output only the next line. | 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 = self.get_ea_direct()
m = self.memory.read_byte(ea)
# log.debug("\tget_ea_m_direct(): ea=$%x m=$%x", ea, m)
return ea, m
def get_m_direct(self):
ea = self.get_ea_direct()
m = self.memory.read_byte(ea)
# log.debug("\tget_m_direct(): $%x from $%x", m, ea)
return m
def get_m_direct_word(self):
ea = self.get_ea_direct()
m = self.memory.read_word(ea)
# log.debug("\tget_m_direct(): $%x from $%x", m, ea)
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
<|code_end|>
. Use current file imports:
(from MC6809.components.MC6809data.MC6809_op_data import REG_S, REG_U, REG_X, REG_Y
from MC6809.utils.bits import is_bit_set
from MC6809.utils.byte_word_values import signed5, signed8, signed16)
and context including class names, function names, or small code snippets from other files:
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_S = "S"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
#
# Path: MC6809/utils/bits.py
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
#
# Path: MC6809/utils/byte_word_values.py
# def signed5(x):
# """ convert to signed 5-bit """
# if x > 0xf: # 0xf == 2**4-1 == 15
# x = x - 0x20 # 0x20 == 2**5 == 32
# return x
#
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
#
# def signed16(x):
# """ convert to signed 16-bit """
# if x > 0x7fff: # 0x7fff == 2**15-1 == 32767
# x = x - 0x10000 # 0x100 == 2**16 == 65536
# return x
. Output only the next line. | 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 get_ea_m_direct(self):
ea = self.get_ea_direct()
m = self.memory.read_byte(ea)
# log.debug("\tget_ea_m_direct(): ea=$%x m=$%x", ea, m)
return ea, m
def get_m_direct(self):
ea = self.get_ea_direct()
m = self.memory.read_byte(ea)
# log.debug("\tget_m_direct(): $%x from $%x", m, ea)
return m
def get_m_direct_word(self):
ea = self.get_ea_direct()
m = self.memory.read_word(ea)
# log.debug("\tget_m_direct(): $%x from $%x", m, ea)
return m
INDEX_POSTBYTE2STR = {
0x00: REG_X, # 16 bit index register
0x01: REG_Y, # 16 bit index register
<|code_end|>
using the current file's imports:
from MC6809.components.MC6809data.MC6809_op_data import REG_S, REG_U, REG_X, REG_Y
from MC6809.utils.bits import is_bit_set
from MC6809.utils.byte_word_values import signed5, signed8, signed16
and any relevant context from other files:
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_S = "S"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
#
# Path: MC6809/utils/bits.py
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
#
# Path: MC6809/utils/byte_word_values.py
# def signed5(x):
# """ convert to signed 5-bit """
# if x > 0xf: # 0xf == 2**4-1 == 15
# x = x - 0x20 # 0x20 == 2**5 == 32
# return x
#
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
#
# def signed16(x):
# """ convert to signed 16-bit """
# if x > 0x7fff: # 0x7fff == 2**15-1 == 32767
# x = x - 0x10000 # 0x100 == 2**16 == 65536
# return x
. Output only the next line. | 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_direct(): ea = dp << 8 | m => $%x=$%x<<8|$%x", ea, dp, m)
return ea
def get_ea_m_direct(self):
ea = self.get_ea_direct()
m = self.memory.read_byte(ea)
# log.debug("\tget_ea_m_direct(): ea=$%x m=$%x", ea, m)
return ea, m
def get_m_direct(self):
ea = self.get_ea_direct()
m = self.memory.read_byte(ea)
# log.debug("\tget_m_direct(): $%x from $%x", m, ea)
return m
def get_m_direct_word(self):
ea = self.get_ea_direct()
m = self.memory.read_word(ea)
# log.debug("\tget_m_direct(): $%x from $%x", m, ea)
return m
INDEX_POSTBYTE2STR = {
<|code_end|>
. Write the next line using the current file imports:
from MC6809.components.MC6809data.MC6809_op_data import REG_S, REG_U, REG_X, REG_Y
from MC6809.utils.bits import is_bit_set
from MC6809.utils.byte_word_values import signed5, signed8, signed16
and context from other files:
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_S = "S"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
#
# Path: MC6809/utils/bits.py
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
#
# Path: MC6809/utils/byte_word_values.py
# def signed5(x):
# """ convert to signed 5-bit """
# if x > 0xf: # 0xf == 2**4-1 == 15
# x = x - 0x20 # 0x20 == 2**5 == 32
# return x
#
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
#
# def signed16(x):
# """ convert to signed 16-bit """
# if x > 0x7fff: # 0x7fff == 2**15-1 == 32767
# x = x - 0x10000 # 0x100 == 2**16 == 65536
# return x
, which may include functions, classes, or code. Output only the next line. | 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=$%x<<8|$%x", ea, dp, m)
return ea
def get_ea_m_direct(self):
ea = self.get_ea_direct()
m = self.memory.read_byte(ea)
# log.debug("\tget_ea_m_direct(): ea=$%x m=$%x", ea, m)
return ea, m
def get_m_direct(self):
ea = self.get_ea_direct()
m = self.memory.read_byte(ea)
# log.debug("\tget_m_direct(): $%x from $%x", m, ea)
return m
def get_m_direct_word(self):
ea = self.get_ea_direct()
m = self.memory.read_word(ea)
# log.debug("\tget_m_direct(): $%x from $%x", m, ea)
return m
INDEX_POSTBYTE2STR = {
0x00: REG_X, # 16 bit index register
<|code_end|>
, generate the next line using the imports in this file:
from MC6809.components.MC6809data.MC6809_op_data import REG_S, REG_U, REG_X, REG_Y
from MC6809.utils.bits import is_bit_set
from MC6809.utils.byte_word_values import signed5, signed8, signed16
and context (functions, classes, or occasionally code) from other files:
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_S = "S"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
#
# Path: MC6809/utils/bits.py
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
#
# Path: MC6809/utils/byte_word_values.py
# def signed5(x):
# """ convert to signed 5-bit """
# if x > 0xf: # 0xf == 2**4-1 == 15
# x = x - 0x20 # 0x20 == 2**5 == 32
# return x
#
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
#
# def signed16(x):
# """ convert to signed 16-bit """
# if x > 0x7fff: # 0x7fff == 2**15-1 == 32767
# x = x - 0x10000 # 0x100 == 2**16 == 65536
# return x
. Output only the next line. | 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):
"""
Calculate the address for all indexed addressing modes
"""
addr, postbyte = self.read_pc_byte()
# log.debug("\tget_ea_indexed(): postbyte: $%02x (%s) from $%04x",
# postbyte, byte2bit_string(postbyte), addr
# )
rr = (postbyte >> 5) & 3
try:
register_str = self.INDEX_POSTBYTE2STR[rr]
except KeyError:
raise RuntimeError(f"Register ${rr:x} doesn't exists! (postbyte: ${postbyte:x})")
register_obj = self.register_str2object[register_str]
register_value = register_obj.value
# log.debug("\t%02x == register %s: value $%x",
# rr, register_obj.name, register_value
# )
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from MC6809.components.MC6809data.MC6809_op_data import REG_S, REG_U, REG_X, REG_Y
from MC6809.utils.bits import is_bit_set
from MC6809.utils.byte_word_values import signed5, signed8, signed16
and context:
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_S = "S"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
#
# Path: MC6809/utils/bits.py
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
#
# Path: MC6809/utils/byte_word_values.py
# def signed5(x):
# """ convert to signed 5-bit """
# if x > 0xf: # 0xf == 2**4-1 == 15
# x = x - 0x20 # 0x20 == 2**5 == 32
# return x
#
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
#
# def signed16(x):
# """ convert to signed 16-bit """
# if x > 0x7fff: # 0x7fff == 2**15-1 == 32767
# x = x - 0x10000 # 0x100 == 2**16 == 65536
# return x
which might include code, classes, or functions. Output only the next line. | 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):
"""
Calculate the address for all indexed addressing modes
"""
addr, postbyte = self.read_pc_byte()
# log.debug("\tget_ea_indexed(): postbyte: $%02x (%s) from $%04x",
# postbyte, byte2bit_string(postbyte), addr
# )
rr = (postbyte >> 5) & 3
try:
register_str = self.INDEX_POSTBYTE2STR[rr]
except KeyError:
raise RuntimeError(f"Register ${rr:x} doesn't exists! (postbyte: ${postbyte:x})")
register_obj = self.register_str2object[register_str]
register_value = register_obj.value
# log.debug("\t%02x == register %s: value $%x",
# rr, register_obj.name, register_value
# )
if not is_bit_set(postbyte, bit=7): # bit 7 == 0
# EA = n, R - use 5-bit offset from post-byte
<|code_end|>
using the current file's imports:
from MC6809.components.MC6809data.MC6809_op_data import REG_S, REG_U, REG_X, REG_Y
from MC6809.utils.bits import is_bit_set
from MC6809.utils.byte_word_values import signed5, signed8, signed16
and any relevant context from other files:
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_S = "S"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
#
# Path: MC6809/utils/bits.py
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
#
# Path: MC6809/utils/byte_word_values.py
# def signed5(x):
# """ convert to signed 5-bit """
# if x > 0xf: # 0xf == 2**4-1 == 15
# x = x - 0x20 # 0x20 == 2**5 == 32
# return x
#
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
#
# def signed16(x):
# """ convert to signed 16-bit """
# if x > 0x7fff: # 0x7fff == 2**15-1 == 32767
# x = x - 0x10000 # 0x100 == 2**16 == 65536
# return x
. Output only the next line. | 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+ | increment by 1")
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 addr_mode == 0x2:
# log.debug("\t0010 0x2 | ,R- | decrement by 1")
register_obj.decrement(1)
ea = register_obj.value
elif addr_mode == 0x3:
# log.debug("\t0011 0x3 | ,R-- | decrement by 2")
register_obj.decrement(2)
ea = register_obj.value
self.cycles += 1
elif addr_mode == 0x4:
# log.debug("\t0100 0x4 | ,R | No offset")
ea = register_value
elif addr_mode == 0x5:
# log.debug("\t0101 0x5 | B, R | B register offset")
<|code_end|>
using the current file's imports:
from MC6809.components.MC6809data.MC6809_op_data import REG_S, REG_U, REG_X, REG_Y
from MC6809.utils.bits import is_bit_set
from MC6809.utils.byte_word_values import signed5, signed8, signed16
and any relevant context from other files:
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_S = "S"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
#
# Path: MC6809/utils/bits.py
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
#
# Path: MC6809/utils/byte_word_values.py
# def signed5(x):
# """ convert to signed 5-bit """
# if x > 0xf: # 0xf == 2**4-1 == 15
# x = x - 0x20 # 0x20 == 2**5 == 32
# return x
#
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
#
# def signed16(x):
# """ convert to signed 16-bit """
# if x > 0x7fff: # 0x7fff == 2**15-1 == 32767
# x = x - 0x10000 # 0x100 == 2**16 == 65536
# return x
. Output only the next line. | 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 addr_mode == 0x2:
# log.debug("\t0010 0x2 | ,R- | decrement by 1")
register_obj.decrement(1)
ea = register_obj.value
elif addr_mode == 0x3:
# log.debug("\t0011 0x3 | ,R-- | decrement by 2")
register_obj.decrement(2)
ea = register_obj.value
self.cycles += 1
elif addr_mode == 0x4:
# log.debug("\t0100 0x4 | ,R | No offset")
ea = register_value
elif addr_mode == 0x5:
# log.debug("\t0101 0x5 | B, R | B register offset")
offset = signed8(self.accu_b.value)
elif addr_mode == 0x6:
# log.debug("\t0110 0x6 | A, R | A register offset")
offset = signed8(self.accu_a.value)
elif addr_mode == 0x8:
# log.debug("\t1000 0x8 | n, R | 8 bit offset")
offset = signed8(self.read_pc_byte()[1])
elif addr_mode == 0x9:
# log.debug("\t1001 0x9 | n, R | 16 bit offset")
<|code_end|>
, determine the next line of code. You have imports:
from MC6809.components.MC6809data.MC6809_op_data import REG_S, REG_U, REG_X, REG_Y
from MC6809.utils.bits import is_bit_set
from MC6809.utils.byte_word_values import signed5, signed8, signed16
and context (class names, function names, or code) available:
# Path: MC6809/components/MC6809data/MC6809_op_data.py
# REG_S = "S"
#
# REG_U = "U"
#
# REG_X = "X"
#
# REG_Y = "Y"
#
# Path: MC6809/utils/bits.py
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
#
# Path: MC6809/utils/byte_word_values.py
# def signed5(x):
# """ convert to signed 5-bit """
# if x > 0xf: # 0xf == 2**4-1 == 15
# x = x - 0x20 # 0x20 == 2**5 == 32
# return x
#
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
#
# def signed16(x):
# """ convert to signed 16-bit """
# if x > 0x7fff: # 0x7fff == 2**15-1 == 32767
# x = x - 0x10000 # 0x100 == 2**16 == 65536
# return x
. Output only the next line. | 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.mbnet.fi/~atjs/mc6809/
:copyleft: 2013-2015 by the MC6809 team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
Based on:
* ApplyPy by James Tauber (MIT license)
* XRoar emulator by Ciaran Anscomb (GPL license)
more info, see README
"""
class OpsLogicalMixin:
# ---- Logical Operations ----
<|code_end|>
. Write the next line using the current file imports:
from MC6809.components.cpu_utils.instruction_caller import opcode
from MC6809.utils.bits import get_bit
and context from other files:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
#
# Path: MC6809/utils/bits.py
# def get_bit(value, bit):
# """
# return 1 or 0 from the bit at the given offset >bit<, e.g.:
#
# >>> get_bit(0x01, bit=0) # 00000001
# 1
# >>> get_bit(0xfd, bit=1) # 11111101
# 0
# >>> get_bit(int('10000000', 2), bit=7)
# 1
# >>> get_bit(int('01111111', 2), bit=7)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=11)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=12)
# 1
# """
# return 0 if value & 2 ** bit == 0 else 1
, which may include functions, classes, or code. Output only the next line. | @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):
"""
Logical shift left accumulator / Arithmetic shift of accumulator
"""
a = register.value
r = self.LSL(a)
# log.debug("$%x LSL %s value $%x << 1 = $%x" % (
# self.program_counter,
# register.name, a, r
# ))
register.set(r)
def LSR(self, a):
"""
Performs a logical shift right on the register. Shifts a zero into bit
seven and bit zero into the C (carry) bit.
source code forms: LSR Q; LSRA; LSRB
CC bits "HNZVC": -0a-s
"""
r = a >> 1
self.clear_NZC()
<|code_end|>
, predict the immediate next line with the help of imports:
from MC6809.components.cpu_utils.instruction_caller import opcode
from MC6809.utils.bits import get_bit
and context (classes, functions, sometimes code) from other files:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
#
# Path: MC6809/utils/bits.py
# def get_bit(value, bit):
# """
# return 1 or 0 from the bit at the given offset >bit<, e.g.:
#
# >>> get_bit(0x01, bit=0) # 00000001
# 1
# >>> get_bit(0xfd, bit=1) # 11111101
# 0
# >>> get_bit(int('10000000', 2), bit=7)
# 1
# >>> get_bit(int('01111111', 2), bit=7)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=11)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=12)
# 1
# """
# return 0 if value & 2 ** bit == 0 else 1
. Output only the next line. | 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.
"""
class CLITestCase(unittest.TestCase):
"""
TODO: Do more than this simple tests
"""
def _invoke(self, *args):
runner = CliRunner()
<|code_end|>
using the current file's imports:
import unittest
import MC6809
from click.testing import CliRunner
from MC6809.cli import cli
and any relevant context from other files:
# Path: MC6809/cli.py
# @click.group()
# @click.version_option(MC6809.__version__)
# def cli():
# """
# MC6809 is a Open source (GPL v3 or later) emulator
# for the legendary 6809 CPU, used in 30 years old homecomputer
# Dragon 32 and Tandy TRS-80 Color Computer (CoCo)...
#
# Created by Jens Diemer
#
# Homepage: https://github.com/6809/MC6809
# """
# pass
. Output only the next line. | 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.getLogger("MC6809")
<|code_end|>
, determine the next line of code. You have imports:
import itertools
import logging
import operator
import sys
import unittest
from MC6809.tests.test_base import BaseCPUTestCase
and context (class names, function names, or code) available:
# Path: MC6809/tests/test_base.py
# class BaseCPUTestCase(BaseTestCase):
# UNITTEST_CFG_DICT = {
# "verbosity": None,
# "display_cycle": False,
# "trace": None,
# "bus_socket_host": None,
# "bus_socket_port": None,
# "ram": None,
# "rom": None,
# "max_ops": None,
# "use_bus": False,
# }
#
# def setUp(self):
# cfg = TestCfg(self.UNITTEST_CFG_DICT)
# memory = Memory(cfg)
# self.cpu = CPU(memory, cfg)
#
# def cpu_test_run(self, start, end, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# log.debug("memory load at $%x: %s", start,
# ", ".join("$%x" % i for i in mem)
# )
# self.cpu.memory.load(start, mem)
# if end is None:
# end = start + len(mem)
# self.cpu.test_run(start, end)
# cpu_test_run.__test__ = False # Exclude from nose
#
# def cpu_test_run2(self, start, count, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# self.cpu.memory.load(start, mem)
# self.cpu.test_run2(start, count)
# cpu_test_run2.__test__ = False # Exclude from nose
#
# def assertMemory(self, start, mem):
# for index, should_byte in enumerate(mem):
# address = start + index
# is_byte = self.cpu.memory.read_byte(address)
#
# msg = f"${is_byte:02x} is not ${should_byte:02x} at address ${address:04x} (index: {index:d})"
# self.assertEqual(is_byte, should_byte, msg)
. Output only the next line. | 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.getLogger("MC6809")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
from MC6809.tests.test_base import BaseCPUTestCase, BaseStackTestCase
and context:
# Path: MC6809/tests/test_base.py
# class BaseCPUTestCase(BaseTestCase):
# UNITTEST_CFG_DICT = {
# "verbosity": None,
# "display_cycle": False,
# "trace": None,
# "bus_socket_host": None,
# "bus_socket_port": None,
# "ram": None,
# "rom": None,
# "max_ops": None,
# "use_bus": False,
# }
#
# def setUp(self):
# cfg = TestCfg(self.UNITTEST_CFG_DICT)
# memory = Memory(cfg)
# self.cpu = CPU(memory, cfg)
#
# def cpu_test_run(self, start, end, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# log.debug("memory load at $%x: %s", start,
# ", ".join("$%x" % i for i in mem)
# )
# self.cpu.memory.load(start, mem)
# if end is None:
# end = start + len(mem)
# self.cpu.test_run(start, end)
# cpu_test_run.__test__ = False # Exclude from nose
#
# def cpu_test_run2(self, start, count, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# self.cpu.memory.load(start, mem)
# self.cpu.test_run2(start, count)
# cpu_test_run2.__test__ = False # Exclude from nose
#
# def assertMemory(self, start, mem):
# for index, should_byte in enumerate(mem):
# address = start + index
# is_byte = self.cpu.memory.read_byte(address)
#
# msg = f"${is_byte:02x} is not ${should_byte:02x} at address ${address:04x} (index: {index:d})"
# self.assertEqual(is_byte, should_byte, msg)
#
# class BaseStackTestCase(BaseCPUTestCase):
# INITIAL_SYSTEM_STACK_ADDR = 0x1000
# INITIAL_USER_STACK_ADDR = 0x2000
#
# def setUp(self):
# super().setUp()
# self.cpu.system_stack_pointer.set(self.INITIAL_SYSTEM_STACK_ADDR)
# self.cpu.user_stack_pointer.set(self.INITIAL_USER_STACK_ADDR)
which might include code, classes, or functions. Output only the next line. | 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=[
0x4D # TSTA
])
self.assertTST(i)
def test_TSTB(self):
for i in range(255):
self.cpu.accu_b.set(i)
self.cpu.set_cc(0xff) # Set all CC flags
self.cpu_test_run(start=0x1000, end=None, mem=[
0x5D # TSTB
])
self.assertTST(i)
# TODO:
# self.cpu_test_run(start=0x4000, end=None, mem=[0x4F]) # CLRA
# self.assertEqualHex(self.cpu.accu_d.value, 0x34)
#
# self.cpu_test_run(start=0x4000, end=None, mem=[0x5F]) # CLRB
# self.assertEqualHex(self.cpu.accu_d.value, 0x0)
<|code_end|>
using the current file's imports:
import logging
from MC6809.tests.test_base import BaseCPUTestCase, BaseStackTestCase
and any relevant context from other files:
# Path: MC6809/tests/test_base.py
# class BaseCPUTestCase(BaseTestCase):
# UNITTEST_CFG_DICT = {
# "verbosity": None,
# "display_cycle": False,
# "trace": None,
# "bus_socket_host": None,
# "bus_socket_port": None,
# "ram": None,
# "rom": None,
# "max_ops": None,
# "use_bus": False,
# }
#
# def setUp(self):
# cfg = TestCfg(self.UNITTEST_CFG_DICT)
# memory = Memory(cfg)
# self.cpu = CPU(memory, cfg)
#
# def cpu_test_run(self, start, end, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# log.debug("memory load at $%x: %s", start,
# ", ".join("$%x" % i for i in mem)
# )
# self.cpu.memory.load(start, mem)
# if end is None:
# end = start + len(mem)
# self.cpu.test_run(start, end)
# cpu_test_run.__test__ = False # Exclude from nose
#
# def cpu_test_run2(self, start, count, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# self.cpu.memory.load(start, mem)
# self.cpu.test_run2(start, count)
# cpu_test_run2.__test__ = False # Exclude from nose
#
# def assertMemory(self, start, mem):
# for index, should_byte in enumerate(mem):
# address = start + index
# is_byte = self.cpu.memory.read_byte(address)
#
# msg = f"${is_byte:02x} is not ${should_byte:02x} at address ${address:04x} (index: {index:d})"
# self.assertEqual(is_byte, should_byte, msg)
#
# class BaseStackTestCase(BaseCPUTestCase):
# INITIAL_SYSTEM_STACK_ADDR = 0x1000
# INITIAL_USER_STACK_ADDR = 0x2000
#
# def setUp(self):
# super().setUp()
# self.cpu.system_stack_pointer.set(self.INITIAL_SYSTEM_STACK_ADDR)
# self.cpu.user_stack_pointer.set(self.INITIAL_USER_STACK_ADDR)
. Output only the next line. | 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.fi/~atjs/mc6809/
:copyleft: 2013-2015 by the MC6809 team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
Based on:
* ApplyPy by James Tauber (MIT license)
* XRoar emulator by Ciaran Anscomb (GPL license)
more info, see README
"""
class OpsLoadStoreMixin:
# ---- Store / Load ----
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from MC6809.components.cpu_utils.instruction_caller import opcode
and context:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
which might include code, classes, or functions. Output only the next line. | @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://koti.mbnet.fi/~atjs/mc6809/
:copyleft: 2013-2015 by the MC6809 team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
Based on:
* ApplyPy by James Tauber (MIT license)
* XRoar emulator by Ciaran Anscomb (GPL license)
more info, see README
"""
class OpsBranchesMixin:
# ---- Programm Flow Instructions ----
<|code_end|>
, generate the next line using the imports in this file:
from MC6809.components.cpu_utils.instruction_caller import opcode
and context (functions, classes, or occasionally code) from other files:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
. Output only the next line. | @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|>
, predict the immediate next line with the help of imports:
import unittest
from MC6809.tests.test_base import BaseCPUTestCase
from MC6809.utils.byte_word_values import signed8
and context (classes, functions, sometimes code) from other files:
# Path: MC6809/tests/test_base.py
# class BaseCPUTestCase(BaseTestCase):
# UNITTEST_CFG_DICT = {
# "verbosity": None,
# "display_cycle": False,
# "trace": None,
# "bus_socket_host": None,
# "bus_socket_port": None,
# "ram": None,
# "rom": None,
# "max_ops": None,
# "use_bus": False,
# }
#
# def setUp(self):
# cfg = TestCfg(self.UNITTEST_CFG_DICT)
# memory = Memory(cfg)
# self.cpu = CPU(memory, cfg)
#
# def cpu_test_run(self, start, end, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# log.debug("memory load at $%x: %s", start,
# ", ".join("$%x" % i for i in mem)
# )
# self.cpu.memory.load(start, mem)
# if end is None:
# end = start + len(mem)
# self.cpu.test_run(start, end)
# cpu_test_run.__test__ = False # Exclude from nose
#
# def cpu_test_run2(self, start, count, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# self.cpu.memory.load(start, mem)
# self.cpu.test_run2(start, count)
# cpu_test_run2.__test__ = False # Exclude from nose
#
# def assertMemory(self, start, mem):
# for index, should_byte in enumerate(mem):
# address = start + index
# is_byte = self.cpu.memory.read_byte(address)
#
# msg = f"${is_byte:02x} is not ${should_byte:02x} at address ${address:04x} (index: {index:d})"
# self.assertEqual(is_byte, should_byte, msg)
#
# Path: MC6809/utils/byte_word_values.py
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
. Output only the next line. | 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):
for i in range(280):
self.cpu.set_cc(0x00)
r = i + 1 # e.g. ADDA 1 loop
self.cpu.update_HNZVC_8(a=i, b=1, r=r)
# print r, self.cpu.get_cc_info()
# test half carry
if r % 16 == 0:
self.assertEqual(self.cpu.H, 1)
else:
self.assertEqual(self.cpu.H, 0)
# test negative
if 128 <= r <= 255:
self.assertEqual(self.cpu.N, 1)
else:
self.assertEqual(self.cpu.N, 0)
# test zero
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from MC6809.tests.test_base import BaseCPUTestCase
from MC6809.utils.byte_word_values import signed8
and context including class names, function names, and sometimes code from other files:
# Path: MC6809/tests/test_base.py
# class BaseCPUTestCase(BaseTestCase):
# UNITTEST_CFG_DICT = {
# "verbosity": None,
# "display_cycle": False,
# "trace": None,
# "bus_socket_host": None,
# "bus_socket_port": None,
# "ram": None,
# "rom": None,
# "max_ops": None,
# "use_bus": False,
# }
#
# def setUp(self):
# cfg = TestCfg(self.UNITTEST_CFG_DICT)
# memory = Memory(cfg)
# self.cpu = CPU(memory, cfg)
#
# def cpu_test_run(self, start, end, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# log.debug("memory load at $%x: %s", start,
# ", ".join("$%x" % i for i in mem)
# )
# self.cpu.memory.load(start, mem)
# if end is None:
# end = start + len(mem)
# self.cpu.test_run(start, end)
# cpu_test_run.__test__ = False # Exclude from nose
#
# def cpu_test_run2(self, start, count, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# self.cpu.memory.load(start, mem)
# self.cpu.test_run2(start, count)
# cpu_test_run2.__test__ = False # Exclude from nose
#
# def assertMemory(self, start, mem):
# for index, should_byte in enumerate(mem):
# address = start + index
# is_byte = self.cpu.memory.read_byte(address)
#
# msg = f"${is_byte:02x} is not ${should_byte:02x} at address ${address:04x} (index: {index:d})"
# self.assertEqual(is_byte, should_byte, msg)
#
# Path: MC6809/utils/byte_word_values.py
# def signed8(x):
# """ convert to signed 8-bit """
# if x > 0x7f: # 0x7f == 2**7-1 == 127
# x = x - 0x100 # 0x100 == 2**8 == 256
# return x
. Output only the next line. | 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 - Overflow
self.C = 0 # C - 0x01 - bit 0 - Carry (or borrow)
self.cc_register = ConditionCodeRegister(self)
####
def get_cc_value(self):
return self.C | \
self.V << 1 | \
self.Z << 2 | \
self.N << 3 | \
self.I << 4 | \
self.H << 5 | \
self.F << 6 | \
self.E << 7
def set_cc(self, status):
self.E, self.F, self.H, self.I, self.N, self.Z, self.V, self.C = \
[0 if status & x == 0 else 1 for x in (128, 64, 32, 16, 8, 4, 2, 1)]
def get_cc_info(self):
"""
return cc flags as text representation, like: 'E.H....C'
used in trace mode and unittests
"""
<|code_end|>
. Use current file imports:
(import logging
from MC6809.utils.humanize import cc_value2txt)
and context including class names, function names, or small code snippets from other files:
# Path: MC6809/utils/humanize.py
# def cc_value2txt(status):
# """
# >>> cc_value2txt(0x50)
# '.F.I....'
# >>> cc_value2txt(0x54)
# '.F.I.Z..'
# >>> cc_value2txt(0x59)
# '.F.IN..C'
# """
# return "".join(
# "." if status & x == 0 else char
# for char, x in zip("EFHINZVC", (128, 64, 32, 16, 8, 4, 2, 1))
# )
. Output only the next line. | 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 details.
"""
log = logging.getLogger("MC6809")
<|code_end|>
. Use current file imports:
(import logging
import sys
import unittest
from MC6809.tests.test_base import BaseCPUTestCase
from MC6809.utils.bits import get_bit, is_bit_set)
and context including class names, function names, or small code snippets from other files:
# Path: MC6809/tests/test_base.py
# class BaseCPUTestCase(BaseTestCase):
# UNITTEST_CFG_DICT = {
# "verbosity": None,
# "display_cycle": False,
# "trace": None,
# "bus_socket_host": None,
# "bus_socket_port": None,
# "ram": None,
# "rom": None,
# "max_ops": None,
# "use_bus": False,
# }
#
# def setUp(self):
# cfg = TestCfg(self.UNITTEST_CFG_DICT)
# memory = Memory(cfg)
# self.cpu = CPU(memory, cfg)
#
# def cpu_test_run(self, start, end, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# log.debug("memory load at $%x: %s", start,
# ", ".join("$%x" % i for i in mem)
# )
# self.cpu.memory.load(start, mem)
# if end is None:
# end = start + len(mem)
# self.cpu.test_run(start, end)
# cpu_test_run.__test__ = False # Exclude from nose
#
# def cpu_test_run2(self, start, count, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# self.cpu.memory.load(start, mem)
# self.cpu.test_run2(start, count)
# cpu_test_run2.__test__ = False # Exclude from nose
#
# def assertMemory(self, start, mem):
# for index, should_byte in enumerate(mem):
# address = start + index
# is_byte = self.cpu.memory.read_byte(address)
#
# msg = f"${is_byte:02x} is not ${should_byte:02x} at address ${address:04x} (index: {index:d})"
# self.assertEqual(is_byte, should_byte, msg)
#
# Path: MC6809/utils/bits.py
# def get_bit(value, bit):
# """
# return 1 or 0 from the bit at the given offset >bit<, e.g.:
#
# >>> get_bit(0x01, bit=0) # 00000001
# 1
# >>> get_bit(0xfd, bit=1) # 11111101
# 0
# >>> get_bit(int('10000000', 2), bit=7)
# 1
# >>> get_bit(int('01111111', 2), bit=7)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=11)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=12)
# 1
# """
# return 0 if value & 2 ** bit == 0 else 1
#
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
. Output only the next line. | 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.get_cc_info()
# )
# test LSL result
r2 = i >> 1 # shift right
r2 = r2 & 0xff # wrap around
self.assertEqualHex(r, r2)
# test negative
if 128 <= r <= 255:
self.assertEqual(self.cpu.N, 1)
else:
self.assertEqual(self.cpu.N, 0)
# test zero
if r == 0:
self.assertEqual(self.cpu.Z, 1)
else:
self.assertEqual(self.cpu.Z, 0)
# test overflow
self.assertEqual(self.cpu.V, 0)
# test carry
<|code_end|>
with the help of current file imports:
import logging
import sys
import unittest
from MC6809.tests.test_base import BaseCPUTestCase
from MC6809.utils.bits import get_bit, is_bit_set
and context from other files:
# Path: MC6809/tests/test_base.py
# class BaseCPUTestCase(BaseTestCase):
# UNITTEST_CFG_DICT = {
# "verbosity": None,
# "display_cycle": False,
# "trace": None,
# "bus_socket_host": None,
# "bus_socket_port": None,
# "ram": None,
# "rom": None,
# "max_ops": None,
# "use_bus": False,
# }
#
# def setUp(self):
# cfg = TestCfg(self.UNITTEST_CFG_DICT)
# memory = Memory(cfg)
# self.cpu = CPU(memory, cfg)
#
# def cpu_test_run(self, start, end, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# log.debug("memory load at $%x: %s", start,
# ", ".join("$%x" % i for i in mem)
# )
# self.cpu.memory.load(start, mem)
# if end is None:
# end = start + len(mem)
# self.cpu.test_run(start, end)
# cpu_test_run.__test__ = False # Exclude from nose
#
# def cpu_test_run2(self, start, count, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# self.cpu.memory.load(start, mem)
# self.cpu.test_run2(start, count)
# cpu_test_run2.__test__ = False # Exclude from nose
#
# def assertMemory(self, start, mem):
# for index, should_byte in enumerate(mem):
# address = start + index
# is_byte = self.cpu.memory.read_byte(address)
#
# msg = f"${is_byte:02x} is not ${should_byte:02x} at address ${address:04x} (index: {index:d})"
# self.assertEqual(is_byte, should_byte, msg)
#
# Path: MC6809/utils/bits.py
# def get_bit(value, bit):
# """
# return 1 or 0 from the bit at the given offset >bit<, e.g.:
#
# >>> get_bit(0x01, bit=0) # 00000001
# 1
# >>> get_bit(0xfd, bit=1) # 11111101
# 0
# >>> get_bit(int('10000000', 2), bit=7)
# 1
# >>> get_bit(int('01111111', 2), bit=7)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=11)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=12)
# 1
# """
# return 0 if value & 2 ** bit == 0 else 1
#
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
, which may contain function names, class names, or code. Output only the next line. | 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]}"
else:
excpeted_bits = f"0{src_bit_str[:-1]}"
# test ASRB/LSRB result
self.assertEqual(dst_bit_str, excpeted_bits)
# test negative
if 128 <= dst <= 255:
self.assertEqual(self.cpu.N, 1)
else:
self.assertEqual(self.cpu.N, 0)
# test zero
if dst == 0:
self.assertEqual(self.cpu.Z, 1)
else:
self.assertEqual(self.cpu.Z, 0)
# test overflow (is uneffected!)
self.assertEqual(self.cpu.V, 0)
# test carry
<|code_end|>
with the help of current file imports:
import logging
import sys
import unittest
from MC6809.tests.test_base import BaseCPUTestCase
from MC6809.utils.bits import get_bit, is_bit_set
and context from other files:
# Path: MC6809/tests/test_base.py
# class BaseCPUTestCase(BaseTestCase):
# UNITTEST_CFG_DICT = {
# "verbosity": None,
# "display_cycle": False,
# "trace": None,
# "bus_socket_host": None,
# "bus_socket_port": None,
# "ram": None,
# "rom": None,
# "max_ops": None,
# "use_bus": False,
# }
#
# def setUp(self):
# cfg = TestCfg(self.UNITTEST_CFG_DICT)
# memory = Memory(cfg)
# self.cpu = CPU(memory, cfg)
#
# def cpu_test_run(self, start, end, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# log.debug("memory load at $%x: %s", start,
# ", ".join("$%x" % i for i in mem)
# )
# self.cpu.memory.load(start, mem)
# if end is None:
# end = start + len(mem)
# self.cpu.test_run(start, end)
# cpu_test_run.__test__ = False # Exclude from nose
#
# def cpu_test_run2(self, start, count, mem):
# for cell in mem:
# self.assertLess(-1, cell, f"${cell:x} < 0")
# self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
# self.cpu.memory.load(start, mem)
# self.cpu.test_run2(start, count)
# cpu_test_run2.__test__ = False # Exclude from nose
#
# def assertMemory(self, start, mem):
# for index, should_byte in enumerate(mem):
# address = start + index
# is_byte = self.cpu.memory.read_byte(address)
#
# msg = f"${is_byte:02x} is not ${should_byte:02x} at address ${address:04x} (index: {index:d})"
# self.assertEqual(is_byte, should_byte, msg)
#
# Path: MC6809/utils/bits.py
# def get_bit(value, bit):
# """
# return 1 or 0 from the bit at the given offset >bit<, e.g.:
#
# >>> get_bit(0x01, bit=0) # 00000001
# 1
# >>> get_bit(0xfd, bit=1) # 11111101
# 0
# >>> get_bit(int('10000000', 2), bit=7)
# 1
# >>> get_bit(int('01111111', 2), bit=7)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=11)
# 0
# >>> get_bit(int('1111000011110000', 2), bit=12)
# 1
# """
# return 0 if value & 2 ** bit == 0 else 1
#
# def is_bit_set(value, bit):
# """
# Return True/False if the bit at offset >bit< is 1 or 0 in given value.
#
# bit 7 | | bit 0
# ...10111101
#
# e.g.:
#
# >>> is_bit_set(0x01, bit=0) # 00000001
# True
# >>> is_bit_set(0xfd, bit=1) # 11111101
# False
# >>> is_bit_set(int('10000000', 2), bit=7)
# True
# >>> is_bit_set(int('01111111', 2), bit=7)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=11)
# False
# >>> is_bit_set(int('1111000011110000', 2), bit=12)
# True
# """
# return False if value & 2 ** bit == 0 else True
, which may contain function names, class names, or code. Output only the next line. | 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 line using the current file imports:
from MC6809.components.cpu_utils.instruction_base import InstructionBase
and context from other files:
# Path: MC6809/components/cpu_utils/instruction_base.py
# class InstructionBase:
# def __init__(self, cpu, instr_func):
# self.cpu = cpu
# self.instr_func = instr_func
#
# def special(self, opcode):
# # e.g: RESET and PAGE 1/2
# return self.instr_func(opcode)
, which may include functions, classes, or code. Output only the next line. | 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://koti.mbnet.fi/~atjs/mc6809/
:copyleft: 2013-2015 by the MC6809 team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
Based on:
* ApplyPy by James Tauber (MIT license)
* XRoar emulator by Ciaran Anscomb (GPL license)
more info, see README
"""
class OpsTestMixin:
# ---- Test Instructions ----
<|code_end|>
. Use current file imports:
from MC6809.components.cpu_utils.instruction_caller import opcode
and context (classes, functions, or code) from other files:
# Path: MC6809/components/cpu_utils/instruction_caller.py
# def opcode(*opcodes):
# """A decorator for opcodes"""
# def decorator(func):
# setattr(func, "_is_opcode", True)
# setattr(func, "_opcodes", opcodes)
# return func
# return decorator
. Output only the next line. | @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 {}
footer = None
if Footer.objects.exists():
footer = Footer.objects.all()[0]
properties = {
"site_tagline": settings.SITE_TAGLINE,
"main_site_url": request.__main_site_url,
"footer": footer
}
return properties
def piwik(request):
""" :returns: the the Piwik analytics URL and SITE_ID """
if hasattr(settings, 'PIWIK_URL') and settings.PIWIK_URL != '':
return {"piwik_url": settings.PIWIK_URL, "piwik_site_id": settings.PIWIK_SITE_ID}
else:
return {}
def homepage_header(request):
if not hasattr(request, '__homepage_header'):
<|code_end|>
. Write the next line using the current file imports:
import logging
from django.contrib.sites.models import Site
from mezzanine.conf import settings
from website.jdpages.views import get_homepage_header
from website.jdpages.models import Footer
and context from other files:
# Path: website/jdpages/views.py
# def get_homepage_header():
# """ Returns the page header image of the homepage """
# homepage_id = get_homepage_id()
# if homepage_id is None:
# return None
# return get_page_header(homepage_id)
#
# Path: website/jdpages/models.py
# class Footer(SiteRelated):
# links_left = models.OneToOneField(FooterLinks, auto_created=True, related_name="links_left")
# links_middle = models.OneToOneField(FooterLinks, auto_created=True, related_name="links_right")
# info_right = models.OneToOneField(FooterInfo, auto_created=True)
#
# class Meta:
# verbose_name = "Footer"
# verbose_name_plural = "Footer"
, which may include functions, classes, or code. Output only the next line. | 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_site_url = 'http://' + dom
except Site.DoesNotExist:
return {}
footer = None
<|code_end|>
. Use current file imports:
import logging
from django.contrib.sites.models import Site
from mezzanine.conf import settings
from website.jdpages.views import get_homepage_header
from website.jdpages.models import Footer
and context (classes, functions, or code) from other files:
# Path: website/jdpages/views.py
# def get_homepage_header():
# """ Returns the page header image of the homepage """
# homepage_id = get_homepage_id()
# if homepage_id is None:
# return None
# return get_page_header(homepage_id)
#
# Path: website/jdpages/models.py
# class Footer(SiteRelated):
# links_left = models.OneToOneField(FooterLinks, auto_created=True, related_name="links_left")
# links_middle = models.OneToOneField(FooterLinks, auto_created=True, related_name="links_right")
# info_right = models.OneToOneField(FooterInfo, auto_created=True)
#
# class Meta:
# verbose_name = "Footer"
# verbose_name_plural = "Footer"
. Output only the next line. | 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 template. It isn't
# commented out like the others, so it's the default. You only need
# one homepage pattern, so if you use a different one, comment this
# one out.
# url("^$", direct_to_template, {"template": "index.html"}, name="home"),
# HOMEPAGE AS AN EDITABLE PAGE IN THE PAGE TREE
# ---------------------------------------------
# This pattern gives us a normal ``Page`` object, so that your
# homepage can be managed via the page tree in the admin. If you
# use this pattern, you'll need to create a page in the page tree,
# and specify its URL (in the Meta Data section) as "/", which
# is the value used below in the ``{"slug": "/"}`` part.
# Also note that the normal rule of adding a custom
# template per page with the template name using the page's slug
# doesn't apply here, since we can't have a template called
# "/.html" - so for this case, the template "pages/index.html"
# should be used if you want to customize the homepage's template.
url("^$", "mezzanine.pages.views.page", {"slug": "/"}, name="home"),
<|code_end|>
with the help of current file imports:
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.views.defaults import page_not_found
from website.jdpages.views import OccuranceJDView
and context from other files:
# Path: website/jdpages/views.py
# class OccuranceJDView(OccurrenceView):
#
# def get_context_data(self, **kwargs):
# context = super().get_context_data(**kwargs)
# context['page_for_sidebars'] = HomePage.objects.all().first()
# return context
, which may contain function names, class names, or code. Output only the next line. | 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():
return pages[0].id
return None
def get_page_header(page):
"""
:returns: the page header for a given page.
Uses parent page image when none is defined.
Top parent is the HomePage.
None when there is no Hompage or when the HomePage has no header.
"""
# Get a random page header, or the first one if there is only one
<|code_end|>
using the current file's imports:
import logging
from mezzanine.pages.models import RichTextPage
from fullcalendar.views import OccurrenceView
from website.jdpages.models import HomePage
from website.jdpages.models import SidebarSocial
from website.jdpages.models import PageHeaderImage
and any relevant context from other files:
# Path: website/jdpages/models.py
# class HomePage(Page, RichText):
# """
# Page model for the site homepage.
# Only works properly when url points to the homepage '/' as url.
# """
# header_title = models.CharField(max_length=300, blank=True, default="")
# header_subtitle = models.CharField(max_length=500, blank=True, default="")
# news_category = models.ForeignKey(BlogCategory, null=True, blank=True)
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# @property
# def blog_posts(self):
# return get_public_blogposts(self.news_category)[:4]
#
# class Meta:
# verbose_name = 'Home pagina'
# verbose_name_plural = "Home pagina's"
#
# Path: website/jdpages/models.py
# class SidebarSocial(PageItem):
#
# @property
# def urls(self):
# smulrs = SocialMediaUrls.objects.all()
# if smulrs.exists():
# return smulrs[0]
# return None
#
# class Meta:
# verbose_name = "Sidebar Social Media Item"
#
# Path: website/jdpages/models.py
# class PageHeaderImage(SiteRelated):
# """ Page header image. """
# name = models.CharField(max_length=1000, blank=True, null=False, default="")
# page = models.ForeignKey(Page, blank=False, null=True)
# image = FileField(max_length=200, format="Image", validators=[validate_header_image])
. Output only the next line. | 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(OrganisationPage)
@processor_for(OrganisationPartPage)
<|code_end|>
with the help of current file imports:
import logging
from mezzanine.blog.views import blog_post_list
from mezzanine.pages.page_processors import processor_for
from mezzanine.pages.models import RichTextPage
from website.jdpages.models import BlogCategoryPage
from mezzanine.forms.models import Form
from website.jdpages.models import HomePage
from website.jdpages.models import OrganisationPage
from website.jdpages.models import OrganisationPartPage
from website.jdpages.models import VisionPage
from website.jdpages.models import VisionsPage
from website.jdpages.models import WordLidPage
from website.jdpages.views import get_page_header
and context from other files:
# Path: website/jdpages/models.py
# class BlogCategoryPage(Page, RichText):
# """
# Model for a page that displays a list of posts in a single blog category.
# """
#
# blog_category = models.ForeignKey(BlogCategory, null=False, blank=False)
# show_excerpt = models.BooleanField(default=False, null=False, blank=False,
# help_text='Show only the first paragraph of a blog post.')
#
# class Meta:
# verbose_name = "Blog categorie pagina"
# verbose_name_plural = "Blog categorie pagina's"
#
# Path: website/jdpages/models.py
# class HomePage(Page, RichText):
# """
# Page model for the site homepage.
# Only works properly when url points to the homepage '/' as url.
# """
# header_title = models.CharField(max_length=300, blank=True, default="")
# header_subtitle = models.CharField(max_length=500, blank=True, default="")
# news_category = models.ForeignKey(BlogCategory, null=True, blank=True)
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# @property
# def blog_posts(self):
# return get_public_blogposts(self.news_category)[:4]
#
# class Meta:
# verbose_name = 'Home pagina'
# verbose_name_plural = "Home pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPage(Page, RichText):
# """
# """
# organisation_part_pages = models.ManyToManyField(OrganisationPartPage, blank=True, verbose_name="Organisatie onderdelen")
#
# class Meta:
# verbose_name = 'Organisatie pagina'
# verbose_name_plural = "Organisatie pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPartPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_organisation_image])
#
# class Meta:
# verbose_name = 'Organisatie-onderdeel pagina'
# verbose_name_plural = "Organisatie-onderdeel pagina's"
#
# Path: website/jdpages/models.py
# class VisionPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_vision_image])
#
# class Meta:
# verbose_name = 'Standpunt pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/models.py
# class VisionsPage(Page, RichText):
# """
# """
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# class Meta:
# verbose_name = 'Standpunten pagina'
# verbose_name_plural = "Standpunten pagina's"
#
# Path: website/jdpages/models.py
# class WordLidPage(Page, RichText):
# """
# """
#
# class Meta:
# verbose_name = 'Word lid pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/views.py
# def get_page_header(page):
# """
# :returns: the page header for a given page.
# Uses parent page image when none is defined.
# Top parent is the HomePage.
# None when there is no Hompage or when the HomePage has no header.
# """
#
# # Get a random page header, or the first one if there is only one
# image = PageHeaderImage.objects.filter(page=page).order_by('?').first()
# if image is not None:
# return image
#
# # No image found! If we received an integer, then do not search further
# if isinstance(page, int):
# return None
#
# # Try from parent
# if page.parent:
# return get_page_header(page.parent)
#
# # Try from first homepage
# homepage = get_homepage_id()
# if homepage is not None:
# # Since we give get_page_header an integer, there is no infinite recursion here...
# return get_page_header(homepage)
#
# return None
, which may contain function names, class names, or code. Output only the next line. | @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_post_list
from mezzanine.pages.page_processors import processor_for
from mezzanine.pages.models import RichTextPage
from website.jdpages.models import BlogCategoryPage
from mezzanine.forms.models import Form
from website.jdpages.models import HomePage
from website.jdpages.models import OrganisationPage
from website.jdpages.models import OrganisationPartPage
from website.jdpages.models import VisionPage
from website.jdpages.models import VisionsPage
from website.jdpages.models import WordLidPage
from website.jdpages.views import get_page_header
and context (functions, classes, or occasionally code) from other files:
# Path: website/jdpages/models.py
# class BlogCategoryPage(Page, RichText):
# """
# Model for a page that displays a list of posts in a single blog category.
# """
#
# blog_category = models.ForeignKey(BlogCategory, null=False, blank=False)
# show_excerpt = models.BooleanField(default=False, null=False, blank=False,
# help_text='Show only the first paragraph of a blog post.')
#
# class Meta:
# verbose_name = "Blog categorie pagina"
# verbose_name_plural = "Blog categorie pagina's"
#
# Path: website/jdpages/models.py
# class HomePage(Page, RichText):
# """
# Page model for the site homepage.
# Only works properly when url points to the homepage '/' as url.
# """
# header_title = models.CharField(max_length=300, blank=True, default="")
# header_subtitle = models.CharField(max_length=500, blank=True, default="")
# news_category = models.ForeignKey(BlogCategory, null=True, blank=True)
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# @property
# def blog_posts(self):
# return get_public_blogposts(self.news_category)[:4]
#
# class Meta:
# verbose_name = 'Home pagina'
# verbose_name_plural = "Home pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPage(Page, RichText):
# """
# """
# organisation_part_pages = models.ManyToManyField(OrganisationPartPage, blank=True, verbose_name="Organisatie onderdelen")
#
# class Meta:
# verbose_name = 'Organisatie pagina'
# verbose_name_plural = "Organisatie pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPartPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_organisation_image])
#
# class Meta:
# verbose_name = 'Organisatie-onderdeel pagina'
# verbose_name_plural = "Organisatie-onderdeel pagina's"
#
# Path: website/jdpages/models.py
# class VisionPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_vision_image])
#
# class Meta:
# verbose_name = 'Standpunt pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/models.py
# class VisionsPage(Page, RichText):
# """
# """
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# class Meta:
# verbose_name = 'Standpunten pagina'
# verbose_name_plural = "Standpunten pagina's"
#
# Path: website/jdpages/models.py
# class WordLidPage(Page, RichText):
# """
# """
#
# class Meta:
# verbose_name = 'Word lid pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/views.py
# def get_page_header(page):
# """
# :returns: the page header for a given page.
# Uses parent page image when none is defined.
# Top parent is the HomePage.
# None when there is no Hompage or when the HomePage has no header.
# """
#
# # Get a random page header, or the first one if there is only one
# image = PageHeaderImage.objects.filter(page=page).order_by('?').first()
# if image is not None:
# return image
#
# # No image found! If we received an integer, then do not search further
# if isinstance(page, int):
# return None
#
# # Try from parent
# if page.parent:
# return get_page_header(page.parent)
#
# # Try from first homepage
# homepage = get_homepage_id()
# if homepage is not None:
# # Since we give get_page_header an integer, there is no infinite recursion here...
# return get_page_header(homepage)
#
# return None
. Output only the next line. | @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:
import logging
from mezzanine.blog.views import blog_post_list
from mezzanine.pages.page_processors import processor_for
from mezzanine.pages.models import RichTextPage
from website.jdpages.models import BlogCategoryPage
from mezzanine.forms.models import Form
from website.jdpages.models import HomePage
from website.jdpages.models import OrganisationPage
from website.jdpages.models import OrganisationPartPage
from website.jdpages.models import VisionPage
from website.jdpages.models import VisionsPage
from website.jdpages.models import WordLidPage
from website.jdpages.views import get_page_header
and context (classes, functions, or code) from other files:
# Path: website/jdpages/models.py
# class BlogCategoryPage(Page, RichText):
# """
# Model for a page that displays a list of posts in a single blog category.
# """
#
# blog_category = models.ForeignKey(BlogCategory, null=False, blank=False)
# show_excerpt = models.BooleanField(default=False, null=False, blank=False,
# help_text='Show only the first paragraph of a blog post.')
#
# class Meta:
# verbose_name = "Blog categorie pagina"
# verbose_name_plural = "Blog categorie pagina's"
#
# Path: website/jdpages/models.py
# class HomePage(Page, RichText):
# """
# Page model for the site homepage.
# Only works properly when url points to the homepage '/' as url.
# """
# header_title = models.CharField(max_length=300, blank=True, default="")
# header_subtitle = models.CharField(max_length=500, blank=True, default="")
# news_category = models.ForeignKey(BlogCategory, null=True, blank=True)
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# @property
# def blog_posts(self):
# return get_public_blogposts(self.news_category)[:4]
#
# class Meta:
# verbose_name = 'Home pagina'
# verbose_name_plural = "Home pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPage(Page, RichText):
# """
# """
# organisation_part_pages = models.ManyToManyField(OrganisationPartPage, blank=True, verbose_name="Organisatie onderdelen")
#
# class Meta:
# verbose_name = 'Organisatie pagina'
# verbose_name_plural = "Organisatie pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPartPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_organisation_image])
#
# class Meta:
# verbose_name = 'Organisatie-onderdeel pagina'
# verbose_name_plural = "Organisatie-onderdeel pagina's"
#
# Path: website/jdpages/models.py
# class VisionPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_vision_image])
#
# class Meta:
# verbose_name = 'Standpunt pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/models.py
# class VisionsPage(Page, RichText):
# """
# """
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# class Meta:
# verbose_name = 'Standpunten pagina'
# verbose_name_plural = "Standpunten pagina's"
#
# Path: website/jdpages/models.py
# class WordLidPage(Page, RichText):
# """
# """
#
# class Meta:
# verbose_name = 'Word lid pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/views.py
# def get_page_header(page):
# """
# :returns: the page header for a given page.
# Uses parent page image when none is defined.
# Top parent is the HomePage.
# None when there is no Hompage or when the HomePage has no header.
# """
#
# # Get a random page header, or the first one if there is only one
# image = PageHeaderImage.objects.filter(page=page).order_by('?').first()
# if image is not None:
# return image
#
# # No image found! If we received an integer, then do not search further
# if isinstance(page, int):
# return None
#
# # Try from parent
# if page.parent:
# return get_page_header(page.parent)
#
# # Try from first homepage
# homepage = get_homepage_id()
# if homepage is not None:
# # Since we give get_page_header an integer, there is no infinite recursion here...
# return get_page_header(homepage)
#
# return None
. Output only the next line. | @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|>
, continue by predicting the next line. Consider current file imports:
import logging
from mezzanine.blog.views import blog_post_list
from mezzanine.pages.page_processors import processor_for
from mezzanine.pages.models import RichTextPage
from website.jdpages.models import BlogCategoryPage
from mezzanine.forms.models import Form
from website.jdpages.models import HomePage
from website.jdpages.models import OrganisationPage
from website.jdpages.models import OrganisationPartPage
from website.jdpages.models import VisionPage
from website.jdpages.models import VisionsPage
from website.jdpages.models import WordLidPage
from website.jdpages.views import get_page_header
and context:
# Path: website/jdpages/models.py
# class BlogCategoryPage(Page, RichText):
# """
# Model for a page that displays a list of posts in a single blog category.
# """
#
# blog_category = models.ForeignKey(BlogCategory, null=False, blank=False)
# show_excerpt = models.BooleanField(default=False, null=False, blank=False,
# help_text='Show only the first paragraph of a blog post.')
#
# class Meta:
# verbose_name = "Blog categorie pagina"
# verbose_name_plural = "Blog categorie pagina's"
#
# Path: website/jdpages/models.py
# class HomePage(Page, RichText):
# """
# Page model for the site homepage.
# Only works properly when url points to the homepage '/' as url.
# """
# header_title = models.CharField(max_length=300, blank=True, default="")
# header_subtitle = models.CharField(max_length=500, blank=True, default="")
# news_category = models.ForeignKey(BlogCategory, null=True, blank=True)
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# @property
# def blog_posts(self):
# return get_public_blogposts(self.news_category)[:4]
#
# class Meta:
# verbose_name = 'Home pagina'
# verbose_name_plural = "Home pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPage(Page, RichText):
# """
# """
# organisation_part_pages = models.ManyToManyField(OrganisationPartPage, blank=True, verbose_name="Organisatie onderdelen")
#
# class Meta:
# verbose_name = 'Organisatie pagina'
# verbose_name_plural = "Organisatie pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPartPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_organisation_image])
#
# class Meta:
# verbose_name = 'Organisatie-onderdeel pagina'
# verbose_name_plural = "Organisatie-onderdeel pagina's"
#
# Path: website/jdpages/models.py
# class VisionPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_vision_image])
#
# class Meta:
# verbose_name = 'Standpunt pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/models.py
# class VisionsPage(Page, RichText):
# """
# """
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# class Meta:
# verbose_name = 'Standpunten pagina'
# verbose_name_plural = "Standpunten pagina's"
#
# Path: website/jdpages/models.py
# class WordLidPage(Page, RichText):
# """
# """
#
# class Meta:
# verbose_name = 'Word lid pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/views.py
# def get_page_header(page):
# """
# :returns: the page header for a given page.
# Uses parent page image when none is defined.
# Top parent is the HomePage.
# None when there is no Hompage or when the HomePage has no header.
# """
#
# # Get a random page header, or the first one if there is only one
# image = PageHeaderImage.objects.filter(page=page).order_by('?').first()
# if image is not None:
# return image
#
# # No image found! If we received an integer, then do not search further
# if isinstance(page, int):
# return None
#
# # Try from parent
# if page.parent:
# return get_page_header(page.parent)
#
# # Try from first homepage
# homepage = get_homepage_id()
# if homepage is not None:
# # Since we give get_page_header an integer, there is no infinite recursion here...
# return get_page_header(homepage)
#
# return None
which might include code, classes, or functions. Output only the next line. | @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 mezzanine.blog.views import blog_post_list
from mezzanine.pages.page_processors import processor_for
from mezzanine.pages.models import RichTextPage
from website.jdpages.models import BlogCategoryPage
from mezzanine.forms.models import Form
from website.jdpages.models import HomePage
from website.jdpages.models import OrganisationPage
from website.jdpages.models import OrganisationPartPage
from website.jdpages.models import VisionPage
from website.jdpages.models import VisionsPage
from website.jdpages.models import WordLidPage
from website.jdpages.views import get_page_header
and context (classes, functions, sometimes code) from other files:
# Path: website/jdpages/models.py
# class BlogCategoryPage(Page, RichText):
# """
# Model for a page that displays a list of posts in a single blog category.
# """
#
# blog_category = models.ForeignKey(BlogCategory, null=False, blank=False)
# show_excerpt = models.BooleanField(default=False, null=False, blank=False,
# help_text='Show only the first paragraph of a blog post.')
#
# class Meta:
# verbose_name = "Blog categorie pagina"
# verbose_name_plural = "Blog categorie pagina's"
#
# Path: website/jdpages/models.py
# class HomePage(Page, RichText):
# """
# Page model for the site homepage.
# Only works properly when url points to the homepage '/' as url.
# """
# header_title = models.CharField(max_length=300, blank=True, default="")
# header_subtitle = models.CharField(max_length=500, blank=True, default="")
# news_category = models.ForeignKey(BlogCategory, null=True, blank=True)
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# @property
# def blog_posts(self):
# return get_public_blogposts(self.news_category)[:4]
#
# class Meta:
# verbose_name = 'Home pagina'
# verbose_name_plural = "Home pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPage(Page, RichText):
# """
# """
# organisation_part_pages = models.ManyToManyField(OrganisationPartPage, blank=True, verbose_name="Organisatie onderdelen")
#
# class Meta:
# verbose_name = 'Organisatie pagina'
# verbose_name_plural = "Organisatie pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPartPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_organisation_image])
#
# class Meta:
# verbose_name = 'Organisatie-onderdeel pagina'
# verbose_name_plural = "Organisatie-onderdeel pagina's"
#
# Path: website/jdpages/models.py
# class VisionPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_vision_image])
#
# class Meta:
# verbose_name = 'Standpunt pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/models.py
# class VisionsPage(Page, RichText):
# """
# """
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# class Meta:
# verbose_name = 'Standpunten pagina'
# verbose_name_plural = "Standpunten pagina's"
#
# Path: website/jdpages/models.py
# class WordLidPage(Page, RichText):
# """
# """
#
# class Meta:
# verbose_name = 'Word lid pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/views.py
# def get_page_header(page):
# """
# :returns: the page header for a given page.
# Uses parent page image when none is defined.
# Top parent is the HomePage.
# None when there is no Hompage or when the HomePage has no header.
# """
#
# # Get a random page header, or the first one if there is only one
# image = PageHeaderImage.objects.filter(page=page).order_by('?').first()
# if image is not None:
# return image
#
# # No image found! If we received an integer, then do not search further
# if isinstance(page, int):
# return None
#
# # Try from parent
# if page.parent:
# return get_page_header(page.parent)
#
# # Try from first homepage
# homepage = get_homepage_id()
# if homepage is not None:
# # Since we give get_page_header an integer, there is no infinite recursion here...
# return get_page_header(homepage)
#
# return None
. Output only the next line. | @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 logging
from mezzanine.blog.views import blog_post_list
from mezzanine.pages.page_processors import processor_for
from mezzanine.pages.models import RichTextPage
from website.jdpages.models import BlogCategoryPage
from mezzanine.forms.models import Form
from website.jdpages.models import HomePage
from website.jdpages.models import OrganisationPage
from website.jdpages.models import OrganisationPartPage
from website.jdpages.models import VisionPage
from website.jdpages.models import VisionsPage
from website.jdpages.models import WordLidPage
from website.jdpages.views import get_page_header
and context from other files:
# Path: website/jdpages/models.py
# class BlogCategoryPage(Page, RichText):
# """
# Model for a page that displays a list of posts in a single blog category.
# """
#
# blog_category = models.ForeignKey(BlogCategory, null=False, blank=False)
# show_excerpt = models.BooleanField(default=False, null=False, blank=False,
# help_text='Show only the first paragraph of a blog post.')
#
# class Meta:
# verbose_name = "Blog categorie pagina"
# verbose_name_plural = "Blog categorie pagina's"
#
# Path: website/jdpages/models.py
# class HomePage(Page, RichText):
# """
# Page model for the site homepage.
# Only works properly when url points to the homepage '/' as url.
# """
# header_title = models.CharField(max_length=300, blank=True, default="")
# header_subtitle = models.CharField(max_length=500, blank=True, default="")
# news_category = models.ForeignKey(BlogCategory, null=True, blank=True)
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# @property
# def blog_posts(self):
# return get_public_blogposts(self.news_category)[:4]
#
# class Meta:
# verbose_name = 'Home pagina'
# verbose_name_plural = "Home pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPage(Page, RichText):
# """
# """
# organisation_part_pages = models.ManyToManyField(OrganisationPartPage, blank=True, verbose_name="Organisatie onderdelen")
#
# class Meta:
# verbose_name = 'Organisatie pagina'
# verbose_name_plural = "Organisatie pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPartPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_organisation_image])
#
# class Meta:
# verbose_name = 'Organisatie-onderdeel pagina'
# verbose_name_plural = "Organisatie-onderdeel pagina's"
#
# Path: website/jdpages/models.py
# class VisionPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_vision_image])
#
# class Meta:
# verbose_name = 'Standpunt pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/models.py
# class VisionsPage(Page, RichText):
# """
# """
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# class Meta:
# verbose_name = 'Standpunten pagina'
# verbose_name_plural = "Standpunten pagina's"
#
# Path: website/jdpages/models.py
# class WordLidPage(Page, RichText):
# """
# """
#
# class Meta:
# verbose_name = 'Word lid pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/views.py
# def get_page_header(page):
# """
# :returns: the page header for a given page.
# Uses parent page image when none is defined.
# Top parent is the HomePage.
# None when there is no Hompage or when the HomePage has no header.
# """
#
# # Get a random page header, or the first one if there is only one
# image = PageHeaderImage.objects.filter(page=page).order_by('?').first()
# if image is not None:
# return image
#
# # No image found! If we received an integer, then do not search further
# if isinstance(page, int):
# return None
#
# # Try from parent
# if page.parent:
# return get_page_header(page.parent)
#
# # Try from first homepage
# homepage = get_homepage_id()
# if homepage is not None:
# # Since we give get_page_header an integer, there is no infinite recursion here...
# return get_page_header(homepage)
#
# return None
, which may include functions, classes, or code. Output only the next line. | @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_for(OrganisationPage)
@processor_for(OrganisationPartPage)
@processor_for(BlogCategoryPage)
@processor_for(RichTextPage)
<|code_end|>
, predict the next line using imports from the current file:
import logging
from mezzanine.blog.views import blog_post_list
from mezzanine.pages.page_processors import processor_for
from mezzanine.pages.models import RichTextPage
from website.jdpages.models import BlogCategoryPage
from mezzanine.forms.models import Form
from website.jdpages.models import HomePage
from website.jdpages.models import OrganisationPage
from website.jdpages.models import OrganisationPartPage
from website.jdpages.models import VisionPage
from website.jdpages.models import VisionsPage
from website.jdpages.models import WordLidPage
from website.jdpages.views import get_page_header
and context including class names, function names, and sometimes code from other files:
# Path: website/jdpages/models.py
# class BlogCategoryPage(Page, RichText):
# """
# Model for a page that displays a list of posts in a single blog category.
# """
#
# blog_category = models.ForeignKey(BlogCategory, null=False, blank=False)
# show_excerpt = models.BooleanField(default=False, null=False, blank=False,
# help_text='Show only the first paragraph of a blog post.')
#
# class Meta:
# verbose_name = "Blog categorie pagina"
# verbose_name_plural = "Blog categorie pagina's"
#
# Path: website/jdpages/models.py
# class HomePage(Page, RichText):
# """
# Page model for the site homepage.
# Only works properly when url points to the homepage '/' as url.
# """
# header_title = models.CharField(max_length=300, blank=True, default="")
# header_subtitle = models.CharField(max_length=500, blank=True, default="")
# news_category = models.ForeignKey(BlogCategory, null=True, blank=True)
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# @property
# def blog_posts(self):
# return get_public_blogposts(self.news_category)[:4]
#
# class Meta:
# verbose_name = 'Home pagina'
# verbose_name_plural = "Home pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPage(Page, RichText):
# """
# """
# organisation_part_pages = models.ManyToManyField(OrganisationPartPage, blank=True, verbose_name="Organisatie onderdelen")
#
# class Meta:
# verbose_name = 'Organisatie pagina'
# verbose_name_plural = "Organisatie pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPartPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_organisation_image])
#
# class Meta:
# verbose_name = 'Organisatie-onderdeel pagina'
# verbose_name_plural = "Organisatie-onderdeel pagina's"
#
# Path: website/jdpages/models.py
# class VisionPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_vision_image])
#
# class Meta:
# verbose_name = 'Standpunt pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/models.py
# class VisionsPage(Page, RichText):
# """
# """
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# class Meta:
# verbose_name = 'Standpunten pagina'
# verbose_name_plural = "Standpunten pagina's"
#
# Path: website/jdpages/models.py
# class WordLidPage(Page, RichText):
# """
# """
#
# class Meta:
# verbose_name = 'Word lid pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/views.py
# def get_page_header(page):
# """
# :returns: the page header for a given page.
# Uses parent page image when none is defined.
# Top parent is the HomePage.
# None when there is no Hompage or when the HomePage has no header.
# """
#
# # Get a random page header, or the first one if there is only one
# image = PageHeaderImage.objects.filter(page=page).order_by('?').first()
# if image is not None:
# return image
#
# # No image found! If we received an integer, then do not search further
# if isinstance(page, int):
# return None
#
# # Try from parent
# if page.parent:
# return get_page_header(page.parent)
#
# # Try from first homepage
# homepage = get_homepage_id()
# if homepage is not None:
# # Since we give get_page_header an integer, there is no infinite recursion here...
# return get_page_header(homepage)
#
# return None
. Output only the next line. | @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(OrganisationPartPage)
@processor_for(BlogCategoryPage)
@processor_for(RichTextPage)
@processor_for(WordLidPage)
def add_header_images(request, page):
<|code_end|>
, determine the next line of code. You have imports:
import logging
from mezzanine.blog.views import blog_post_list
from mezzanine.pages.page_processors import processor_for
from mezzanine.pages.models import RichTextPage
from website.jdpages.models import BlogCategoryPage
from mezzanine.forms.models import Form
from website.jdpages.models import HomePage
from website.jdpages.models import OrganisationPage
from website.jdpages.models import OrganisationPartPage
from website.jdpages.models import VisionPage
from website.jdpages.models import VisionsPage
from website.jdpages.models import WordLidPage
from website.jdpages.views import get_page_header
and context (class names, function names, or code) available:
# Path: website/jdpages/models.py
# class BlogCategoryPage(Page, RichText):
# """
# Model for a page that displays a list of posts in a single blog category.
# """
#
# blog_category = models.ForeignKey(BlogCategory, null=False, blank=False)
# show_excerpt = models.BooleanField(default=False, null=False, blank=False,
# help_text='Show only the first paragraph of a blog post.')
#
# class Meta:
# verbose_name = "Blog categorie pagina"
# verbose_name_plural = "Blog categorie pagina's"
#
# Path: website/jdpages/models.py
# class HomePage(Page, RichText):
# """
# Page model for the site homepage.
# Only works properly when url points to the homepage '/' as url.
# """
# header_title = models.CharField(max_length=300, blank=True, default="")
# header_subtitle = models.CharField(max_length=500, blank=True, default="")
# news_category = models.ForeignKey(BlogCategory, null=True, blank=True)
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# @property
# def blog_posts(self):
# return get_public_blogposts(self.news_category)[:4]
#
# class Meta:
# verbose_name = 'Home pagina'
# verbose_name_plural = "Home pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPage(Page, RichText):
# """
# """
# organisation_part_pages = models.ManyToManyField(OrganisationPartPage, blank=True, verbose_name="Organisatie onderdelen")
#
# class Meta:
# verbose_name = 'Organisatie pagina'
# verbose_name_plural = "Organisatie pagina's"
#
# Path: website/jdpages/models.py
# class OrganisationPartPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_organisation_image])
#
# class Meta:
# verbose_name = 'Organisatie-onderdeel pagina'
# verbose_name_plural = "Organisatie-onderdeel pagina's"
#
# Path: website/jdpages/models.py
# class VisionPage(Page, RichText):
# """
# """
# image = FileField(max_length=300, format="Image", blank=True, default="", validators=[validate_vision_image])
#
# class Meta:
# verbose_name = 'Standpunt pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/models.py
# class VisionsPage(Page, RichText):
# """
# """
# vision_pages = models.ManyToManyField(VisionPage, blank=True, verbose_name="Standpunt pagina's")
#
# class Meta:
# verbose_name = 'Standpunten pagina'
# verbose_name_plural = "Standpunten pagina's"
#
# Path: website/jdpages/models.py
# class WordLidPage(Page, RichText):
# """
# """
#
# class Meta:
# verbose_name = 'Word lid pagina'
# verbose_name_plural = "Standpunt pagina's"
#
# Path: website/jdpages/views.py
# def get_page_header(page):
# """
# :returns: the page header for a given page.
# Uses parent page image when none is defined.
# Top parent is the HomePage.
# None when there is no Hompage or when the HomePage has no header.
# """
#
# # Get a random page header, or the first one if there is only one
# image = PageHeaderImage.objects.filter(page=page).order_by('?').first()
# if image is not None:
# return image
#
# # No image found! If we received an integer, then do not search further
# if isinstance(page, int):
# return None
#
# # Try from parent
# if page.parent:
# return get_page_header(page.parent)
#
# # Try from first homepage
# homepage = get_homepage_id()
# if homepage is not None:
# # Since we give get_page_header an integer, there is no infinite recursion here...
# return get_page_header(homepage)
#
# return None
. Output only the next line. | 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("data", PickleType, unique=True),
)
<|code_end|>
, determine the next line of code. You have imports:
from sqlalchemy import Column, Table, select
from sqlalchemy.types import Integer, PickleType, DateTime, Unicode
from webtools.database import Base
from webtools.utils import timezone
from .base import BaseSessionEngine
and context (class names, function names, or code) available:
# Path: webtools/database.py
#
# Path: webtools/utils/timezone.py
# def get_default_timezone_name(application=None):
# def get_default_timezone(application):
# def as_localtime(value, timezone):
# def get_timezone(name):
# def make_aware(value, timezone):
# def make_naive(value, timezone):
#
# Path: webtools/session/backend/base.py
# class BaseSessionEngine(object):
# def __init__(self, application):
# self._application = application
# self._session_data = None
# self._modified = False
# self._current_session_key = None
#
# @property
# def is_modified(self):
# return self._modified
#
# @property
# def session_key(self):
# return self._application.settings.get('session_key', 'tornado_webtools_sessionid')
#
# def __contains__(self, key):
# return key in self.session_data
#
# def __getitem__(self, key):
# return self.session_data[key]
#
# def __setitem__(self, key, value):
# self.session_data[key] = value
# self._modified = True
#
# def __delitem__(self, key):
# del self.session_data[key]
# self._modified = True
#
# def get(self, key, default=None):
# return self.session_data.get(key, default)
#
# def pop(self, key, *args):
# self._modified = self._modified or key in self.session_data
# return self.session_data.pop(key, *args)
#
# def update(self, data):
# assert isinstance(data, dict), "the first parameter must be a dict instance"
# self.session_data.update(data)
# self._modified = True
#
# def keys(self):
# return self.session_data.keys()
#
# def values(self):
# return self.session_data.values()
#
# def items(self):
# return self.session_data.items()
#
# def clear(self):
# self._session_data = {}
# self._modified = True
#
# def random_session_key(self):
# return str(uuid.uuid1())
#
# @property
# def session_key(self):
# return self._current_session_key
#
# def flush(self):
# self.clear()
# self.delete()
#
# @property
# def session_data(self):
# if self._session_data is None:
# self.load()
#
# return self._session_data
#
# def load(self):
# raise NotImplementedError()
#
# def save(self):
# raise NotImplementedError()
#
# def delete(self):
# raise NotImplementedError()
. Output only the next line. | 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):
commands = {}
default_commands= [
"webtools.management.commands.help.HelpCommand",
"webtools.management.commands.runserver.RunserverCommand",
"webtools.management.commands.syncdb.SyncdbCommand",
"webtools.management.commands.syncdb.DropdbCommand",
"webtools.management.commands.shell.ShellCommand",
]
def __init__(self, app):
self.app = app
def _load_commands(self):
commands = {}
command_list = set(self.default_commands[:])
if self.app.conf is not None:
command_list.update(self.app.conf.COMMANDS or [])
for class_path in command_list:
<|code_end|>
, generate the next line using the imports in this file:
import sys
import argparse
import traceback
import importlib
import inspect
import logging
import logging.handlers
import os
from webtools.utils.imp import load_class
and context (functions, classes, or occasionally code) from other files:
# Path: webtools/utils/imp.py
# def load_class(path):
# """
# Load class from path.
# """
#
# mod_name, klass_name = None, None
#
# try:
# mod_name, klass_name = path.rsplit('.', 1)
# mod = import_module(mod_name)
# except AttributeError as e:
# raise RuntimeError("Error importing {0}: '{1}'".format(mod_name, e))
#
# try:
# klass = getattr(mod, klass_name)
# except AttributeError:
# raise RuntimeError('Module "{0}" does not define a "{1}" class'.format(mod_name, klass_name))
#
# return klass
. Output only the next line. | 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["webtools_locale"])
return None
def _(self, message, plural_message=None, count=None):
return self.locale.translate(message, plural_message=plural_message, count=count)
def activate_locale(self, locale_name):
"""
Activate a specific locale for current user.
"""
self.session["webtools_locale"] = locale_name
self._locale = locale.get(locale_name)
class TimezoneMixin(object):
@property
def timezone(self):
if not hasattr(self, "_timezone"):
self._timezone = self.get_user_timezone()
return self._timezone
def get_user_timezone(self):
if "webtools_timezone" in self.session:
<|code_end|>
, predict the immediate next line with the help of imports:
from tornado import locale
from webtools.utils.timezone import get_default_timezone, get_timezone
and context (classes, functions, sometimes code) from other files:
# Path: webtools/utils/timezone.py
# def get_default_timezone(application):
# global _localtime
#
# if _localtime is None:
# default_tzname = get_default_timezone_name(application)
# _localtime = pytz.timezone(default_tzname)
#
# return _localtime
#
# def get_timezone(name):
# return pytz.timezone(name)
. Output only the next line. | 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 Application(tornado.web.Application):
engine = None
session_engine = None
jinja_env = None
auth_backends = []
context_processors = []
def __init__(self, settings):
self.conf = settings
handlers = self.conf.HANDLERS
if handlers is not None:
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import tornado.web
import importlib
import copy
import os
from .utils.imp import load_class
from .template.base import Library
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from webtools.utils import locale
from jinja2 import PackageLoader
from jinja2 import FileSystemLoader
from jinja2 import Environment, ChoiceLoader
and context:
# Path: webtools/utils/imp.py
# def load_class(path):
# """
# Load class from path.
# """
#
# mod_name, klass_name = None, None
#
# try:
# mod_name, klass_name = path.rsplit('.', 1)
# mod = import_module(mod_name)
# except AttributeError as e:
# raise RuntimeError("Error importing {0}: '{1}'".format(mod_name, e))
#
# try:
# klass = getattr(mod, klass_name)
# except AttributeError:
# raise RuntimeError('Module "{0}" does not define a "{1}" class'.format(mod_name, klass_name))
#
# return klass
#
# Path: webtools/template/base.py
# class Library(object):
# _instance = None
#
# def __new__(cls, *args, **kwargs):
# if not cls._instance:
# cls._instance = super(Library, self).__new__(*args, **kwargs)
# return cls._instance
#
# def __init__(self):
# self._globals = {}
# self._tests = {}
# self._filters = {}
#
# def _update_env(self, env):
# env.filters.update(self._filters)
# env.globals.update(self._globals)
# env.tests.update(self._tests)
#
# def _new_function(self, attr, func, name=None):
# _attr = getattr(self, attr)
# if name is None:
# name = func.__name__
#
# _attr[name] = func
# return func
#
# def _function(self, attr, name=None, _function=None):
# if name is None and _function is None:
# def dec(func):
# return self._new_function(attr, func)
# return dec
#
# elif name is not None and _function is None:
# if callable(name):
# return self._new_function(attr, name)
#
# else:
# def dec(func):
# return self._function(attr, name, func)
# return dec
#
# elif name is not None and _function is not None:
# return self._new_function(attr, _function, name)
#
# raise RuntimeError("Invalid parameters")
#
# def global_function(self, *args, **kwargs):
# return self._function("_globals", *args, **kwargs)
#
# def test(self, *args, **kwargs):
# return self._function("_tests", *args, **kwargs)
#
# def filter(self, *args, **kwargs):
# return self._function("_filters", *args, **kwargs)
which might include code, classes, or functions. Output only the next line. | 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))
module = None
try:
module = importlib.import_module(module_path)
except ImportError:
continue
# setup module template loader
self.loaders.append(PackageLoader(module_path, "templates"))
# setup jinja template additions
try:
importlib.import_module(module_path + ".jinja2_addons")
except ImportError:
pass
# try import models
try:
models_mod = importlib.import_module(module_path + ".models")
self.models_modules.append(models_mod)
except ImportError:
pass
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import tornado.web
import importlib
import copy
import os
from .utils.imp import load_class
from .template.base import Library
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from webtools.utils import locale
from jinja2 import PackageLoader
from jinja2 import FileSystemLoader
from jinja2 import Environment, ChoiceLoader
and context:
# Path: webtools/utils/imp.py
# def load_class(path):
# """
# Load class from path.
# """
#
# mod_name, klass_name = None, None
#
# try:
# mod_name, klass_name = path.rsplit('.', 1)
# mod = import_module(mod_name)
# except AttributeError as e:
# raise RuntimeError("Error importing {0}: '{1}'".format(mod_name, e))
#
# try:
# klass = getattr(mod, klass_name)
# except AttributeError:
# raise RuntimeError('Module "{0}" does not define a "{1}" class'.format(mod_name, klass_name))
#
# return klass
#
# Path: webtools/template/base.py
# class Library(object):
# _instance = None
#
# def __new__(cls, *args, **kwargs):
# if not cls._instance:
# cls._instance = super(Library, self).__new__(*args, **kwargs)
# return cls._instance
#
# def __init__(self):
# self._globals = {}
# self._tests = {}
# self._filters = {}
#
# def _update_env(self, env):
# env.filters.update(self._filters)
# env.globals.update(self._globals)
# env.tests.update(self._tests)
#
# def _new_function(self, attr, func, name=None):
# _attr = getattr(self, attr)
# if name is None:
# name = func.__name__
#
# _attr[name] = func
# return func
#
# def _function(self, attr, name=None, _function=None):
# if name is None and _function is None:
# def dec(func):
# return self._new_function(attr, func)
# return dec
#
# elif name is not None and _function is None:
# if callable(name):
# return self._new_function(attr, name)
#
# else:
# def dec(func):
# return self._function(attr, name, func)
# return dec
#
# elif name is not None and _function is not None:
# return self._new_function(attr, _function, name)
#
# raise RuntimeError("Invalid parameters")
#
# def global_function(self, *args, **kwargs):
# return self._function("_globals", *args, **kwargs)
#
# def test(self, *args, **kwargs):
# return self._function("_tests", *args, **kwargs)
#
# def filter(self, *args, **kwargs):
# return self._function("_filters", *args, **kwargs)
which might include code, classes, or functions. Output only the next line. | 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:
(from webtools.management.base import Command
from webtools.utils.imp import load_class
from webtools.application import Application
import tornado.ioloop)
and context including class names, function names, or small code snippets from other files:
# Path: webtools/management/base.py
# class Command(object):
# def __init__(self, cmdapp):
# self.cmdapp = cmdapp
#
# @classmethod
# def get_name(cls):
# name = cls.__name__.lower()
# if name.endswith("command"):
# name = name[:-7]
# elif name.endswith("cmd"):
# name = name[:-3]
# return name
#
# @classmethod
# def get_description(cls):
# doc = inspect.getdoc(cls)
# if not doc:
# return ""
#
# return doc.strip().split("\n")[0]
#
# @classmethod
# def get_parser(cls, root_parser):
# """
# Return an :class:`argparse.ArgumentParser`.
# """
# return root_parser
#
# def take_action(self, parsed_args):
# """
# Override to do something useful.
# """
# raise NotImplementedError
#
# def run(self, parsed_args):
# """
# Invoked by the application when the command is run.
#
# Developers implementing commands should override
# :meth:`take_action`.
#
# 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
#
# Path: webtools/utils/imp.py
# def load_class(path):
# """
# Load class from path.
# """
#
# mod_name, klass_name = None, None
#
# try:
# mod_name, klass_name = path.rsplit('.', 1)
# mod = import_module(mod_name)
# except AttributeError as e:
# raise RuntimeError("Error importing {0}: '{1}'".format(mod_name, e))
#
# try:
# klass = getattr(mod, klass_name)
# except AttributeError:
# raise RuntimeError('Module "{0}" does not define a "{1}" class'.format(mod_name, klass_name))
#
# return klass
. Output only the next line. | 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, count=count)
@jinja2.contextfilter
def date(context, value, format=None, tz=None):
handler = context["handler"]
if tz is not None:
timezone = get_timezone(tz)
else:
timezone = handler.timezone
if is_naive(value):
value = make_aware(value, get_default_timezone(handler.application))
# TODO: full django like formate subsystem
<|code_end|>
with the help of current file imports:
import jinja2
from webtools.utils.timezone import as_localtime, is_naive, is_aware, make_aware, get_timezone, get_default_timezone
and context from other files:
# Path: webtools/utils/timezone.py
# def get_default_timezone_name(application=None):
# def get_default_timezone(application):
# def as_localtime(value, timezone):
# def get_timezone(name):
# def make_aware(value, timezone):
# def make_naive(value, timezone):
, which may contain function names, class names, or code. Output only the next line. | 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.contextfilter
def date(context, value, format=None, tz=None):
handler = context["handler"]
if tz is not None:
timezone = get_timezone(tz)
else:
timezone = handler.timezone
<|code_end|>
. Write the next line using the current file imports:
import jinja2
from webtools.utils.timezone import as_localtime, is_naive, is_aware, make_aware, get_timezone, get_default_timezone
and context from other files:
# Path: webtools/utils/timezone.py
# def get_default_timezone_name(application=None):
# def get_default_timezone(application):
# def as_localtime(value, timezone):
# def get_timezone(name):
# def make_aware(value, timezone):
# def make_naive(value, timezone):
, which may include functions, classes, or code. Output only the next line. | 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.contextfilter
def date(context, value, format=None, tz=None):
handler = context["handler"]
if tz is not None:
timezone = get_timezone(tz)
else:
timezone = handler.timezone
if is_naive(value):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import jinja2
from webtools.utils.timezone import as_localtime, is_naive, is_aware, make_aware, get_timezone, get_default_timezone
and context:
# Path: webtools/utils/timezone.py
# def get_default_timezone_name(application=None):
# def get_default_timezone(application):
# def as_localtime(value, timezone):
# def get_timezone(name):
# def make_aware(value, timezone):
# def make_naive(value, timezone):
which might include code, classes, or functions. Output only the next line. | 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)
@jinja2.contextfilter
def date(context, value, format=None, tz=None):
handler = context["handler"]
if tz is not None:
<|code_end|>
, generate the next line using the imports in this file:
import jinja2
from webtools.utils.timezone import as_localtime, is_naive, is_aware, make_aware, get_timezone, get_default_timezone
and context (functions, classes, or occasionally code) from other files:
# Path: webtools/utils/timezone.py
# def get_default_timezone_name(application=None):
# def get_default_timezone(application):
# def as_localtime(value, timezone):
# def get_timezone(name):
# def make_aware(value, timezone):
# def make_naive(value, timezone):
. Output only the next line. | 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, count=count)
@jinja2.contextfilter
def date(context, value, format=None, tz=None):
handler = context["handler"]
if tz is not None:
timezone = get_timezone(tz)
else:
timezone = handler.timezone
if is_naive(value):
<|code_end|>
with the help of current file imports:
import jinja2
from webtools.utils.timezone import as_localtime, is_naive, is_aware, make_aware, get_timezone, get_default_timezone
and context from other files:
# Path: webtools/utils/timezone.py
# def get_default_timezone_name(application=None):
# def get_default_timezone(application):
# def as_localtime(value, timezone):
# def get_timezone(name):
# def make_aware(value, timezone):
# def make_naive(value, timezone):
, which may contain function names, class names, or code. Output only the next line. | 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):
def authenticate(self, username=None, password=None):
try:
<|code_end|>
, predict the immediate next line with the help of imports:
from sqlalchemy.orm.exc import NoResultFound
from .models import User
from .hashers import check_password
and context (classes, functions, sometimes code) from other files:
# Path: webtools/auth/models.py
# 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(Unicode(200), nullable=False)
# email = Column(Unicode(200), nullable=False)
# password = Column(String(200), nullable=False)
#
# def __repr__(self):
# return "<User {0}>".format(self.id)
#
# def set_password(self, password):
# self.password = make_password(password)
#
# def check_password(self, password):
# return check_password(password, self.password)
#
# Path: webtools/auth/hashers.py
# def check_password(password, encoded, setter=None, preferred='default'):
# """
# Returns a boolean of whether the raw password matches the three
# part encoded digest.
#
# If setter is specified, it'll be called when you need to
# regenerate the password.
# """
# if not password or not is_password_usable(encoded):
# return False
#
# preferred = get_hasher(preferred)
# hasher = identify_hasher(encoded)
#
# must_update = hasher.algorithm != preferred.algorithm
# is_correct = hasher.verify(password, encoded)
# if setter and is_correct and must_update:
# setter(password)
# return is_correct
. Output only the next line. | 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):
def authenticate(self, username=None, password=None):
try:
user = self.application.db.query(User).filter(User.username == username).one()
<|code_end|>
, predict the immediate next line with the help of imports:
from sqlalchemy.orm.exc import NoResultFound
from .models import User
from .hashers import check_password
and context (classes, functions, sometimes code) from other files:
# Path: webtools/auth/models.py
# 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(Unicode(200), nullable=False)
# email = Column(Unicode(200), nullable=False)
# password = Column(String(200), nullable=False)
#
# def __repr__(self):
# return "<User {0}>".format(self.id)
#
# def set_password(self, password):
# self.password = make_password(password)
#
# def check_password(self, password):
# return check_password(password, self.password)
#
# Path: webtools/auth/hashers.py
# def check_password(password, encoded, setter=None, preferred='default'):
# """
# Returns a boolean of whether the raw password matches the three
# part encoded digest.
#
# If setter is specified, it'll be called when you need to
# regenerate the password.
# """
# if not password or not is_password_usable(encoded):
# return False
#
# preferred = get_hasher(preferred)
# hasher = identify_hasher(encoded)
#
# must_update = hasher.algorithm != preferred.algorithm
# is_correct = hasher.verify(password, encoded)
# if setter and is_correct and must_update:
# setter(password)
# return is_correct
. Output only the next line. | 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_name = Column(Unicode(200), nullable=False)
email = Column(Unicode(200), nullable=False)
password = Column(String(200), nullable=False)
def __repr__(self):
return "<User {0}>".format(self.id)
def set_password(self, password):
<|code_end|>
using the current file's imports:
from sqlalchemy import Column
from sqlalchemy.types import Integer, String, DateTime, Unicode
from webtools.database import Base
from .hashers import make_password, check_password
and any relevant context from other files:
# Path: webtools/database.py
#
# Path: webtools/auth/hashers.py
# def make_password(password, salt=None, hasher='default'):
# """
# Turn a plain-text password into a hash for database storage
#
# Same as encode() but generates a new random salt. If
# password is None or blank then UNUSABLE_PASSWORD will be
# returned which disallows logins.
# """
#
# if not password:
# return UNUSABLE_PASSWORD
#
# hasher = get_hasher(hasher)
#
# if not salt:
# salt = hasher.salt()
#
# return hasher.encode(password, salt)
#
# def check_password(password, encoded, setter=None, preferred='default'):
# """
# Returns a boolean of whether the raw password matches the three
# part encoded digest.
#
# If setter is specified, it'll be called when you need to
# regenerate the password.
# """
# if not password or not is_password_usable(encoded):
# return False
#
# preferred = get_hasher(preferred)
# hasher = identify_hasher(encoded)
#
# must_update = hasher.algorithm != preferred.algorithm
# is_correct = hasher.verify(password, encoded)
# if setter and is_correct and must_update:
# setter(password)
# return is_correct
. Output only the next line. | 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(Unicode(200), nullable=False)
email = Column(Unicode(200), nullable=False)
password = Column(String(200), nullable=False)
def __repr__(self):
return "<User {0}>".format(self.id)
def set_password(self, password):
self.password = make_password(password)
<|code_end|>
. Use current file imports:
(from sqlalchemy import Column
from sqlalchemy.types import Integer, String, DateTime, Unicode
from webtools.database import Base
from .hashers import make_password, check_password)
and context including class names, function names, or small code snippets from other files:
# Path: webtools/database.py
#
# Path: webtools/auth/hashers.py
# def make_password(password, salt=None, hasher='default'):
# """
# Turn a plain-text password into a hash for database storage
#
# Same as encode() but generates a new random salt. If
# password is None or blank then UNUSABLE_PASSWORD will be
# returned which disallows logins.
# """
#
# if not password:
# return UNUSABLE_PASSWORD
#
# hasher = get_hasher(hasher)
#
# if not salt:
# salt = hasher.salt()
#
# return hasher.encode(password, salt)
#
# def check_password(password, encoded, setter=None, preferred='default'):
# """
# Returns a boolean of whether the raw password matches the three
# part encoded digest.
#
# If setter is specified, it'll be called when you need to
# regenerate the password.
# """
# if not password or not is_password_usable(encoded):
# return False
#
# preferred = get_hasher(preferred)
# hasher = identify_hasher(encoded)
#
# must_update = hasher.algorithm != preferred.algorithm
# is_correct = hasher.verify(password, encoded)
# if setter and is_correct and must_update:
# setter(password)
# return is_correct
. Output only the next line. | 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 = {}
self._validated = False
self._initial = copy.deepcopy(self.initial)
def with_prefix(self, name):
if self.prefix is None:
return name
return "{0}-{1}".format(self.prefix, name)
def _field_validate(self):
for field_name, field in self.base_fields.items():
field_name_with_prefix = self.with_prefix(field_name)
try:
value = field.clean(field_name_with_prefix, self)
if not field.required and value is None:
continue
self.cleaned_data[field_name] = value
<|code_end|>
, generate the next line using the imports in this file:
from .exceptions import ValidateError
from .field import Field, BoundField
import copy
and context (functions, classes, or occasionally code) from other files:
# Path: webtools/formdata/exceptions.py
# class ValidateError(Exception):
# pass
#
# Path: webtools/formdata/field.py
# 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.required = required
# self.widget = widget
#
# if self.widget:
# if isinstance(self.widget, type):
# self.widget = self.widget()
# assert isinstance(self.widget, Widget), "widget must be a instance of Widget"
#
# def clean(self, name, formdata):
# raw_value = formdata.get_argument(name)
# if raw_value:
# return self.datatype.to_python(raw_value, self)
# else:
# if not self.required:
# return self.default
# raise ValidateError("this field is required")
#
# class BoundField(object):
# def __init__(self, name, prefixed_name, field, form):
# self.name = name
# self.prefixed_name = prefixed_name
# self.field = field
# self.form = form
#
# def __str__(self):
# if not self.field.widget:
# return ""
#
# value = self.form._initial.get(self.name, None)
# value = self.field.datatype.from_python(value)
#
# return self.field.widget(self.name, self.prefixed_name, value)
. Output only the next line. | 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
def validate(self):
if self.handler is None:
raise RuntimeError("Cannot validate form without handler instance")
self.cleaned_data = {}
self._field_validate()
self._form_validate()
self._validated = True
self._initial.update(self.cleaned_data)
def is_valid(self):
return not bool(self.errors) and self._validated
def get_argument(self, name):
return self.handler.get_arguments(name)
def __getitem__(self, name):
if name in self.base_fields:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .exceptions import ValidateError
from .field import Field, BoundField
import copy
and context:
# Path: webtools/formdata/exceptions.py
# class ValidateError(Exception):
# pass
#
# Path: webtools/formdata/field.py
# 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.required = required
# self.widget = widget
#
# if self.widget:
# if isinstance(self.widget, type):
# self.widget = self.widget()
# assert isinstance(self.widget, Widget), "widget must be a instance of Widget"
#
# def clean(self, name, formdata):
# raw_value = formdata.get_argument(name)
# if raw_value:
# return self.datatype.to_python(raw_value, self)
# else:
# if not self.required:
# return self.default
# raise ValidateError("this field is required")
#
# class BoundField(object):
# def __init__(self, name, prefixed_name, field, form):
# self.name = name
# self.prefixed_name = prefixed_name
# self.field = field
# self.form = form
#
# def __str__(self):
# if not self.field.widget:
# return ""
#
# value = self.form._initial.get(self.name, None)
# value = self.field.datatype.from_python(value)
#
# return self.field.widget(self.name, self.prefixed_name, value)
which might include code, classes, or functions. Output only the next line. | 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.required = required
self.widget = widget
if self.widget:
if isinstance(self.widget, type):
self.widget = self.widget()
<|code_end|>
with the help of current file imports:
from .widgets import Widget
from .exceptions import ValidateError
from . import data_types
and context from other files:
# Path: webtools/formdata/widgets.py
# class Widget(object):
# """
# Base class for all formdata widgets.
# """
#
# def __init__(self, attrs={}):
# self.attrs = attrs
#
# def set_field(self, field):
# self.field = field
#
# def render(self, name, prefixed_name, value):
# raise NotImplementedError()
#
# def attrs_to_str(self, attrs):
# return " ".join(['{key}="{val}"'.format(key=x, val=y)
# for x,y in attrs.items()])
#
# def __call__(self, name, prefixed_name, value):
# return self.render(name, prefixed_name, value)
#
# Path: webtools/formdata/exceptions.py
# class ValidateError(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | 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.required = required
self.widget = widget
if self.widget:
if isinstance(self.widget, type):
self.widget = self.widget()
assert isinstance(self.widget, Widget), "widget must be a instance of Widget"
def clean(self, name, formdata):
raw_value = formdata.get_argument(name)
if raw_value:
return self.datatype.to_python(raw_value, self)
else:
if not self.required:
return self.default
<|code_end|>
with the help of current file imports:
from .widgets import Widget
from .exceptions import ValidateError
from . import data_types
and context from other files:
# Path: webtools/formdata/widgets.py
# class Widget(object):
# """
# Base class for all formdata widgets.
# """
#
# def __init__(self, attrs={}):
# self.attrs = attrs
#
# def set_field(self, field):
# self.field = field
#
# def render(self, name, prefixed_name, value):
# raise NotImplementedError()
#
# def attrs_to_str(self, attrs):
# return " ".join(['{key}="{val}"'.format(key=x, val=y)
# for x,y in attrs.items()])
#
# def __call__(self, name, prefixed_name, value):
# return self.render(name, prefixed_name, value)
#
# Path: webtools/formdata/exceptions.py
# class ValidateError(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | 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 global settings.
"""
if lang is None and handler is None:
raise RuntimeError("One of parameters 'lang' or 'handler' is mandatory")
<|code_end|>
. Use current file imports:
from webtools.utils.encoding import smart_text
from .base import Service
and context (classes, functions, or code) from other files:
# Path: webtools/utils/encoding.py
# def smart_text(value, encoding="utf-8", errors="strict"):
# if isinstance(value, str):
# if encoding == "utf-8":
# return value
#
# return value.encode('utf-8', errors).decode(encoding, errors)
#
# if not isinstance(value, bytes):
# return str(value)
#
# return value.decode(encoding, errors)
#
# Path: webtools/services/base.py
# class Service(objects):
# """
# Base class for all services.
# """
# def __get__(self, instance, owner):
# return ServiceDescriptor(self, instance, owner)
. Output only the next line. | 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.database import Base
from webtools.auth.models import User
from .settings import TestOverwriteSettings
from webtools.application import Application
and context including class names, function names, and sometimes code from other files:
# Path: webtools/database.py
#
# Path: webtools/auth/models.py
# 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(Unicode(200), nullable=False)
# email = Column(Unicode(200), nullable=False)
# password = Column(String(200), nullable=False)
#
# def __repr__(self):
# return "<User {0}>".format(self.id)
#
# def set_password(self, password):
# self.password = make_password(password)
#
# def check_password(self, password):
# return check_password(password, self.password)
#
# Path: tests/settings.py
# class TestOverwriteSettings(Settings):
# SQLALCHEMY_ENGINE_URL = "sqlite://"
# AUTHENTICATION_BACKENDS = ["webtools.auth.backends.DatabaseAuthenticationBackend"]
#
# JINJA2_TEMPLATE_DIRS = [
# os.path.join(CURRENT_PATH, "template")
# ]
# INSTALLED_MODULES = [
# "tests",
# ]
#
# COMMANDS = [
# "webtools.management.commands.runserver.RunserverCommand",
# ]
#
# I18N = True
#
# I18N_DIRECTORIES = [
# os.path.join(CURRENT_PATH, "locale"),
# ]
. Output only the next line. | 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):
Base.metadata.drop_all(cls.app.engine)
def tearDown(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from webtools.database import Base
from webtools.auth.models import User
from .settings import TestOverwriteSettings
from webtools.application import Application
and context including class names, function names, and sometimes code from other files:
# Path: webtools/database.py
#
# Path: webtools/auth/models.py
# 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(Unicode(200), nullable=False)
# email = Column(Unicode(200), nullable=False)
# password = Column(String(200), nullable=False)
#
# def __repr__(self):
# return "<User {0}>".format(self.id)
#
# def set_password(self, password):
# self.password = make_password(password)
#
# def check_password(self, password):
# return check_password(password, self.password)
#
# Path: tests/settings.py
# class TestOverwriteSettings(Settings):
# SQLALCHEMY_ENGINE_URL = "sqlite://"
# AUTHENTICATION_BACKENDS = ["webtools.auth.backends.DatabaseAuthenticationBackend"]
#
# JINJA2_TEMPLATE_DIRS = [
# os.path.join(CURRENT_PATH, "template")
# ]
# INSTALLED_MODULES = [
# "tests",
# ]
#
# COMMANDS = [
# "webtools.management.commands.runserver.RunserverCommand",
# ]
#
# I18N = True
#
# I18N_DIRECTORIES = [
# os.path.join(CURRENT_PATH, "locale"),
# ]
. Output only the next line. | 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 TestOverwriteSettings
from webtools.application import Application
and context from other files:
# Path: webtools/database.py
#
# Path: webtools/auth/models.py
# 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(Unicode(200), nullable=False)
# email = Column(Unicode(200), nullable=False)
# password = Column(String(200), nullable=False)
#
# def __repr__(self):
# return "<User {0}>".format(self.id)
#
# def set_password(self, password):
# self.password = make_password(password)
#
# def check_password(self, password):
# return check_password(password, self.password)
#
# Path: tests/settings.py
# class TestOverwriteSettings(Settings):
# SQLALCHEMY_ENGINE_URL = "sqlite://"
# AUTHENTICATION_BACKENDS = ["webtools.auth.backends.DatabaseAuthenticationBackend"]
#
# JINJA2_TEMPLATE_DIRS = [
# os.path.join(CURRENT_PATH, "template")
# ]
# INSTALLED_MODULES = [
# "tests",
# ]
#
# COMMANDS = [
# "webtools.management.commands.runserver.RunserverCommand",
# ]
#
# I18N = True
#
# I18N_DIRECTORIES = [
# os.path.join(CURRENT_PATH, "locale"),
# ]
, which may contain function names, class names, or code. Output only the next line. | 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)):
value = [value]
return value
<|code_end|>
. Write the next line using the current file imports:
from unittest import TestCase
from webtools.formdata.base import FormData
from webtools.formdata.field import Field
from webtools.formdata import data_types as types
from webtools.formdata import widgets
and context from other files:
# Path: webtools/formdata/base.py
# class FormData(FormDataBase, metaclass=FormDataMeta):
# pass
#
# Path: webtools/formdata/field.py
# 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.required = required
# self.widget = widget
#
# if self.widget:
# if isinstance(self.widget, type):
# self.widget = self.widget()
# assert isinstance(self.widget, Widget), "widget must be a instance of Widget"
#
# def clean(self, name, formdata):
# raw_value = formdata.get_argument(name)
# if raw_value:
# return self.datatype.to_python(raw_value, self)
# else:
# if not self.required:
# return self.default
# raise ValidateError("this field is required")
#
# Path: webtools/formdata/data_types.py
# class Type(object):
# class Integer(Type):
# class Unicode(Type):
# class MultipleUnicode(Type):
# class MultipleInteger(Type):
# class Date(Type):
# class DateTime(Type):
# def to_python(self, value, field):
# def from_python(self, value):
# def to_python(self, value, field):
# def to_python(self, value, field):
# def to_python(self, value, field):
#
# Path: webtools/formdata/widgets.py
# class Widget(object):
# class InputText(Widget):
# class Textarea(Widget):
# def __init__(self, attrs={}):
# def set_field(self, field):
# def render(self, name, prefixed_name, value):
# def attrs_to_str(self, attrs):
# def __call__(self, name, prefixed_name, value):
# def render(self, name, prefixed_name, value):
# def render(self, name, prefixed_name, value):
, which may include functions, classes, or code. Output only the next line. | 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)):
value = [value]
return value
class TestForm1(FormData):
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from webtools.formdata.base import FormData
from webtools.formdata.field import Field
from webtools.formdata import data_types as types
from webtools.formdata import widgets
and context (functions, classes, or occasionally code) from other files:
# Path: webtools/formdata/base.py
# class FormData(FormDataBase, metaclass=FormDataMeta):
# pass
#
# Path: webtools/formdata/field.py
# 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.required = required
# self.widget = widget
#
# if self.widget:
# if isinstance(self.widget, type):
# self.widget = self.widget()
# assert isinstance(self.widget, Widget), "widget must be a instance of Widget"
#
# def clean(self, name, formdata):
# raw_value = formdata.get_argument(name)
# if raw_value:
# return self.datatype.to_python(raw_value, self)
# else:
# if not self.required:
# return self.default
# raise ValidateError("this field is required")
#
# Path: webtools/formdata/data_types.py
# class Type(object):
# class Integer(Type):
# class Unicode(Type):
# class MultipleUnicode(Type):
# class MultipleInteger(Type):
# class Date(Type):
# class DateTime(Type):
# def to_python(self, value, field):
# def from_python(self, value):
# def to_python(self, value, field):
# def to_python(self, value, field):
# def to_python(self, value, field):
#
# Path: webtools/formdata/widgets.py
# class Widget(object):
# class InputText(Widget):
# class Textarea(Widget):
# def __init__(self, attrs={}):
# def set_field(self, field):
# def render(self, name, prefixed_name, value):
# def attrs_to_str(self, attrs):
# def __call__(self, name, prefixed_name, value):
# def render(self, name, prefixed_name, value):
# def render(self, name, prefixed_name, value):
. Output only the next line. | 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)):
value = [value]
return value
class TestForm1(FormData):
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from webtools.formdata.base import FormData
from webtools.formdata.field import Field
from webtools.formdata import data_types as types
from webtools.formdata import widgets
and context (classes, functions, sometimes code) from other files:
# Path: webtools/formdata/base.py
# class FormData(FormDataBase, metaclass=FormDataMeta):
# pass
#
# Path: webtools/formdata/field.py
# 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.required = required
# self.widget = widget
#
# if self.widget:
# if isinstance(self.widget, type):
# self.widget = self.widget()
# assert isinstance(self.widget, Widget), "widget must be a instance of Widget"
#
# def clean(self, name, formdata):
# raw_value = formdata.get_argument(name)
# if raw_value:
# return self.datatype.to_python(raw_value, self)
# else:
# if not self.required:
# return self.default
# raise ValidateError("this field is required")
#
# Path: webtools/formdata/data_types.py
# class Type(object):
# class Integer(Type):
# class Unicode(Type):
# class MultipleUnicode(Type):
# class MultipleInteger(Type):
# class Date(Type):
# class DateTime(Type):
# def to_python(self, value, field):
# def from_python(self, value):
# def to_python(self, value, field):
# def to_python(self, value, field):
# def to_python(self, value, field):
#
# Path: webtools/formdata/widgets.py
# class Widget(object):
# class InputText(Widget):
# class Textarea(Widget):
# def __init__(self, attrs={}):
# def set_field(self, field):
# def render(self, name, prefixed_name, value):
# def attrs_to_str(self, attrs):
# def __call__(self, name, prefixed_name, value):
# def render(self, name, prefixed_name, value):
# def render(self, name, prefixed_name, value):
. Output only the next line. | 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._validated)
self.assertFalse(form.is_valid())
self.assertIn("field2", form.errors)
def test_simple_validate_03(self):
handler = HandlerMock({"field1": "Hola"})
form = TestForm1(handler)
self.assertNotIn("field1", form._initial)
form.validate()
self.assertTrue(form._validated)
self.assertFalse(form.is_valid())
self.assertIn("field2", form.errors)
self.assertIn("field1", form._initial)
self.assertIn("field1", form.cleaned_data)
class WidgetTests(TestCase):
def setUp(self):
class SampleForm(FormData):
<|code_end|>
. Use current file imports:
from unittest import TestCase
from webtools.formdata.base import FormData
from webtools.formdata.field import Field
from webtools.formdata import data_types as types
from webtools.formdata import widgets
and context (classes, functions, or code) from other files:
# Path: webtools/formdata/base.py
# class FormData(FormDataBase, metaclass=FormDataMeta):
# pass
#
# Path: webtools/formdata/field.py
# 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.required = required
# self.widget = widget
#
# if self.widget:
# if isinstance(self.widget, type):
# self.widget = self.widget()
# assert isinstance(self.widget, Widget), "widget must be a instance of Widget"
#
# def clean(self, name, formdata):
# raw_value = formdata.get_argument(name)
# if raw_value:
# return self.datatype.to_python(raw_value, self)
# else:
# if not self.required:
# return self.default
# raise ValidateError("this field is required")
#
# Path: webtools/formdata/data_types.py
# class Type(object):
# class Integer(Type):
# class Unicode(Type):
# class MultipleUnicode(Type):
# class MultipleInteger(Type):
# class Date(Type):
# class DateTime(Type):
# def to_python(self, value, field):
# def from_python(self, value):
# def to_python(self, value, field):
# def to_python(self, value, field):
# def to_python(self, value, field):
#
# Path: webtools/formdata/widgets.py
# class Widget(object):
# class InputText(Widget):
# class Textarea(Widget):
# def __init__(self, attrs={}):
# def set_field(self, field):
# def render(self, name, prefixed_name, value):
# def attrs_to_str(self, attrs):
# def __call__(self, name, prefixed_name, value):
# def render(self, name, prefixed_name, value):
# def render(self, name, prefixed_name, value):
. Output only the next line. | 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(self):
self.handler = ResponseMock()
self.handler.application = self.app
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", {"name": "foo"})
self.assertEqual(result, "Hello foo")
class TimezoneModuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = Application(TestOverwriteSettings())
<|code_end|>
with the help of current file imports:
from webtools.template.handlers import ResponseHandlerMixin
from webtools.handlers.i18n import TimezoneMixin, I18nMixin
from webtools.handlers.base import BaseHandler
from webtools.database import Base
from webtools.utils import timezone
from ..settings import TestOverwriteSettings
from unittest import TestCase
from webtools.application import Application
from webtools.application import Application
from webtools.application import Application
import os.path, io
import unittest
import datetime
import pytz
and context from other files:
# Path: webtools/template/handlers.py
# class ResponseHandlerMixin(object):
# def get_template(self, template_name):
# return self.application.jinja_env.get_template(template_name)
#
# def get_template_from_string(self, data):
# return self.application.jinja_env.from_string(data)
#
# def render(self, template, context={}):
# if not isinstance(template, jinja2.Template):
# template = self.get_template(template)
# context = self._populate_context_form_ctxprocessors(context)
#
# for chuck in template.generate(context):
# self.write(chuck)
#
# def render_to_string(self, template, context={}):
# if not isinstance(template, jinja2.Template):
# template = self.get_template(template)
# context = self._populate_context_form_ctxprocessors(context)
# return template.render(context)
#
# def _populate_context_form_ctxprocessors(self, context):
# ctx = {}
# ctx.update(context)
#
# for ctx_processor in self.application.context_processors:
# ctx.update(ctx_processor(self))
#
# ctx.update({
# "handler": self,
# "application": self.application.conf,
# "config": self.application.conf,
# })
#
# return ctx
#
# Path: webtools/handlers/i18n.py
# class TimezoneMixin(object):
# @property
# def timezone(self):
# if not hasattr(self, "_timezone"):
# self._timezone = self.get_user_timezone()
# return self._timezone
#
# def get_user_timezone(self):
# if "webtools_timezone" in self.session:
# return get_timezone(self.session["webtools_timezone"])
# return get_timezone(self.application.conf.DEFAULT_TZ)
#
# def activate_timezone(self, timezone_name):
# self.session["webtools_timezone"] = timezone_name
# self._timezone = get_timezone(timezone_name)
#
# class I18nMixin(object):
# def get_browser_locale(self, default=None):
# """
# Overwrite default behavior with correct
# setting the default language.
# """
# 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["webtools_locale"])
# return None
#
# def _(self, message, plural_message=None, count=None):
# return self.locale.translate(message, plural_message=plural_message, count=count)
#
# def activate_locale(self, locale_name):
# """
# Activate a specific locale for current user.
# """
# self.session["webtools_locale"] = locale_name
# self._locale = locale.get(locale_name)
#
# Path: webtools/handlers/base.py
# class BaseHandler(tornado.web.RequestHandler):
# @property
# def db(self):
# return self.application.db
#
# @property
# def session(self):
# return self.application.session_engine
#
# def on_finish(self):
# if self.session and self.session.is_modified:
# self.session.save()
#
# super(BaseHandler, self).on_finish()
#
# Path: webtools/database.py
#
# Path: webtools/utils/timezone.py
# def get_default_timezone_name(application=None):
# def get_default_timezone(application):
# def as_localtime(value, timezone):
# def get_timezone(name):
# def make_aware(value, timezone):
# def make_naive(value, timezone):
#
# Path: tests/settings.py
# class TestOverwriteSettings(Settings):
# SQLALCHEMY_ENGINE_URL = "sqlite://"
# AUTHENTICATION_BACKENDS = ["webtools.auth.backends.DatabaseAuthenticationBackend"]
#
# JINJA2_TEMPLATE_DIRS = [
# os.path.join(CURRENT_PATH, "template")
# ]
# INSTALLED_MODULES = [
# "tests",
# ]
#
# COMMANDS = [
# "webtools.management.commands.runserver.RunserverCommand",
# ]
#
# I18N = True
#
# I18N_DIRECTORIES = [
# os.path.join(CURRENT_PATH, "locale"),
# ]
, which may contain function names, class names, or code. Output only the next line. | 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", {"name": "foo"})
self.assertEqual(result, "Hello foo")
class TimezoneModuleTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = Application(TestOverwriteSettings())
Base.metadata.create_all(cls.app.engine)
def setUp(self):
self.handler = ResponseMock()
self.handler.application = self.app
def tearDown(self):
self.handler.session.flush()
def test_activate(self):
self.handler.activate_locale("America/Los_Angeles")
self.assertIn("webtools_locale", self.handler.session)
self.assertEqual("America/Los_Angeles", self.handler.session["webtools_locale"])
def test_as_localtime(self):
<|code_end|>
. Use current file imports:
from webtools.template.handlers import ResponseHandlerMixin
from webtools.handlers.i18n import TimezoneMixin, I18nMixin
from webtools.handlers.base import BaseHandler
from webtools.database import Base
from webtools.utils import timezone
from ..settings import TestOverwriteSettings
from unittest import TestCase
from webtools.application import Application
from webtools.application import Application
from webtools.application import Application
import os.path, io
import unittest
import datetime
import pytz
and context (classes, functions, or code) from other files:
# Path: webtools/template/handlers.py
# class ResponseHandlerMixin(object):
# def get_template(self, template_name):
# return self.application.jinja_env.get_template(template_name)
#
# def get_template_from_string(self, data):
# return self.application.jinja_env.from_string(data)
#
# def render(self, template, context={}):
# if not isinstance(template, jinja2.Template):
# template = self.get_template(template)
# context = self._populate_context_form_ctxprocessors(context)
#
# for chuck in template.generate(context):
# self.write(chuck)
#
# def render_to_string(self, template, context={}):
# if not isinstance(template, jinja2.Template):
# template = self.get_template(template)
# context = self._populate_context_form_ctxprocessors(context)
# return template.render(context)
#
# def _populate_context_form_ctxprocessors(self, context):
# ctx = {}
# ctx.update(context)
#
# for ctx_processor in self.application.context_processors:
# ctx.update(ctx_processor(self))
#
# ctx.update({
# "handler": self,
# "application": self.application.conf,
# "config": self.application.conf,
# })
#
# return ctx
#
# Path: webtools/handlers/i18n.py
# class TimezoneMixin(object):
# @property
# def timezone(self):
# if not hasattr(self, "_timezone"):
# self._timezone = self.get_user_timezone()
# return self._timezone
#
# def get_user_timezone(self):
# if "webtools_timezone" in self.session:
# return get_timezone(self.session["webtools_timezone"])
# return get_timezone(self.application.conf.DEFAULT_TZ)
#
# def activate_timezone(self, timezone_name):
# self.session["webtools_timezone"] = timezone_name
# self._timezone = get_timezone(timezone_name)
#
# class I18nMixin(object):
# def get_browser_locale(self, default=None):
# """
# Overwrite default behavior with correct
# setting the default language.
# """
# 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["webtools_locale"])
# return None
#
# def _(self, message, plural_message=None, count=None):
# return self.locale.translate(message, plural_message=plural_message, count=count)
#
# def activate_locale(self, locale_name):
# """
# Activate a specific locale for current user.
# """
# self.session["webtools_locale"] = locale_name
# self._locale = locale.get(locale_name)
#
# Path: webtools/handlers/base.py
# class BaseHandler(tornado.web.RequestHandler):
# @property
# def db(self):
# return self.application.db
#
# @property
# def session(self):
# return self.application.session_engine
#
# def on_finish(self):
# if self.session and self.session.is_modified:
# self.session.save()
#
# super(BaseHandler, self).on_finish()
#
# Path: webtools/database.py
#
# Path: webtools/utils/timezone.py
# def get_default_timezone_name(application=None):
# def get_default_timezone(application):
# def as_localtime(value, timezone):
# def get_timezone(name):
# def make_aware(value, timezone):
# def make_naive(value, timezone):
#
# Path: tests/settings.py
# class TestOverwriteSettings(Settings):
# SQLALCHEMY_ENGINE_URL = "sqlite://"
# AUTHENTICATION_BACKENDS = ["webtools.auth.backends.DatabaseAuthenticationBackend"]
#
# JINJA2_TEMPLATE_DIRS = [
# os.path.join(CURRENT_PATH, "template")
# ]
# INSTALLED_MODULES = [
# "tests",
# ]
#
# COMMANDS = [
# "webtools.management.commands.runserver.RunserverCommand",
# ]
#
# I18N = True
#
# I18N_DIRECTORIES = [
# os.path.join(CURRENT_PATH, "locale"),
# ]
. Output only the next line. | 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_user(self):
return None
class DefaultTemplateTests(TestCase):
@classmethod
def setUpClass(cls):
<|code_end|>
using the current file's imports:
from webtools.template.handlers import ResponseHandlerMixin
from webtools.handlers.i18n import TimezoneMixin, I18nMixin
from webtools.handlers.base import BaseHandler
from webtools.database import Base
from webtools.utils import timezone
from ..settings import TestOverwriteSettings
from unittest import TestCase
from webtools.application import Application
from webtools.application import Application
from webtools.application import Application
import os.path, io
import unittest
import datetime
import pytz
and any relevant context from other files:
# Path: webtools/template/handlers.py
# class ResponseHandlerMixin(object):
# def get_template(self, template_name):
# return self.application.jinja_env.get_template(template_name)
#
# def get_template_from_string(self, data):
# return self.application.jinja_env.from_string(data)
#
# def render(self, template, context={}):
# if not isinstance(template, jinja2.Template):
# template = self.get_template(template)
# context = self._populate_context_form_ctxprocessors(context)
#
# for chuck in template.generate(context):
# self.write(chuck)
#
# def render_to_string(self, template, context={}):
# if not isinstance(template, jinja2.Template):
# template = self.get_template(template)
# context = self._populate_context_form_ctxprocessors(context)
# return template.render(context)
#
# def _populate_context_form_ctxprocessors(self, context):
# ctx = {}
# ctx.update(context)
#
# for ctx_processor in self.application.context_processors:
# ctx.update(ctx_processor(self))
#
# ctx.update({
# "handler": self,
# "application": self.application.conf,
# "config": self.application.conf,
# })
#
# return ctx
#
# Path: webtools/handlers/i18n.py
# class TimezoneMixin(object):
# @property
# def timezone(self):
# if not hasattr(self, "_timezone"):
# self._timezone = self.get_user_timezone()
# return self._timezone
#
# def get_user_timezone(self):
# if "webtools_timezone" in self.session:
# return get_timezone(self.session["webtools_timezone"])
# return get_timezone(self.application.conf.DEFAULT_TZ)
#
# def activate_timezone(self, timezone_name):
# self.session["webtools_timezone"] = timezone_name
# self._timezone = get_timezone(timezone_name)
#
# class I18nMixin(object):
# def get_browser_locale(self, default=None):
# """
# Overwrite default behavior with correct
# setting the default language.
# """
# 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["webtools_locale"])
# return None
#
# def _(self, message, plural_message=None, count=None):
# return self.locale.translate(message, plural_message=plural_message, count=count)
#
# def activate_locale(self, locale_name):
# """
# Activate a specific locale for current user.
# """
# self.session["webtools_locale"] = locale_name
# self._locale = locale.get(locale_name)
#
# Path: webtools/handlers/base.py
# class BaseHandler(tornado.web.RequestHandler):
# @property
# def db(self):
# return self.application.db
#
# @property
# def session(self):
# return self.application.session_engine
#
# def on_finish(self):
# if self.session and self.session.is_modified:
# self.session.save()
#
# super(BaseHandler, self).on_finish()
#
# Path: webtools/database.py
#
# Path: webtools/utils/timezone.py
# def get_default_timezone_name(application=None):
# def get_default_timezone(application):
# def as_localtime(value, timezone):
# def get_timezone(name):
# def make_aware(value, timezone):
# def make_naive(value, timezone):
#
# Path: tests/settings.py
# class TestOverwriteSettings(Settings):
# SQLALCHEMY_ENGINE_URL = "sqlite://"
# AUTHENTICATION_BACKENDS = ["webtools.auth.backends.DatabaseAuthenticationBackend"]
#
# JINJA2_TEMPLATE_DIRS = [
# os.path.join(CURRENT_PATH, "template")
# ]
# INSTALLED_MODULES = [
# "tests",
# ]
#
# COMMANDS = [
# "webtools.management.commands.runserver.RunserverCommand",
# ]
#
# I18N = True
#
# I18N_DIRECTORIES = [
# os.path.join(CURRENT_PATH, "locale"),
# ]
. Output only the next line. | 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):
if len(value) != 1:
<|code_end|>
. Use current file imports:
(from .exceptions import ValidateError)
and context including class names, function names, or small code snippets from other files:
# Path: webtools/formdata/exceptions.py
# class ValidateError(Exception):
# pass
. Output only the next line. | 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
def get_current_user(self):
if hasattr(self, "_user"):
return self._user
if "user_id" in self.session:
<|code_end|>
using the current file's imports:
from .models import User
and any relevant context from other files:
# Path: webtools/auth/models.py
# 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(Unicode(200), nullable=False)
# email = Column(Unicode(200), nullable=False)
# password = Column(String(200), nullable=False)
#
# def __repr__(self):
# return "<User {0}>".format(self.id)
#
# def set_password(self, password):
# self.password = make_password(password)
#
# def check_password(self, password):
# return check_password(password, self.password)
. Output only the next line. | 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._load_library()
data = bcrypt.hashpw(password, salt)
return "%s$%s" % (self.algorithm, data)
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
bcrypt = self._load_library()
return constant_time_compare(data, bcrypt.hashpw(password, data))
class SHA1PasswordHasher(BasePasswordHasher):
"""
The SHA1 password hashing algorithm (not recommended)
"""
algorithm = "sha1"
def encode(self, password, salt):
assert password
assert salt and '$' not in salt
<|code_end|>
, predict the next line using imports from the current file:
from webtools.utils.encoding import smart_bytes
from webtools.utils.crypto import pbkdf2, constant_time_compare, get_random_string
from webtools.application import get_app
import base64
import hashlib
import importlib
and context including class names, function names, and sometimes code from other files:
# Path: webtools/utils/encoding.py
# def smart_bytes(value, encoding='utf-8', errors='strict'):
# if isinstance(value, bytes):
# if encoding == 'utf-8':
# return value
#
# return value.decode('utf-8', errors).encode(encoding, errors)
#
# if not isinstance(value, str):
# value = str(value)
#
# return value.encode(encoding, errors)
#
# Path: webtools/utils/crypto.py
# def pbkdf2(password, salt, iterations, dklen=0, digest=None):
# """
# Implements PBKDF2 as defined in RFC 2898, section 5.2
#
# HMAC+SHA256 is used as the default pseudo random function.
#
# Right now 10,000 iterations is the recommended default which takes
# 100ms on a 2.2Ghz Core 2 Duo. This is probably the bare minimum
# for security given 1000 iterations was recommended in 2001. This
# code is very well optimized for CPython and is only four times
# slower than openssl's implementation.
# """
# assert iterations > 0
# if not digest:
# digest = hashlib.sha256
# password = smart_bytes(password)
# salt = smart_bytes(salt)
# hlen = digest().digest_size
# if not dklen:
# dklen = hlen
# if dklen > (2 ** 32 - 1) * hlen:
# raise OverflowError('dklen too big')
# l = -(-dklen // hlen)
# r = dklen - (l - 1) * hlen
#
# hex_format_string = "%%0%ix" % (hlen * 2)
#
# def F(i):
# def U():
# u = salt + struct.pack(b'>I', i)
# for j in range(int(iterations)):
# u = _fast_hmac(password, u, digest).digest()
# yield _bin_to_long(u)
# return _long_to_bin(reduce(operator.xor, U()), hex_format_string)
#
# T = [F(x) for x in range(1, l + 1)]
# return b''.join(T[:-1]) + T[-1][:r]
#
# def constant_time_compare(val1, val2):
# """
# Returns True if the two strings are equal, False otherwise.
#
# The time taken is independent of the number of characters that match.
# """
# if len(val1) != len(val2):
# return False
# result = 0
# for x, y in zip(val1, val2):
# result |= ord(x) ^ ord(y)
# return result == 0
#
# def get_random_string(length=12,
# allowed_chars='abcdefghijklmnopqrstuvwxyz'
# 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
# """
# Returns a securely generated random string.
#
# The default length of 12 with the a-z, A-Z, 0-9 character set returns
# a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
# """
# if not using_sysrandom:
# # This is ugly, and a hack, but it makes things better than
# # the alternative of predictability. This re-seeds the PRNG
# # using a value that is hard for an attacker to predict, every
# # time a random string is required. This may change the
# # properties of the chosen random sequence slightly, but this
# # is better than absolute predictability.
# random.seed(
# hashlib.sha256(
# "%s%s%s" % (
# random.getstate(),
# time.time(),
# settings.SECRET_KEY)
# ).digest())
# return ''.join([random.choice(allowed_chars) for i in range(length)])
. Output only the next line. | 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 NotImplementedError()
class PBKDF2PasswordHasher(BasePasswordHasher):
"""
Secure password hashing using the PBKDF2 algorithm (recommended)
Configured to use PBKDF2 + HMAC + SHA256 with 10000 iterations.
The result is a 64 byte binary string. Iterations may be changed
safely but you must rename the algorithm if you change SHA256.
"""
algorithm = "pbkdf2_sha256"
iterations = 10000
digest = hashlib.sha256
def encode(self, password, salt, iterations=None):
assert password
assert salt and '$' not in salt
if not iterations:
iterations = self.iterations
<|code_end|>
, determine the next line of code. You have imports:
from webtools.utils.encoding import smart_bytes
from webtools.utils.crypto import pbkdf2, constant_time_compare, get_random_string
from webtools.application import get_app
import base64
import hashlib
import importlib
and context (class names, function names, or code) available:
# Path: webtools/utils/encoding.py
# def smart_bytes(value, encoding='utf-8', errors='strict'):
# if isinstance(value, bytes):
# if encoding == 'utf-8':
# return value
#
# return value.decode('utf-8', errors).encode(encoding, errors)
#
# if not isinstance(value, str):
# value = str(value)
#
# return value.encode(encoding, errors)
#
# Path: webtools/utils/crypto.py
# def pbkdf2(password, salt, iterations, dklen=0, digest=None):
# """
# Implements PBKDF2 as defined in RFC 2898, section 5.2
#
# HMAC+SHA256 is used as the default pseudo random function.
#
# Right now 10,000 iterations is the recommended default which takes
# 100ms on a 2.2Ghz Core 2 Duo. This is probably the bare minimum
# for security given 1000 iterations was recommended in 2001. This
# code is very well optimized for CPython and is only four times
# slower than openssl's implementation.
# """
# assert iterations > 0
# if not digest:
# digest = hashlib.sha256
# password = smart_bytes(password)
# salt = smart_bytes(salt)
# hlen = digest().digest_size
# if not dklen:
# dklen = hlen
# if dklen > (2 ** 32 - 1) * hlen:
# raise OverflowError('dklen too big')
# l = -(-dklen // hlen)
# r = dklen - (l - 1) * hlen
#
# hex_format_string = "%%0%ix" % (hlen * 2)
#
# def F(i):
# def U():
# u = salt + struct.pack(b'>I', i)
# for j in range(int(iterations)):
# u = _fast_hmac(password, u, digest).digest()
# yield _bin_to_long(u)
# return _long_to_bin(reduce(operator.xor, U()), hex_format_string)
#
# T = [F(x) for x in range(1, l + 1)]
# return b''.join(T[:-1]) + T[-1][:r]
#
# def constant_time_compare(val1, val2):
# """
# Returns True if the two strings are equal, False otherwise.
#
# The time taken is independent of the number of characters that match.
# """
# if len(val1) != len(val2):
# return False
# result = 0
# for x, y in zip(val1, val2):
# result |= ord(x) ^ ord(y)
# return result == 0
#
# def get_random_string(length=12,
# allowed_chars='abcdefghijklmnopqrstuvwxyz'
# 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
# """
# Returns a securely generated random string.
#
# The default length of 12 with the a-z, A-Z, 0-9 character set returns
# a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
# """
# if not using_sysrandom:
# # This is ugly, and a hack, but it makes things better than
# # the alternative of predictability. This re-seeds the PRNG
# # using a value that is hard for an attacker to predict, every
# # time a random string is required. This may change the
# # properties of the chosen random sequence slightly, but this
# # is better than absolute predictability.
# random.seed(
# hashlib.sha256(
# "%s%s%s" % (
# random.getstate(),
# time.time(),
# settings.SECRET_KEY)
# ).digest())
# return ''.join([random.choice(allowed_chars) for i in range(length)])
. Output only the next line. | 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 iterations.
The result is a 64 byte binary string. Iterations may be changed
safely but you must rename the algorithm if you change SHA256.
"""
algorithm = "pbkdf2_sha256"
iterations = 10000
digest = hashlib.sha256
def encode(self, password, salt, iterations=None):
assert password
assert salt and '$' not in salt
if not iterations:
iterations = self.iterations
hash = pbkdf2(password, salt, iterations, digest=self.digest)
hash = base64.b64encode(hash).decode('ascii').strip()
return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
def verify(self, password, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, salt, int(iterations))
<|code_end|>
. Use current file imports:
(from webtools.utils.encoding import smart_bytes
from webtools.utils.crypto import pbkdf2, constant_time_compare, get_random_string
from webtools.application import get_app
import base64
import hashlib
import importlib)
and context including class names, function names, or small code snippets from other files:
# Path: webtools/utils/encoding.py
# def smart_bytes(value, encoding='utf-8', errors='strict'):
# if isinstance(value, bytes):
# if encoding == 'utf-8':
# return value
#
# return value.decode('utf-8', errors).encode(encoding, errors)
#
# if not isinstance(value, str):
# value = str(value)
#
# return value.encode(encoding, errors)
#
# Path: webtools/utils/crypto.py
# def pbkdf2(password, salt, iterations, dklen=0, digest=None):
# """
# Implements PBKDF2 as defined in RFC 2898, section 5.2
#
# HMAC+SHA256 is used as the default pseudo random function.
#
# Right now 10,000 iterations is the recommended default which takes
# 100ms on a 2.2Ghz Core 2 Duo. This is probably the bare minimum
# for security given 1000 iterations was recommended in 2001. This
# code is very well optimized for CPython and is only four times
# slower than openssl's implementation.
# """
# assert iterations > 0
# if not digest:
# digest = hashlib.sha256
# password = smart_bytes(password)
# salt = smart_bytes(salt)
# hlen = digest().digest_size
# if not dklen:
# dklen = hlen
# if dklen > (2 ** 32 - 1) * hlen:
# raise OverflowError('dklen too big')
# l = -(-dklen // hlen)
# r = dklen - (l - 1) * hlen
#
# hex_format_string = "%%0%ix" % (hlen * 2)
#
# def F(i):
# def U():
# u = salt + struct.pack(b'>I', i)
# for j in range(int(iterations)):
# u = _fast_hmac(password, u, digest).digest()
# yield _bin_to_long(u)
# return _long_to_bin(reduce(operator.xor, U()), hex_format_string)
#
# T = [F(x) for x in range(1, l + 1)]
# return b''.join(T[:-1]) + T[-1][:r]
#
# def constant_time_compare(val1, val2):
# """
# Returns True if the two strings are equal, False otherwise.
#
# The time taken is independent of the number of characters that match.
# """
# if len(val1) != len(val2):
# return False
# result = 0
# for x, y in zip(val1, val2):
# result |= ord(x) ^ ord(y)
# return result == 0
#
# def get_random_string(length=12,
# allowed_chars='abcdefghijklmnopqrstuvwxyz'
# 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
# """
# Returns a securely generated random string.
#
# The default length of 12 with the a-z, A-Z, 0-9 character set returns
# a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
# """
# if not using_sysrandom:
# # This is ugly, and a hack, but it makes things better than
# # the alternative of predictability. This re-seeds the PRNG
# # using a value that is hard for an attacker to predict, every
# # time a random string is required. This may change the
# # properties of the chosen random sequence slightly, but this
# # is better than absolute predictability.
# random.seed(
# hashlib.sha256(
# "%s%s%s" % (
# random.getstate(),
# time.time(),
# settings.SECRET_KEY)
# ).digest())
# return ''.join([random.choice(allowed_chars) for i in range(length)])
. Output only the next line. | 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 = None
def _load_library(self):
if self.library is not None:
if isinstance(self.library, (tuple, list)):
name, mod_path = self.library
else:
name = mod_path = self.library
try:
module = importlib.import_module(mod_path)
except ImportError:
raise ValueError("Couldn't load %s password algorithm "
"library" % name)
return module
raise ValueError("Hasher '%s' doesn't specify a library attribute" %
self.__class__)
def salt(self):
"""
Generates a cryptographically secure nonce salt in ascii
"""
<|code_end|>
, predict the next line using imports from the current file:
from webtools.utils.encoding import smart_bytes
from webtools.utils.crypto import pbkdf2, constant_time_compare, get_random_string
from webtools.application import get_app
import base64
import hashlib
import importlib
and context including class names, function names, and sometimes code from other files:
# Path: webtools/utils/encoding.py
# def smart_bytes(value, encoding='utf-8', errors='strict'):
# if isinstance(value, bytes):
# if encoding == 'utf-8':
# return value
#
# return value.decode('utf-8', errors).encode(encoding, errors)
#
# if not isinstance(value, str):
# value = str(value)
#
# return value.encode(encoding, errors)
#
# Path: webtools/utils/crypto.py
# def pbkdf2(password, salt, iterations, dklen=0, digest=None):
# """
# Implements PBKDF2 as defined in RFC 2898, section 5.2
#
# HMAC+SHA256 is used as the default pseudo random function.
#
# Right now 10,000 iterations is the recommended default which takes
# 100ms on a 2.2Ghz Core 2 Duo. This is probably the bare minimum
# for security given 1000 iterations was recommended in 2001. This
# code is very well optimized for CPython and is only four times
# slower than openssl's implementation.
# """
# assert iterations > 0
# if not digest:
# digest = hashlib.sha256
# password = smart_bytes(password)
# salt = smart_bytes(salt)
# hlen = digest().digest_size
# if not dklen:
# dklen = hlen
# if dklen > (2 ** 32 - 1) * hlen:
# raise OverflowError('dklen too big')
# l = -(-dklen // hlen)
# r = dklen - (l - 1) * hlen
#
# hex_format_string = "%%0%ix" % (hlen * 2)
#
# def F(i):
# def U():
# u = salt + struct.pack(b'>I', i)
# for j in range(int(iterations)):
# u = _fast_hmac(password, u, digest).digest()
# yield _bin_to_long(u)
# return _long_to_bin(reduce(operator.xor, U()), hex_format_string)
#
# T = [F(x) for x in range(1, l + 1)]
# return b''.join(T[:-1]) + T[-1][:r]
#
# def constant_time_compare(val1, val2):
# """
# Returns True if the two strings are equal, False otherwise.
#
# The time taken is independent of the number of characters that match.
# """
# if len(val1) != len(val2):
# return False
# result = 0
# for x, y in zip(val1, val2):
# result |= ord(x) ^ ord(y)
# return result == 0
#
# def get_random_string(length=12,
# allowed_chars='abcdefghijklmnopqrstuvwxyz'
# 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
# """
# Returns a securely generated random string.
#
# The default length of 12 with the a-z, A-Z, 0-9 character set returns
# a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
# """
# if not using_sysrandom:
# # This is ugly, and a hack, but it makes things better than
# # the alternative of predictability. This re-seeds the PRNG
# # using a value that is hard for an attacker to predict, every
# # time a random string is required. This may change the
# # properties of the chosen random sequence slightly, but this
# # is better than absolute predictability.
# random.seed(
# hashlib.sha256(
# "%s%s%s" % (
# random.getstate(),
# time.time(),
# settings.SECRET_KEY)
# ).digest())
# return ''.join([random.choice(allowed_chars) for i in range(length)])
. Output only the next line. | 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
from ..settings import TestOverwriteSettings
from webtools.application import Application
and context:
# Path: webtools/database.py
#
# Path: tests/settings.py
# class TestOverwriteSettings(Settings):
# SQLALCHEMY_ENGINE_URL = "sqlite://"
# AUTHENTICATION_BACKENDS = ["webtools.auth.backends.DatabaseAuthenticationBackend"]
#
# JINJA2_TEMPLATE_DIRS = [
# os.path.join(CURRENT_PATH, "template")
# ]
# INSTALLED_MODULES = [
# "tests",
# ]
#
# COMMANDS = [
# "webtools.management.commands.runserver.RunserverCommand",
# ]
#
# I18N = True
#
# I18N_DIRECTORIES = [
# os.path.join(CURRENT_PATH, "locale"),
# ]
which might include code, classes, or functions. Output only the next line. | 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
from webtools.application import Application
and context:
# Path: webtools/database.py
#
# Path: tests/settings.py
# class TestOverwriteSettings(Settings):
# SQLALCHEMY_ENGINE_URL = "sqlite://"
# AUTHENTICATION_BACKENDS = ["webtools.auth.backends.DatabaseAuthenticationBackend"]
#
# JINJA2_TEMPLATE_DIRS = [
# os.path.join(CURRENT_PATH, "template")
# ]
# INSTALLED_MODULES = [
# "tests",
# ]
#
# COMMANDS = [
# "webtools.management.commands.runserver.RunserverCommand",
# ]
#
# I18N = True
#
# I18N_DIRECTORIES = [
# os.path.join(CURRENT_PATH, "locale"),
# ]
which might include code, classes, or functions. Output only the next line. | 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"
" is mandatory!")
app = Application(self.cmdapp.conf)
print("Create theese tables:")
<|code_end|>
, determine the next line of code. You have imports:
from webtools.management.base import Command
from webtools.database import Base
from webtools.application import Application
from webtools.application import Application
and context (class names, function names, or code) available:
# Path: webtools/management/base.py
# class Command(object):
# def __init__(self, cmdapp):
# self.cmdapp = cmdapp
#
# @classmethod
# def get_name(cls):
# name = cls.__name__.lower()
# if name.endswith("command"):
# name = name[:-7]
# elif name.endswith("cmd"):
# name = name[:-3]
# return name
#
# @classmethod
# def get_description(cls):
# doc = inspect.getdoc(cls)
# if not doc:
# return ""
#
# return doc.strip().split("\n")[0]
#
# @classmethod
# def get_parser(cls, root_parser):
# """
# Return an :class:`argparse.ArgumentParser`.
# """
# return root_parser
#
# def take_action(self, parsed_args):
# """
# Override to do something useful.
# """
# raise NotImplementedError
#
# def run(self, parsed_args):
# """
# Invoked by the application when the command is run.
#
# Developers implementing commands should override
# :meth:`take_action`.
#
# 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
#
# Path: webtools/database.py
. Output only the next line. | 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 = bytearray([(x ^ 0x36) for x in range(256)])
def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
"""
if secret is None:
secret = settings.SECRET_KEY
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function and
# SHA1 works nicely.
key = hashlib.sha1((key_salt + secret).encode('utf-8')).digest()
# If len(key_salt + secret) > sha_constructor().block_size, the above
# line is redundant and could be replaced by key = key_salt + secret, since
# the hmac module does the same thing for keys longer than the block size.
# However, we need to ensure that we *always* do this.
<|code_end|>
, generate the next line using the imports in this file:
import hmac
import struct
import hashlib
import binascii
import operator
import time
import random
import warnings
from functools import reduce
from webtools.utils.encoding import smart_bytes
and context (functions, classes, or occasionally code) from other files:
# Path: webtools/utils/encoding.py
# def smart_bytes(value, encoding='utf-8', errors='strict'):
# if isinstance(value, bytes):
# if encoding == 'utf-8':
# return value
#
# return value.decode('utf-8', errors).encode(encoding, errors)
#
# if not isinstance(value, str):
# value = str(value)
#
# return value.encode(encoding, errors)
. Output only the next line. | 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 QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
def test_qpagesetupdialog_exec_():
"""Test qtpy.QtPrintSupport.QPageSetupDialog exec_"""
assert QtPrintSupport.QPageSetupDialog.exec_ is not None
def test_qprintdialog_exec_():
"""Test qtpy.QtPrintSupport.QPrintDialog exec_"""
assert QtPrintSupport.QPrintDialog.exec_ is not None
@pytest.mark.skipif(
<|code_end|>
, generate the next line using the imports in this file:
import sys
import pytest
from qtpy import QtPrintSupport
from qtpy.tests.utils import not_using_conda
and context (functions, classes, or occasionally code) from other files:
# Path: qtpy/QtPrintSupport.py
#
# Path: qtpy/tests/utils.py
# def not_using_conda():
# return os.environ.get('USE_CONDA', 'No') == 'No'
. Output only the next line. | 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 context from other files:
# Path: xpra/xposix/xsettings.py
# class XSettingsManager(object):
# def __init__(self, settings_blob):
# self._selection = ManagerSelection(gtk.gdk.display_get_default(),
# "_XSETTINGS_S0")
# # Technically I suppose ICCCM says we should use FORCE, but it's not
# # like a window manager where you have to wait for the old wm to clean
# # things up before you can do anything... as soon as the selection is
# # gone, the settings are gone. (Also, if we're stealing from
# # ourselves, we probably don't clean up the window properly.)
# self._selection.acquire(self._selection.FORCE_AND_RETURN)
# self._window = self._selection.window()
# self._set_blob_in_place(settings_blob)
#
# # This is factored out as a separate function to make it easier to test
# # XSettingsWatcher:
# def _set_blob_in_place(self, settings_blob):
# prop_set(self._window, "_XSETTINGS_SETTINGS", "xsettings-settings",
# settings_blob)
#
# class XSettingsWatcher(gobject.GObject):
# __gsignals__ = {
# "xsettings-changed": no_arg_signal,
#
# "wimpiggy-property-notify-event": one_arg_signal,
# "wimpiggy-client-message-event": one_arg_signal,
# }
# def __init__(self):
# gobject.GObject.__init__(self)
# self._clipboard = gtk.Clipboard(gtk.gdk.display_get_default(),
# "_XSETTINGS_S0")
# self._current = None
# self._root = self._clipboard.get_display().get_default_screen().get_root_window()
# add_event_receiver(self._root, self)
# self._add_watch()
#
# def _owner(self):
# owner_x = myGetSelectionOwner(self._clipboard, "_XSETTINGS_S0")
# if owner_x == const["XNone"]:
# return None
# try:
# return trap.call(get_pywindow, self._clipboard, owner_x)
# except XError:
# log("X error while fetching owner of XSettings data; ignored")
# return None
#
# def _add_watch(self):
# owner = self._owner()
# if owner is not None:
# add_event_receiver(owner, self)
#
# def do_wimpiggy_client_message_event(self, event):
# if (event.window is self._root
# and event.message_type == "MANAGER"
# and event.data[1] == get_xatom(event.window, "_XSETTINGS_S0")):
# log("XSettings manager changed")
# self._add_watch()
# self.emit("xsettings-changed")
#
# def do_wimpiggy_property_notify_event(self, event):
# if event.atom == "_XSETTINGS_SETTINGS":
# log("XSettings property value changed")
# self.emit("xsettings-changed")
#
# def _get_settings_blob(self):
# owner = self._owner()
# if owner is None:
# return None
# blob = prop_get(owner, "_XSETTINGS_SETTINGS", "xsettings-settings")
# return blob
#
# def get_settings_blob(self):
# log("Fetching current XSettings data")
# try:
# return trap.call(self._get_settings_blob)
# except XError, e:
# log("X error while fetching XSettings data; ignored")
# return None
, which may include functions, classes, or code. Output only the next line. | 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 XSettingsManager, XSettingsWatcher
import gtk
and context (class names, function names, or code) available:
# Path: xpra/xposix/xsettings.py
# class XSettingsManager(object):
# def __init__(self, settings_blob):
# self._selection = ManagerSelection(gtk.gdk.display_get_default(),
# "_XSETTINGS_S0")
# # Technically I suppose ICCCM says we should use FORCE, but it's not
# # like a window manager where you have to wait for the old wm to clean
# # things up before you can do anything... as soon as the selection is
# # gone, the settings are gone. (Also, if we're stealing from
# # ourselves, we probably don't clean up the window properly.)
# self._selection.acquire(self._selection.FORCE_AND_RETURN)
# self._window = self._selection.window()
# self._set_blob_in_place(settings_blob)
#
# # This is factored out as a separate function to make it easier to test
# # XSettingsWatcher:
# def _set_blob_in_place(self, settings_blob):
# prop_set(self._window, "_XSETTINGS_SETTINGS", "xsettings-settings",
# settings_blob)
#
# class XSettingsWatcher(gobject.GObject):
# __gsignals__ = {
# "xsettings-changed": no_arg_signal,
#
# "wimpiggy-property-notify-event": one_arg_signal,
# "wimpiggy-client-message-event": one_arg_signal,
# }
# def __init__(self):
# gobject.GObject.__init__(self)
# self._clipboard = gtk.Clipboard(gtk.gdk.display_get_default(),
# "_XSETTINGS_S0")
# self._current = None
# self._root = self._clipboard.get_display().get_default_screen().get_root_window()
# add_event_receiver(self._root, self)
# self._add_watch()
#
# def _owner(self):
# owner_x = myGetSelectionOwner(self._clipboard, "_XSETTINGS_S0")
# if owner_x == const["XNone"]:
# return None
# try:
# return trap.call(get_pywindow, self._clipboard, owner_x)
# except XError:
# log("X error while fetching owner of XSettings data; ignored")
# return None
#
# def _add_watch(self):
# owner = self._owner()
# if owner is not None:
# add_event_receiver(owner, self)
#
# def do_wimpiggy_client_message_event(self, event):
# if (event.window is self._root
# and event.message_type == "MANAGER"
# and event.data[1] == get_xatom(event.window, "_XSETTINGS_S0")):
# log("XSettings manager changed")
# self._add_watch()
# self.emit("xsettings-changed")
#
# def do_wimpiggy_property_notify_event(self, event):
# if event.atom == "_XSETTINGS_SETTINGS":
# log("XSettings property value changed")
# self.emit("xsettings-changed")
#
# def _get_settings_blob(self):
# owner = self._owner()
# if owner is None:
# return None
# blob = prop_get(owner, "_XSETTINGS_SETTINGS", "xsettings-settings")
# return blob
#
# def get_settings_blob(self):
# log("Fetching current XSettings data")
# try:
# return trap.call(self._get_settings_blob)
# except XError, e:
# log("X error while fetching XSettings data; ignored")
# return None
. Output only the next line. | 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 = PseudoclientWindow(wm)
window.set_resizable(True)
window.set_title("Parti REPL")
scroll = gtk.ScrolledWindow()
scroll.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
<|code_end|>
. Use current file imports:
import gtk
from wimpiggy.pseudoclient import PseudoclientWindow
from parti.addons.ipython_view import IPythonView
and context (classes, functions, or code) from other files:
# Path: wimpiggy/pseudoclient.py
# class PseudoclientWindow(gtk.Window):
# """A gtk.Window that acts like an ordinary client.
#
# All the wm-magic that would normally accrue to a window created within our
# process is removed.
#
# Keyword arguments (notably 'type') are forwarded to
# gtk.Window.__init__.
#
# The reason this is a separate class, as opposed to say a gtk.Window
# factory method on wm, is that this way allows for subclassing."""
#
# def __init__(self, wm, **kwargs):
# gtk.Window.__init__(self, **kwargs)
# wm._make_window_pseudoclient(self)
#
# Path: parti/addons/ipython_view.py
# class IPythonView(ConsoleView, IterableIPShell):
# def __init__(self):
# ConsoleView.__init__(self)
# self.cout = StringIO()
# IterableIPShell.__init__(self, cout=self.cout,cerr=self.cout,
# input_func=self.raw_input)
# self.connect('key_press_event', self.keyPress)
# self.execute()
# self.cout.truncate(0)
# self.showPrompt(self.prompt)
# self.interrupt = False
#
# def raw_input(self, prompt=''):
# if self.interrupt:
# self.interrupt = False
# raise KeyboardInterrupt
# return self.getCurrentLine()
#
# def keyPress(self, widget, event):
# if event.state & gtk.gdk.CONTROL_MASK and event.keyval == 99:
# self.interrupt = True
# self._processLine()
# return True
# elif event.keyval == gtk.keysyms.Return:
# self._processLine()
# return True
# elif event.keyval == gtk.keysyms.Up:
# self.changeLine(self.historyBack())
# return True
# elif event.keyval == gtk.keysyms.Down:
# self.changeLine(self.historyForward())
# return True
# elif event.keyval == gtk.keysyms.Tab:
# if not self.getCurrentLine().strip():
# return False
# completed, possibilities = self.complete(self.getCurrentLine())
# if len(possibilities) > 1:
# slice = self.getCurrentLine()
# self.write('\n')
# for symbol in possibilities:
# self.write(symbol+'\n')
# self.showPrompt(self.prompt)
# self.changeLine(completed or slice)
# return True
#
# def _processLine(self):
# self.history_pos = 0
# self.execute()
# rv = self.cout.getvalue()
# if rv: rv = rv.strip('\n')
# self.showReturned(rv)
# self.cout.truncate(0)
. Output only the next line. | 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, sh_quotemeta(value), var, var))
else:
script.append("%s=%s; export %s\n"
% (var, sh_quotemeta(value), var))
# We ignore failures in cd'ing, b/c it's entirely possible that we were
# started from some temporary directory and all paths are absolute.
script.append("cd %s\n" % sh_quotemeta(starting_dir))
script.append("_XPRA_PYTHON=%s\n" % (sh_quotemeta(sys.executable),))
script.append("_XPRA_SCRIPT=%s\n" % (sh_quotemeta(xpra_file),))
script.append("""
if which "$_XPRA_PYTHON" > /dev/null && [ -e "$_XPRA_SCRIPT" ]; then
# Happypath:
exec "$_XPRA_PYTHON" "$_XPRA_SCRIPT" "$@"
else
cat >&2 <<END
Could not find one or both of '$_XPRA_PYTHON' and '$_XPRA_SCRIPT'
Perhaps your environment has changed since the xpra server was started?
I'll just try executing 'xpra' with current PATH, and hope...
END
exec xpra "$@"
fi
""")
return "".join(script)
def create_unix_domain_socket(display_name, upgrading):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import gobject
import subprocess
import sys
import os
import os.path
import atexit
import signal
import socket
import gtk
import wimpiggy.prop
import gtk
import wimpiggy.prop
import gtk
import xpra.server
from xpra.wait_for_x_server import wait_for_x_server
from xpra.dotxpra import DotXpra, ServerSockInUse
and context:
# Path: xpra/dotxpra.py
# class DotXpra(object):
# def __init__(self, dir=None):
# assert XPRA_LOCAL_SERVERS_SUPPORTED
# if dir is None:
# dir = os.path.expanduser("~/.xpra")
# self._dir = dir
# if not os.path.exists(self._dir):
# os.mkdir(dir, 0700)
# self._prefix = "%s-" % (socket.gethostname(),)
#
# def dir(self):
# return self._dir
#
# def _normalize_local_display_name(self, local_display_name):
# if not local_display_name.startswith(":"):
# local_display_name = ":" + local_display_name
# if "." in local_display_name:
# local_display_name = local_display_name[:local_display_name.rindex(".")]
# assert local_display_name.startswith(":")
# for char in local_display_name[1:]:
# assert char in "0123456789"
# return local_display_name
#
# def socket_path(self, local_display_name):
# local_display_name = self._normalize_local_display_name(local_display_name)
# return os.path.join(self._dir, self._prefix + local_display_name[1:])
#
# LIVE = "LIVE"
# DEAD = "DEAD"
# UNKNOWN = "UNKNOWN"
# def server_state(self, local_display_name):
# path = self.socket_path(local_display_name)
# if not os.path.exists(path):
# return self.DEAD
# sock = socket.socket(socket.AF_UNIX)
# sock.settimeout(5)
# try:
# sock.connect(path)
# except socket.error, e:
# err = e.args[0]
# if err in (errno.ECONNREFUSED, errno.ENOENT):
# return self.DEAD
# else:
# sock.close()
# return self.LIVE
# return self.UNKNOWN
#
# # Same as socket_path, but preps for the server:
# def server_socket_path(self, local_display_name, clobber):
# if not clobber:
# state = self.server_state(local_display_name)
# if state is not self.DEAD:
# raise ServerSockInUse, (state, local_display_name)
# path = self.socket_path(local_display_name)
# if os.path.exists(path):
# os.unlink(path)
# return path
#
# def sockets(self):
# results = []
# base = os.path.join(self._dir, self._prefix)
# potential_sockets = glob.glob(base + "*")
# for path in potential_sockets:
# if stat.S_ISSOCK(os.stat(path).st_mode):
# local_display = ":" + path[len(base):]
# state = self.server_state(local_display)
# results.append((state, local_display))
# return results
#
# class ServerSockInUse(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | 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", "upgrade")
upgrading = (mode == "upgrade")
dotxpra = DotXpra()
# This used to be given a display-specific name, but now we give it a
# single fixed name and if multiple servers are started then the last one
# will clobber the rest. This isn't great, but the tradeoff is that it
# makes it possible to use bare 'ssh:hostname' display names and
# autodiscover the proper numeric display name when only one xpra server
# is running on the remote host. Might need to revisit this later if
# people run into problems or autodiscovery turns out to be less useful
# than expected.
scriptpath = os.path.join(dotxpra.dir(), "run-xpra")
# Save the starting dir now, because we'll lose track of it when we
# daemonize:
starting_dir = os.getcwd()
# Daemonize:
if opts.daemon:
try:
logpath = dotxpra.server_socket_path(display_name, upgrading) + ".log"
<|code_end|>
, generate the next line using the imports in this file:
import gobject
import subprocess
import sys
import os
import os.path
import atexit
import signal
import socket
import gtk
import wimpiggy.prop
import gtk
import wimpiggy.prop
import gtk
import xpra.server
from xpra.wait_for_x_server import wait_for_x_server
from xpra.dotxpra import DotXpra, ServerSockInUse
and context (functions, classes, or occasionally code) from other files:
# Path: xpra/dotxpra.py
# class DotXpra(object):
# def __init__(self, dir=None):
# assert XPRA_LOCAL_SERVERS_SUPPORTED
# if dir is None:
# dir = os.path.expanduser("~/.xpra")
# self._dir = dir
# if not os.path.exists(self._dir):
# os.mkdir(dir, 0700)
# self._prefix = "%s-" % (socket.gethostname(),)
#
# def dir(self):
# return self._dir
#
# def _normalize_local_display_name(self, local_display_name):
# if not local_display_name.startswith(":"):
# local_display_name = ":" + local_display_name
# if "." in local_display_name:
# local_display_name = local_display_name[:local_display_name.rindex(".")]
# assert local_display_name.startswith(":")
# for char in local_display_name[1:]:
# assert char in "0123456789"
# return local_display_name
#
# def socket_path(self, local_display_name):
# local_display_name = self._normalize_local_display_name(local_display_name)
# return os.path.join(self._dir, self._prefix + local_display_name[1:])
#
# LIVE = "LIVE"
# DEAD = "DEAD"
# UNKNOWN = "UNKNOWN"
# def server_state(self, local_display_name):
# path = self.socket_path(local_display_name)
# if not os.path.exists(path):
# return self.DEAD
# sock = socket.socket(socket.AF_UNIX)
# sock.settimeout(5)
# try:
# sock.connect(path)
# except socket.error, e:
# err = e.args[0]
# if err in (errno.ECONNREFUSED, errno.ENOENT):
# return self.DEAD
# else:
# sock.close()
# return self.LIVE
# return self.UNKNOWN
#
# # Same as socket_path, but preps for the server:
# def server_socket_path(self, local_display_name, clobber):
# if not clobber:
# state = self.server_state(local_display_name)
# if state is not self.DEAD:
# raise ServerSockInUse, (state, local_display_name)
# path = self.socket_path(local_display_name)
# if os.path.exists(path):
# os.unlink(path)
# return path
#
# def sockets(self):
# results = []
# base = os.path.join(self._dir, self._prefix)
# potential_sockets = glob.glob(base + "*")
# for path in potential_sockets:
# if stat.S_ISSOCK(os.stat(path).st_mode):
# local_display = ":" + path[len(base):]
# state = self.server_state(local_display)
# results.append((state, local_display))
# return results
#
# class ServerSockInUse(Exception):
# pass
. Output only the next line. | 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_acquisition_stealing(self):
d1 = self.clone_display()
d2 = self.clone_display()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from wimpiggy.test import *
from wimpiggy.selection import ManagerSelection, AlreadyOwned
import wimpiggy.lowlevel
import struct
and context:
# Path: wimpiggy/selection.py
# class ManagerSelection(gobject.GObject):
# __gsignals__ = {
# "selection-lost": no_arg_signal,
#
# "wimpiggy-destroy-event": one_arg_signal,
# }
#
# def __init__(self, display, selection):
# gobject.GObject.__init__(self)
# self.atom = selection
# self.clipboard = gtk.Clipboard(display, selection)
# self._xwindow = None
#
# def _owner(self):
# return myGetSelectionOwner(self.clipboard, self.atom)
#
# def owned(self):
# "Returns True if someone owns the given selection."
# return self._owner() != const["XNone"]
#
# # If the selection is already owned, then raise AlreadyOwned rather
# # than stealing it.
# IF_UNOWNED = "if_unowned"
# # If the selection is already owned, then steal it, and then block until
# # the previous owner has signaled that they are done cleaning up.
# FORCE = "force"
# # If the selection is already owned, then steal it and return immediately.
# # Created for the use of tests.
# FORCE_AND_RETURN = "force_and_return"
# def acquire(self, when):
# old_owner = self._owner()
# if when is self.IF_UNOWNED and old_owner != const["XNone"]:
# raise AlreadyOwned
#
# self.clipboard.set_with_data([("VERSION", 0, 0)],
# self._get,
# self._clear,
# None)
#
# # Having acquired the selection, we have to announce our existence
# # (ICCCM 2.8, still). The details here probably don't matter too
# # much; I've never heard of an app that cares about these messages,
# # and metacity actually gets the format wrong in several ways (no
# # MANAGER or owner_window atoms). But might as well get it as right
# # as possible.
#
# # To announce our existence, we need:
# # -- the timestamp we arrived at
# # -- the manager selection atom
# # -- the window that registered the selection
# # Of course, because Gtk is doing so much magic for us, we have to do
# # some weird tricks to get at these.
#
# # Ask ourselves when we acquired the selection:
# ts_data = self.clipboard.wait_for_contents("TIMESTAMP").data
# ts_num = unpack("@i", ts_data[:4])[0]
# # Calculate the X atom for this selection:
# selection_xatom = get_xatom(self.clipboard, self.atom)
# # Ask X what window we used:
# self._xwindow = myGetSelectionOwner(self.clipboard, self.atom)
#
# root = self.clipboard.get_display().get_default_screen().get_root_window()
# sendClientMessage(root, False, const["StructureNotifyMask"],
# "MANAGER",
# ts_num, selection_xatom, self._xwindow, 0, 0)
#
# if old_owner != const["XNone"] and when is self.FORCE:
# # Block in a recursive mainloop until the previous owner has
# # cleared out.
# def getwin():
# window = get_pywindow(self.clipboard, old_owner)
# window.set_events(window.get_events() | gtk.gdk.STRUCTURE_MASK)
# return window
# try:
# window = trap.call(getwin)
# log("got window")
# except XError:
# log("Previous owner is already gone, not blocking")
# else:
# log("Waiting for previous owner to exit...")
# add_event_receiver(window, self)
# gtk.main()
# log("...they did.")
#
# def do_wimpiggy_destroy_event(self, event):
# remove_event_receiver(event.window, self)
# gtk.main_quit()
#
# def _get(self, clipboard, outdata, which, userdata):
# # We are compliant with ICCCM version 2.0 (see section 4.3)
# outdata.set("INTEGER", 32, pack("@ii", 2, 0))
#
# def _clear(self, clipboard, userdata):
# self._xwindow = None
# self.emit("selection-lost")
#
# def window(self):
# if self._xwindow is None:
# return None
# return get_pywindow(self.clipboard, self._xwindow)
#
# class AlreadyOwned(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | 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):
def test_acquisition_stealing(self):
d1 = self.clone_display()
d2 = self.clone_display()
m1 = ManagerSelection(d1, "WM_S0")
m2 = ManagerSelection(d2, "WM_S0")
selection_lost_fired = {m1: False, m2: False}
def cb(manager):
selection_lost_fired[manager] = True
m1.connect("selection-lost", cb)
m2.connect("selection-lost", cb)
assert not m1.owned()
assert not m2.owned()
m1.acquire(m1.IF_UNOWNED)
assert m1.owned()
assert m2.owned()
<|code_end|>
. Use current file imports:
(from wimpiggy.test import *
from wimpiggy.selection import ManagerSelection, AlreadyOwned
import wimpiggy.lowlevel
import struct)
and context including class names, function names, or small code snippets from other files:
# Path: wimpiggy/selection.py
# class ManagerSelection(gobject.GObject):
# __gsignals__ = {
# "selection-lost": no_arg_signal,
#
# "wimpiggy-destroy-event": one_arg_signal,
# }
#
# def __init__(self, display, selection):
# gobject.GObject.__init__(self)
# self.atom = selection
# self.clipboard = gtk.Clipboard(display, selection)
# self._xwindow = None
#
# def _owner(self):
# return myGetSelectionOwner(self.clipboard, self.atom)
#
# def owned(self):
# "Returns True if someone owns the given selection."
# return self._owner() != const["XNone"]
#
# # If the selection is already owned, then raise AlreadyOwned rather
# # than stealing it.
# IF_UNOWNED = "if_unowned"
# # If the selection is already owned, then steal it, and then block until
# # the previous owner has signaled that they are done cleaning up.
# FORCE = "force"
# # If the selection is already owned, then steal it and return immediately.
# # Created for the use of tests.
# FORCE_AND_RETURN = "force_and_return"
# def acquire(self, when):
# old_owner = self._owner()
# if when is self.IF_UNOWNED and old_owner != const["XNone"]:
# raise AlreadyOwned
#
# self.clipboard.set_with_data([("VERSION", 0, 0)],
# self._get,
# self._clear,
# None)
#
# # Having acquired the selection, we have to announce our existence
# # (ICCCM 2.8, still). The details here probably don't matter too
# # much; I've never heard of an app that cares about these messages,
# # and metacity actually gets the format wrong in several ways (no
# # MANAGER or owner_window atoms). But might as well get it as right
# # as possible.
#
# # To announce our existence, we need:
# # -- the timestamp we arrived at
# # -- the manager selection atom
# # -- the window that registered the selection
# # Of course, because Gtk is doing so much magic for us, we have to do
# # some weird tricks to get at these.
#
# # Ask ourselves when we acquired the selection:
# ts_data = self.clipboard.wait_for_contents("TIMESTAMP").data
# ts_num = unpack("@i", ts_data[:4])[0]
# # Calculate the X atom for this selection:
# selection_xatom = get_xatom(self.clipboard, self.atom)
# # Ask X what window we used:
# self._xwindow = myGetSelectionOwner(self.clipboard, self.atom)
#
# root = self.clipboard.get_display().get_default_screen().get_root_window()
# sendClientMessage(root, False, const["StructureNotifyMask"],
# "MANAGER",
# ts_num, selection_xatom, self._xwindow, 0, 0)
#
# if old_owner != const["XNone"] and when is self.FORCE:
# # Block in a recursive mainloop until the previous owner has
# # cleared out.
# def getwin():
# window = get_pywindow(self.clipboard, old_owner)
# window.set_events(window.get_events() | gtk.gdk.STRUCTURE_MASK)
# return window
# try:
# window = trap.call(getwin)
# log("got window")
# except XError:
# log("Previous owner is already gone, not blocking")
# else:
# log("Waiting for previous owner to exit...")
# add_event_receiver(window, self)
# gtk.main()
# log("...they did.")
#
# def do_wimpiggy_destroy_event(self, event):
# remove_event_receiver(event.window, self)
# gtk.main_quit()
#
# def _get(self, clipboard, outdata, which, userdata):
# # We are compliant with ICCCM version 2.0 (see section 4.3)
# outdata.set("INTEGER", 32, pack("@ii", 2, 0))
#
# def _clear(self, clipboard, userdata):
# self._xwindow = None
# self.emit("selection-lost")
#
# def window(self):
# if self._xwindow is None:
# return None
# return get_pywindow(self.clipboard, self._xwindow)
#
# class AlreadyOwned(Exception):
# pass
. Output only the next line. | 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 temporarily. For instance,
# gtk_clipboard_for_display creates a GtkInvisible, which
# unconditionally sets its colormap (using the default display) before
# gtk_clipboard_for_display gets a chance to switch it to the proper
# display. So the end result is that we always need a valid default
# display of some sort:
gtk.gdk.display_manager_get().set_default_display(self.display)
print "Opened new display %r" % (self.display,)
os.environ["DBUS_SESSION_BUS_ADDRESS"] = _the_session._dbus_address
def tearDown(self):
# Could do cleanup here (close X11 connections, unset
# os.environ["DBUS_SESSION_BUS_ADDRESS"], etc.), but our test runner
# runs us in a forked off process that will exit immediately after
# this, so who cares?
pass
def clone_display(self):
clone = gtk.gdk.Display(self.display.get_name())
print "Cloned new display %r" % (clone,)
return clone
class MockEventReceiver(gobject.GObject):
__gsignals__ = {
<|code_end|>
, predict the next line using imports from the current file:
import subprocess
import sys
import os
import traceback
import os
import atexit
import errno
import gobject
import gtk
import gtk.gdk
from wimpiggy.util import one_arg_signal
and context including class names, function names, and sometimes code from other files:
# Path: wimpiggy/util.py
# class AutoPropGObjectMixin(object):
# class AdHocStruct(object):
# def __init__(self):
# def _munge_property_name(self, name):
# def do_get_property(self, pspec):
# def do_set_property(self, pspec, value):
# def _internal_set_property(self, name, value):
# def dump_exc():
# def __repr__(self):
# def n_arg_signal(n):
# def non_none_list_accumulator(ihint, return_accu, handler_return):
# def gtk_main_quit_really():
# def gtk_main_quit_forever():
# def gtk_main_quit_on_fatal_exceptions_enable():
# def gtk_main_quit_on_fatal_exception(type, val, tb):
. Output only the next line. | "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, couchpotato_host, couchpotato_port, couchpotato_apikey, couchpotato_basepath, couchpotato_ssl=False, **kwargs):
self.logger.debug("Testing connectivity to couchpotato")
if couchpotato_password and couchpotato_username != '':
couchpotato_password = hashlib.md5(couchpotato_password).hexdigest()
couchpotato_username = hashlib.md5(couchpotato_username).hexdigest()
getkey = 'getkey/?p=%s&u=%s' % (couchpotato_password, couchpotato_username)
if not(couchpotato_basepath.endswith('/')):
couchpotato_basepath += "/"
ssl = 's' if couchpotato_ssl else ''
url = 'http' + ssl + '://' + couchpotato_host + ':' + couchpotato_port + couchpotato_basepath + getkey
try:
return json.loads(urlopen(url, timeout=10).read())
except:
self.logger.error("Unable to connect to couchpotato")
self.logger.debug("connection-URL: " + url)
return json.loads(urlopen(url, timeout=10).read())
@cherrypy.expose()
@require()
def GetImage(self, url, h=None, w=None, o=100):
<|code_end|>
, determine the next line of code. You have imports:
import cherrypy
import htpc
import json
import logging
import hashlib
from htpc.proxy import get_image
from urllib2 import urlopen
from cherrypy.lib.auth2 import require
and context (class names, function names, or code) available:
# Path: htpc/proxy.py
# def get_image(url, height=None, width=None, opacity=100, auth=None, headers=None):
# """ Load image form cache if possible, else download. Resize if needed """
# opacity = float(opacity)
# logger = logging.getLogger('htpc.proxy')
#
# # Create image directory if it doesnt exist
# imgdir = os.path.join(htpc.DATADIR, 'images/')
# if not os.path.exists(imgdir):
# logger.debug("Creating image directory at " + imgdir)
# os.makedirs(imgdir)
#
# # Create a hash of the path to use as filename
# imghash = hashlib.md5(url).hexdigest()
#
# # Set filename and path
# image = os.path.join(imgdir, imghash)
#
# # If there is no local copy of the original
# if not os.path.isfile(image):
# logger.debug("No local image found for " + image + ". Downloading")
# download_image(url, image, auth, headers)
#
# # Check if resize is needed
# if (height and width) or (opacity < 100):
#
# if PIL:
# # Set filename for resized file
# resized = image + '_w' + width + '_h' + height + '_o' + str(opacity)
#
# # If there is no local resized copy
# if not os.path.isfile(resized):
# resize_image(image, height, width, opacity, resized)
#
# # Serve the resized file
# image = resized
# else:
# logger.error("Can't resize when PIL is missing on system!")
# if (opacity < 100):
# image = os.path.join(htpc.RUNDIR, 'interfaces/default/img/fff_20.png')
#
# # Load file from disk
# imagetype = imghdr.what(image)
# if imagetype is not None:
# return serve_file(path=image, content_type='image/' + imagetype)
. Output only the next line. | 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 Exception, e:
self.logger.error("Unable to fetch albums! Exception: " + str(e))
return
@cherrypy.expose()
@require()
def GetThumb(self, thumb=None, h=None, w=None, o=100):
""" Parse thumb to get the url and send to htpc.proxy.get_image """
#url = self.url('/images/DefaultVideo.png')
if thumb:
if o > 100:
url = "http://%s:%s%s" % (htpc.settings.get('plex_host', 'localhost'), htpc.settings.get('plex_port', '32400'), thumb)
else:
# If o < 100 transcode on Plex server to widen format support
url = "http://%s:%s/photo/:/transcode?height=%s&width=%s&url=%s" % (htpc.settings.get('plex_host', 'localhost'), htpc.settings.get('plex_port', '32400'), h, w, urllib.quote_plus("http://%s:%s%s" % (htpc.settings.get('plex_host', 'localhost'), htpc.settings.get('plex_port', '32400'), thumb)))
h=None
w=None
else:
url = "/images/DefaultVideo.png"
self.logger.debug("Trying to fetch image via " + url)
<|code_end|>
, generate the next line using the imports in this file:
import cherrypy
import htpc
import re
import socket
import struct
import logging
import urllib
import base64
import uuid
import platform
from json import loads, dumps
from urllib2 import Request, urlopen, quote
from htpc.proxy import get_image
from cherrypy.lib.auth2 import require
and context (functions, classes, or occasionally code) from other files:
# Path: htpc/proxy.py
# def get_image(url, height=None, width=None, opacity=100, auth=None, headers=None):
# """ Load image form cache if possible, else download. Resize if needed """
# opacity = float(opacity)
# logger = logging.getLogger('htpc.proxy')
#
# # Create image directory if it doesnt exist
# imgdir = os.path.join(htpc.DATADIR, 'images/')
# if not os.path.exists(imgdir):
# logger.debug("Creating image directory at " + imgdir)
# os.makedirs(imgdir)
#
# # Create a hash of the path to use as filename
# imghash = hashlib.md5(url).hexdigest()
#
# # Set filename and path
# image = os.path.join(imgdir, imghash)
#
# # If there is no local copy of the original
# if not os.path.isfile(image):
# logger.debug("No local image found for " + image + ". Downloading")
# download_image(url, image, auth, headers)
#
# # Check if resize is needed
# if (height and width) or (opacity < 100):
#
# if PIL:
# # Set filename for resized file
# resized = image + '_w' + width + '_h' + height + '_o' + str(opacity)
#
# # If there is no local resized copy
# if not os.path.isfile(resized):
# resize_image(image, height, width, opacity, resized)
#
# # Serve the resized file
# image = resized
# else:
# logger.error("Can't resize when PIL is missing on system!")
# if (opacity < 100):
# image = os.path.join(htpc.RUNDIR, 'interfaces/default/img/fff_20.png')
#
# # Load file from disk
# imagetype = imghdr.what(image)
# if imagetype is not None:
# return serve_file(path=image, content_type='image/' + imagetype)
. Output only the next line. | 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))
self.logger.info("Selecting XBMC server: %s", id)
return "success"
except SQLObjectNotFound:
try:
self.current = XbmcServers.select(limit=1).getOne()
self.logger.error("Invalid server. Selecting first Available.")
return "success"
except SQLObjectNotFound:
self.current = None
self.logger.warning("No configured XBMC-Servers.")
return "No valid servers"
@cherrypy.expose()
@require()
def GetThumb(self, thumb=None, h=None, w=None, o=100):
""" Parse thumb to get the url and send to htpc.proxy.get_image """
url = self.url('/images/DefaultVideo.png')
if thumb:
url = self.url('/image/' + quote(thumb))
self.logger.debug("Trying to fetch image via %s", url)
<|code_end|>
using the current file's imports:
import cherrypy
import htpc
import base64
import socket
import struct
import logging
from urllib2 import quote
from jsonrpclib import Server
from sqlobject import SQLObject, SQLObjectNotFound
from sqlobject.col import StringCol, IntCol
from htpc.proxy import get_image
from cherrypy.lib.auth2 import require
and any relevant context from other files:
# Path: htpc/proxy.py
# def get_image(url, height=None, width=None, opacity=100, auth=None, headers=None):
# """ Load image form cache if possible, else download. Resize if needed """
# opacity = float(opacity)
# logger = logging.getLogger('htpc.proxy')
#
# # Create image directory if it doesnt exist
# imgdir = os.path.join(htpc.DATADIR, 'images/')
# if not os.path.exists(imgdir):
# logger.debug("Creating image directory at " + imgdir)
# os.makedirs(imgdir)
#
# # Create a hash of the path to use as filename
# imghash = hashlib.md5(url).hexdigest()
#
# # Set filename and path
# image = os.path.join(imgdir, imghash)
#
# # If there is no local copy of the original
# if not os.path.isfile(image):
# logger.debug("No local image found for " + image + ". Downloading")
# download_image(url, image, auth, headers)
#
# # Check if resize is needed
# if (height and width) or (opacity < 100):
#
# if PIL:
# # Set filename for resized file
# resized = image + '_w' + width + '_h' + height + '_o' + str(opacity)
#
# # If there is no local resized copy
# if not os.path.isfile(resized):
# resize_image(image, height, width, opacity, resized)
#
# # Serve the resized file
# image = resized
# else:
# logger.error("Can't resize when PIL is missing on system!")
# if (opacity < 100):
# image = os.path.join(htpc.RUNDIR, 'interfaces/default/img/fff_20.png')
#
# # Load file from disk
# imagetype = imghdr.what(image)
# if imagetype is not None:
# return serve_file(path=image, content_type='image/' + imagetype)
. Output only the next line. | 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')
self.logger.debug('Current version: ' + output)
if (output == '') :
self.logger.error('Got no response for current Git version.')
return False
if re.match('^[a-z0-9]+$', output):
return output
def update(self):
""" Do update through git """
self.logger.info("Attempting update through Git.")
self.UPDATING = 1
output = self.git_exec('pull origin %s' % gitBranch)
if not output:
self.logger.error("Unable to update through git. Make sure that Git is located in your path and can be accessed by this application.")
elif 'Aborting.' in output:
self.logger.error("Update aborted.")
else:
# Restart HTPC Manager to make sure all new code is loaded
self.logger.warning('Restarting HTPC Manager after update.')
<|code_end|>
, determine the next line of code. You have imports:
import os
import urllib2
import subprocess
import re
import cherrypy
import htpc
import logging
import tarfile
import shutil
from threading import Thread
from json import loads
from htpc.root import do_restart
and context (class names, function names, or code) available:
# Path: htpc/root.py
# def do_restart():
# arguments = sys.argv[:]
# arguments.insert(0, sys.executable)
# if sys.platform == 'win32':
# arguments = ['"%s"' % arg for arg in arguments]
# os.chdir(os.getcwd())
# cherrypy.engine.exit()
# os.execv(sys.executable, arguments)
. Output only the next line. | 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_enable'},
{'type':'text', 'label':'Host', 'name':'newznab_host'},
{'type':'text', 'label':'Apikey', 'name':'newznab_apikey'},
{'type': 'bool', 'label': 'Use SSL', 'name': 'newznab_ssl'}
]})
@cherrypy.expose()
@require()
def index(self, query='', **kwargs):
return htpc.LOOKUP.get_template('search.html').render(query=query, scriptname='search')
@cherrypy.expose()
@require()
def thumb(self, url, h=None, w=None, o=100):
if url.startswith('rageid'):
settings = htpc.settings
host = settings.get('newznab_host', '').replace('http://', '').replace('https://', '')
ssl = 's' if settings.get('newznab_ssl', 0) else ''
url = 'http' + ssl + '://' + host + '/covers/tv/' + url[6:] + '.jpg'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import cherrypy
import htpc
import urllib2
import logging
from htpc.proxy import get_image
from json import loads
from cherrypy.lib.auth2 import require
and context:
# Path: htpc/proxy.py
# def get_image(url, height=None, width=None, opacity=100, auth=None, headers=None):
# """ Load image form cache if possible, else download. Resize if needed """
# opacity = float(opacity)
# logger = logging.getLogger('htpc.proxy')
#
# # Create image directory if it doesnt exist
# imgdir = os.path.join(htpc.DATADIR, 'images/')
# if not os.path.exists(imgdir):
# logger.debug("Creating image directory at " + imgdir)
# os.makedirs(imgdir)
#
# # Create a hash of the path to use as filename
# imghash = hashlib.md5(url).hexdigest()
#
# # Set filename and path
# image = os.path.join(imgdir, imghash)
#
# # If there is no local copy of the original
# if not os.path.isfile(image):
# logger.debug("No local image found for " + image + ". Downloading")
# download_image(url, image, auth, headers)
#
# # Check if resize is needed
# if (height and width) or (opacity < 100):
#
# if PIL:
# # Set filename for resized file
# resized = image + '_w' + width + '_h' + height + '_o' + str(opacity)
#
# # If there is no local resized copy
# if not os.path.isfile(resized):
# resize_image(image, height, width, opacity, resized)
#
# # Serve the resized file
# image = resized
# else:
# logger.error("Can't resize when PIL is missing on system!")
# if (opacity < 100):
# image = os.path.join(htpc.RUNDIR, 'interfaces/default/img/fff_20.png')
#
# # Load file from disk
# imagetype = imghdr.what(image)
# if imagetype is not None:
# return serve_file(path=image, content_type='image/' + imagetype)
which might include code, classes, or functions. Output only the next line. | 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 config.email_type == 'gmail': # gmail send
server = smtplib.SMTP('smtp.gmail.com:587')
elif config.email_type == 'qq': # qq send
server = smtplib.SMTP_SSL('smtp.qq.com', 465)
else: # default gmail
server = smtplib.SMTP('smtp.gmail.com:587')
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(config.self_email, config.self_password)
server.sendmail(config.self_email, to_email, msg.as_string())
server.quit()
logging.debug('send_email success...')
return True
except Exception, e:
logging.exception('send_email exception msg:%s' % e)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import smtplib
import logging
import config
from cus_exception import CusException
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
and context:
# Path: cus_exception.py
# class CusException(Exception):
# def __init__(self, name, error_msg):
# super(CusException, self).__init__(name, error_msg)
# self.name = name
#
# if type(error_msg) == CusException:
# self.error_msg = error_msg.error_msg
# else:
# self.error_msg = error_msg
#
# self.error_time = str(datetime.datetime.now())
which might include code, classes, or functions. Output only the next line. | 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.product_id = '3995645'
# self.product_id = '10213303572'
self.font_name = 'DroidSansFallback.ttf'
<|code_end|>
. Write the next line using the current file imports:
import matplotlib
import logging
import utils
import config
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from matplotlib import font_manager
from pandas import DataFrame, Series
from jd_analysis import settings
from PIL import Image
from cus_exception import CusException
and context from other files:
# Path: jd_analysis/settings.py
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECRET_KEY = '!=6ve76(w#_0r_b8ic#mo-*s2#xf^*&(lfn1$#c=0-u=icl(8@'
# DEBUG = True
# ALLOWED_HOSTS = []
# INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
# 'django_crontab',
# 'jd',
# ]
# MIDDLEWARE = [
# 'django.middleware.security.SecurityMiddleware',
# 'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.messages.middleware.MessageMiddleware',
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
# ]
# ROOT_URLCONF = 'jd_analysis.urls'
# TEMPLATES = [
# {
# 'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [],
# 'APP_DIRS': True,
# 'OPTIONS': {
# 'context_processors': [
# 'django.template.context_processors.debug',
# 'django.template.context_processors.request',
# 'django.contrib.auth.context_processors.auth',
# 'django.contrib.messages.context_processors.messages',
# ],
# },
# },
# ]
# WSGI_APPLICATION = 'jd_analysis.wsgi.application'
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'jd_analysis',
# 'USER': 'root',
# 'PASSWORD': '123456',
# 'HOST': '',
# 'PORT': '',
# }
# }
# AUTH_PASSWORD_VALIDATORS = [
# {
# 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
# },
# ]
# CRONJOBS = [
# ('*/1 */1 * * *', 'django.core.management.call_command', ['full_analysis'], {},
# '>> ' + BASE_DIR + '/log/full_analysis.log')
# ]
# LANGUAGE_CODE = 'en-us'
# TIME_ZONE = 'Asia/Shanghai'
# USE_I18N = True
# USE_L10N = True
# USE_TZ = True
# STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
#
# Path: cus_exception.py
# class CusException(Exception):
# def __init__(self, name, error_msg):
# super(CusException, self).__init__(name, error_msg)
# self.name = name
#
# if type(error_msg) == CusException:
# self.error_msg = error_msg.error_msg
# else:
# self.error_msg = error_msg
#
# self.error_time = str(datetime.datetime.now())
, which may include functions, classes, or code. Output only the next line. | 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/font/%s' % (settings.BASE_DIR, self.font_name)
self.full_result = ''
self.bar_width = 0.45
self.opacity = 0.4
self.color = 'b'
self.data_frame = None
self.init()
def init(self):
prop = font_manager.FontProperties(fname = self.font_path)
matplotlib.rcParams['font.family'] = prop.get_name()
try:
command = "SELECT product_color, product_size, user_level_name, user_province, reference_time, " \
"creation_time,is_mobile, user_client_show, days, user_level_name FROM {0}". \
format('item_%s' % self.product_id)
result = self.sql.query(command, commit = False, cursor_type = 'dict')
self.data_frame = DataFrame(result)
except Exception, e:
logging.exception('analysis init exception msg:%s' % e)
<|code_end|>
. Use current file imports:
(import matplotlib
import logging
import utils
import config
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from matplotlib import font_manager
from pandas import DataFrame, Series
from jd_analysis import settings
from PIL import Image
from cus_exception import CusException)
and context including class names, function names, or small code snippets from other files:
# Path: jd_analysis/settings.py
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECRET_KEY = '!=6ve76(w#_0r_b8ic#mo-*s2#xf^*&(lfn1$#c=0-u=icl(8@'
# DEBUG = True
# ALLOWED_HOSTS = []
# INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
# 'django_crontab',
# 'jd',
# ]
# MIDDLEWARE = [
# 'django.middleware.security.SecurityMiddleware',
# 'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.messages.middleware.MessageMiddleware',
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
# ]
# ROOT_URLCONF = 'jd_analysis.urls'
# TEMPLATES = [
# {
# 'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [],
# 'APP_DIRS': True,
# 'OPTIONS': {
# 'context_processors': [
# 'django.template.context_processors.debug',
# 'django.template.context_processors.request',
# 'django.contrib.auth.context_processors.auth',
# 'django.contrib.messages.context_processors.messages',
# ],
# },
# },
# ]
# WSGI_APPLICATION = 'jd_analysis.wsgi.application'
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'jd_analysis',
# 'USER': 'root',
# 'PASSWORD': '123456',
# 'HOST': '',
# 'PORT': '',
# }
# }
# AUTH_PASSWORD_VALIDATORS = [
# {
# 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
# },
# ]
# CRONJOBS = [
# ('*/1 */1 * * *', 'django.core.management.call_command', ['full_analysis'], {},
# '>> ' + BASE_DIR + '/log/full_analysis.log')
# ]
# LANGUAGE_CODE = 'en-us'
# TIME_ZONE = 'Asia/Shanghai'
# USE_I18N = True
# USE_L10N = True
# USE_TZ = True
# STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
#
# Path: cus_exception.py
# class CusException(Exception):
# def __init__(self, name, error_msg):
# super(CusException, self).__init__(name, error_msg)
# self.name = name
#
# if type(error_msg) == CusException:
# self.error_msg = error_msg.error_msg
# else:
# self.error_msg = error_msg
#
# self.error_time = str(datetime.datetime.now())
. Output only the next line. | 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('HTTP_USER_AGENT', '')
vt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
jd_url = request.POST.get('url')
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import utils
from django.utils.deprecation import MiddlewareMixin
from jd.models import JDVisit
and context (class names, function names, or code) available:
# Path: jd/models.py
# class JDVisit(models.Model):
# id = models.AutoField(primary_key = True, name = 'id')
# jd_url = models.CharField(max_length = 200, name = 'jd_url', verbose_name = '京东商城商品的 url 链接', default = '')
# ip = models.CharField(max_length = 20, name = 'ip', verbose_name = '访问者的 IP 地址')
# ip_address = models.CharField(max_length = 200, name = 'ip_address', verbose_name = 'IP 对应的地址', default = None)
# visit_time = models.DateTimeField(name = 'visit_time', verbose_name = '访问的时间')
# user_agent = models.TextField(max_length = 1000, name = 'user_agent', verbose_name = '访问者的 HTTP_USER_AGENT',
# default = '')
#
# ip_hight_success = models.CharField(max_length = 10, name = 'ip_hight_success', verbose_name = '查询 IP 高精度定位是否成功',
# default = '')
# ip_hight_address = models.CharField(max_length = 200, name = 'ip_hight_address', verbose_name = 'IP 对应的高精度地址',
# default = '')
# ip_confidence = models.FloatField(name = 'ip_confidence', verbose_name = 'IP 高精度查询结果的可信度', default = 0)
# ip_hight_radius = models.IntegerField(name = 'ip_hight_radius', verbose_name = 'IP 高精度查询结果的偏移半径', default = -1)
# ip_hight_lat = models.FloatField(name = 'ip_hight_lat', verbose_name = 'IP 高精度查询经度', default = -1)
# ip_hight_long = models.FloatField(name = 'ip_hight_long', verbose_name = 'IP 高精度查询纬度', default = -1)
#
# class Meta:
# db_table = 'jd_visit'
. Output only the next line. | 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.