Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|> 'normal': {'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]'
' %(message)s')},
}
}
# Internal dev pecan server
server = {
'port': '51000',
'host': '0.0.0.0'
}
# Pecan REST and rendering configuration
app = {
'root': 'repoxplorer.controllers.root.RootController',
'modules': ['repoxplorer'],
'custom_renderers': {'csv': CSVRenderer},
'static_root': '%s/public' % runtimedir,
'debug': False,
'errors': {
404: '/error/e404',
'__force_dict__': True
}
}
# Additional RepoXplorer configurations
db_default_file = None
db_path = runtimedir
db_cache_path = db_path
git_store = '%s/git_store' % runtimedir
xorkey = None
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import copy
from repoxplorer.controllers.renderers import CSVRenderer
and context from other files:
# Path: repoxplorer/controllers/renderers.py
# class CSVRenderer(object):
# def __init__(self, path, extra_vars):
# pass
#
# def render(self, template_path, namespace):
# buf = StringIO()
# # Assume namespace an array of dict
# if not isinstance(namespace, list):
# namespace = [namespace]
# for e in namespace:
# assert isinstance(e, dict)
# keys = list(namespace[0].keys())
# keys.sort()
# w = csv.DictWriter(buf, fieldnames=keys)
# w.writeheader()
# for e in namespace:
# d = {}
# for k, v in e.items():
# if not any([
# isinstance(v, str),
# isinstance(v, list),
# isinstance(v, int),
# isinstance(v, float)]):
# raise ValueError(
# "'%s' (type: %s) is not supported for CSV output" % (
# str(v), type(v)))
# if isinstance(v, str):
# d[k] = v
# elif isinstance(v, list):
# d[k] = ";".join(v)
# else:
# d[k] = str(v)
# w.writerow(d)
# buf.seek(0)
# return buf.read()
, which may include functions, classes, or code. Output only the next line. | elasticsearch_host = 'localhost' |
Predict the next line after this snippet: <|code_start|>
# Server Specific Configurations
server = {
'port': '8080',
'host': '0.0.0.0'
}
# Pecan Application Configurations
app = {
'root': 'repoxplorer.controllers.root.RootController',
'modules': ['repoxplorer'],
'custom_renderers': {'csv': CSVRenderer},
'static_root': '%(confdir)s/../../public',
'debug': True,
'errors': {
'404': '/error/404',
'__force_dict__': True
}
}
projects_file_path = None
git_store = None
<|code_end|>
using the current file's imports:
import tempfile
from repoxplorer.controllers.renderers import CSVRenderer
and any relevant context from other files:
# Path: repoxplorer/controllers/renderers.py
# class CSVRenderer(object):
# def __init__(self, path, extra_vars):
# pass
#
# def render(self, template_path, namespace):
# buf = StringIO()
# # Assume namespace an array of dict
# if not isinstance(namespace, list):
# namespace = [namespace]
# for e in namespace:
# assert isinstance(e, dict)
# keys = list(namespace[0].keys())
# keys.sort()
# w = csv.DictWriter(buf, fieldnames=keys)
# w.writeheader()
# for e in namespace:
# d = {}
# for k, v in e.items():
# if not any([
# isinstance(v, str),
# isinstance(v, list),
# isinstance(v, int),
# isinstance(v, float)]):
# raise ValueError(
# "'%s' (type: %s) is not supported for CSV output" % (
# str(v), type(v)))
# if isinstance(v, str):
# d[k] = v
# elif isinstance(v, list):
# d[k] = ";".join(v)
# else:
# d[k] = str(v)
# w.writerow(d)
# buf.seek(0)
# return buf.read()
. Output only the next line. | db_path = tempfile.mkdtemp() |
Given the code snippet: <|code_start|># Copyright 2017, Fabien Boucher
# Copyright 2017, Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class TestCSVRenderer(TestCase):
def setUp(self):
self.csvrender = renderers.CSVRenderer(None, None)
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from repoxplorer.controllers import renderers
and context (functions, classes, or occasionally code) from other files:
# Path: repoxplorer/controllers/renderers.py
# class CSVRenderer(object):
# def __init__(self, path, extra_vars):
# def render(self, template_path, namespace):
. Output only the next line. | def test_rendering(self): |
Predict the next line for this snippet: <|code_start|>
def parse_arguments():
parser = argparse.ArgumentParser(
description='''Train a Multi-Task deep neural network. Note: Only high-level hyperparameters can be set
through command-line arguments. Network architechture; and choice of activation function, regularization
technique, and iterative optimization procedure can be tweaked by modifying the code.''')
parser.add_argument('--learning-rate', nargs='?', type=float, default=LEARNING_RATE, const=LEARNING_RATE,
help="Learning rate for SGD", dest='learning_rate')
parser.add_argument('--batch-size', nargs='?', type=int, default=BATCH_SIZE, const=BATCH_SIZE,
help="Mini-batch size for SGD-based training", dest='batch_size')
parser.add_argument('--num-epochs', nargs='?', type=int, default=NUM_EPOCHS, const=NUM_EPOCHS,
help="Number of epochs -- number of passes over the entire training set.", dest='num_epochs')
parser.add_argument('--experiment-name', nargs='?', type=str, default=EXPT_NAME, const=EXPT_NAME,
<|code_end|>
with the help of current file imports:
import argparse
from utils.network_utils.params import LEARNING_RATE, BATCH_SIZE, NUM_EPOCHS
from utils.training_utils.params import EXPT_NAME
and context from other files:
# Path: utils/network_utils/params.py
# LEARNING_RATE = 1e-4
#
# BATCH_SIZE = 128
#
# NUM_EPOCHS = 1000
#
# Path: utils/training_utils/params.py
# EXPT_NAME = "default"
, which may contain function names, class names, or code. Output only the next line. | help="""Name of the experiment to be used to name the experiment's directory""", |
Using the snippet: <|code_start|>
def parse_arguments():
parser = argparse.ArgumentParser(
description='''Train a Multi-Task deep neural network. Note: Only high-level hyperparameters can be set
through command-line arguments. Network architechture; and choice of activation function, regularization
technique, and iterative optimization procedure can be tweaked by modifying the code.''')
parser.add_argument('--learning-rate', nargs='?', type=float, default=LEARNING_RATE, const=LEARNING_RATE,
help="Learning rate for SGD", dest='learning_rate')
parser.add_argument('--batch-size', nargs='?', type=int, default=BATCH_SIZE, const=BATCH_SIZE,
help="Mini-batch size for SGD-based training", dest='batch_size')
parser.add_argument('--num-epochs', nargs='?', type=int, default=NUM_EPOCHS, const=NUM_EPOCHS,
help="Number of epochs -- number of passes over the entire training set.", dest='num_epochs')
parser.add_argument('--experiment-name', nargs='?', type=str, default=EXPT_NAME, const=EXPT_NAME,
help="""Name of the experiment to be used to name the experiment's directory""",
dest='experiment_name')
<|code_end|>
, determine the next line of code. You have imports:
import argparse
from utils.network_utils.params import LEARNING_RATE, BATCH_SIZE, NUM_EPOCHS
from utils.training_utils.params import EXPT_NAME
and context (class names, function names, or code) available:
# Path: utils/network_utils/params.py
# LEARNING_RATE = 1e-4
#
# BATCH_SIZE = 128
#
# NUM_EPOCHS = 1000
#
# Path: utils/training_utils/params.py
# EXPT_NAME = "default"
. Output only the next line. | parser.add_argument('--task-type', nargs='?', type=str, dest='task_type') |
Given the following code snippet before the placeholder: <|code_start|>
def parse_arguments():
parser = argparse.ArgumentParser(
description='''Train a Multi-Task deep neural network. Note: Only high-level hyperparameters can be set
through command-line arguments. Network architechture; and choice of activation function, regularization
technique, and iterative optimization procedure can be tweaked by modifying the code.''')
parser.add_argument('--learning-rate', nargs='?', type=float, default=LEARNING_RATE, const=LEARNING_RATE,
help="Learning rate for SGD", dest='learning_rate')
parser.add_argument('--batch-size', nargs='?', type=int, default=BATCH_SIZE, const=BATCH_SIZE,
help="Mini-batch size for SGD-based training", dest='batch_size')
parser.add_argument('--num-epochs', nargs='?', type=int, default=NUM_EPOCHS, const=NUM_EPOCHS,
help="Number of epochs -- number of passes over the entire training set.", dest='num_epochs')
parser.add_argument('--experiment-name', nargs='?', type=str, default=EXPT_NAME, const=EXPT_NAME,
help="""Name of the experiment to be used to name the experiment's directory""",
dest='experiment_name')
parser.add_argument('--task-type', nargs='?', type=str, dest='task_type')
<|code_end|>
, predict the next line using imports from the current file:
import argparse
from utils.network_utils.params import LEARNING_RATE, BATCH_SIZE, NUM_EPOCHS
from utils.training_utils.params import EXPT_NAME
and context including class names, function names, and sometimes code from other files:
# Path: utils/network_utils/params.py
# LEARNING_RATE = 1e-4
#
# BATCH_SIZE = 128
#
# NUM_EPOCHS = 1000
#
# Path: utils/training_utils/params.py
# EXPT_NAME = "default"
. Output only the next line. | results = parser.parse_args() |
Given the following code snippet before the placeholder: <|code_start|>
class Coupled(object):
tasks = {
'tightly_coupled': {'pop': LossTypes.cross_entropy,
'pop rock': LossTypes.cross_entropy,
'ballad': LossTypes.cross_entropy},
'loosely_coupled': {'pop': LossTypes.cross_entropy,
'loudness': LossTypes.mse,
'year': LossTypes.mse}
<|code_end|>
, predict the next line using imports from the current file:
from utils.network_utils.params import LossTypes
and context including class names, function names, and sometimes code from other files:
# Path: utils/network_utils/params.py
# class LossTypes(Enum):
# mse = "mse"
# cross_entropy = "cross-entropy"
. Output only the next line. | } |
Given snippet: <|code_start|>
class ConsolePlayerTest(BaseUnitTest):
def setUp(self):
self.valid_actions = [\
{'action': 'fold', 'amount': 0},\
{'action': 'call', 'amount': 10},\
{'action': 'raise', 'amount': {'max': 105, 'min': 15}}\
]
self.round_state = {
'dealer_btn': 1,
'street': 'preflop',
'seats': [
{'stack': 85, 'state': 'participating', 'name': u'player1', 'uuid': 'ciglbcevkvoqzguqvnyhcb'},
{'stack': 100, 'state': 'participating', 'name': u'player2', 'uuid': 'zjttlanhlvpqzebrwmieho'}
],
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tests.base_unittest import BaseUnitTest
from examples.players.console_player import ConsolePlayer
and context:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: examples/players/console_player.py
# class ConsolePlayer(BasePokerPlayer):
#
# def __init__(self, input_receiver=None):
# self.input_receiver = input_receiver if input_receiver else self.__gen_raw_input_wrapper()
#
# def declare_action(self, valid_actions, hole_card, round_state):
# print(U.visualize_declare_action(valid_actions, hole_card, round_state, self.uuid))
# action, amount = self.__receive_action_from_console(valid_actions)
# return action, amount
#
# def receive_game_start_message(self, game_info):
# print(U.visualize_game_start(game_info, self.uuid))
# self.__wait_until_input()
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# print(U.visualize_round_start(round_count, hole_card, seats, self.uuid))
# self.__wait_until_input()
#
# def receive_street_start_message(self, street, round_state):
# print(U.visualize_street_start(street, round_state, self.uuid))
# self.__wait_until_input()
#
# def receive_game_update_message(self, new_action, round_state):
# print(U.visualize_game_update(new_action, round_state, self.uuid))
# self.__wait_until_input()
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# print(U.visualize_round_result(winners, hand_info, round_state, self.uuid))
# self.__wait_until_input()
#
# def __wait_until_input(self):
# raw_input("Enter some key to continue ...")
#
# def __gen_raw_input_wrapper(self):
# return lambda msg: raw_input(msg)
#
# def __receive_action_from_console(self, valid_actions):
# flg = self.input_receiver('Enter f(fold), c(call), r(raise).\n >> ')
# if flg in self.__gen_valid_flg(valid_actions):
# if flg == 'f':
# return valid_actions[0]['action'], valid_actions[0]['amount']
# elif flg == 'c':
# return valid_actions[1]['action'], valid_actions[1]['amount']
# elif flg == 'r':
# valid_amounts = valid_actions[2]['amount']
# raise_amount = self.__receive_raise_amount_from_console(valid_amounts['min'], valid_amounts['max'])
# return valid_actions[2]['action'], raise_amount
# else:
# return self.__receive_action_from_console(valid_actions)
#
# def __gen_valid_flg(self, valid_actions):
# flgs = ['f', 'c']
# is_raise_possible = valid_actions[2]['amount']['min'] != -1
# if is_raise_possible:
# flgs.append('r')
# return flgs
#
# def __receive_raise_amount_from_console(self, min_amount, max_amount):
# raw_amount = self.input_receiver("valid raise range = [%d, %d]" % (min_amount, max_amount))
# try:
# amount = int(raw_amount)
# if min_amount <= amount and amount <= max_amount:
# return amount
# else:
# print("Invalid raise amount %d. Try again.")
# return self.__receive_raise_amount_from_console(min_amount, max_amount)
# except:
# print("Invalid input received. Try again.")
# return self.__receive_raise_amount_from_console(min_amount, max_amount)
which might include code, classes, or functions. Output only the next line. | 'next_player': 1, |
Next line prediction: <|code_start|>
class ConsolePlayerTest(BaseUnitTest):
def setUp(self):
self.valid_actions = [\
{'action': 'fold', 'amount': 0},\
{'action': 'call', 'amount': 10},\
{'action': 'raise', 'amount': {'max': 105, 'min': 15}}\
]
self.round_state = {
'dealer_btn': 1,
'street': 'preflop',
'seats': [
{'stack': 85, 'state': 'participating', 'name': u'player1', 'uuid': 'ciglbcevkvoqzguqvnyhcb'},
{'stack': 100, 'state': 'participating', 'name': u'player2', 'uuid': 'zjttlanhlvpqzebrwmieho'}
],
'next_player': 1,
'small_blind_pos': 0,
<|code_end|>
. Use current file imports:
(from tests.base_unittest import BaseUnitTest
from examples.players.console_player import ConsolePlayer)
and context including class names, function names, or small code snippets from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: examples/players/console_player.py
# class ConsolePlayer(BasePokerPlayer):
#
# def __init__(self, input_receiver=None):
# self.input_receiver = input_receiver if input_receiver else self.__gen_raw_input_wrapper()
#
# def declare_action(self, valid_actions, hole_card, round_state):
# print(U.visualize_declare_action(valid_actions, hole_card, round_state, self.uuid))
# action, amount = self.__receive_action_from_console(valid_actions)
# return action, amount
#
# def receive_game_start_message(self, game_info):
# print(U.visualize_game_start(game_info, self.uuid))
# self.__wait_until_input()
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# print(U.visualize_round_start(round_count, hole_card, seats, self.uuid))
# self.__wait_until_input()
#
# def receive_street_start_message(self, street, round_state):
# print(U.visualize_street_start(street, round_state, self.uuid))
# self.__wait_until_input()
#
# def receive_game_update_message(self, new_action, round_state):
# print(U.visualize_game_update(new_action, round_state, self.uuid))
# self.__wait_until_input()
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# print(U.visualize_round_result(winners, hand_info, round_state, self.uuid))
# self.__wait_until_input()
#
# def __wait_until_input(self):
# raw_input("Enter some key to continue ...")
#
# def __gen_raw_input_wrapper(self):
# return lambda msg: raw_input(msg)
#
# def __receive_action_from_console(self, valid_actions):
# flg = self.input_receiver('Enter f(fold), c(call), r(raise).\n >> ')
# if flg in self.__gen_valid_flg(valid_actions):
# if flg == 'f':
# return valid_actions[0]['action'], valid_actions[0]['amount']
# elif flg == 'c':
# return valid_actions[1]['action'], valid_actions[1]['amount']
# elif flg == 'r':
# valid_amounts = valid_actions[2]['amount']
# raise_amount = self.__receive_raise_amount_from_console(valid_amounts['min'], valid_amounts['max'])
# return valid_actions[2]['action'], raise_amount
# else:
# return self.__receive_action_from_console(valid_actions)
#
# def __gen_valid_flg(self, valid_actions):
# flgs = ['f', 'c']
# is_raise_possible = valid_actions[2]['amount']['min'] != -1
# if is_raise_possible:
# flgs.append('r')
# return flgs
#
# def __receive_raise_amount_from_console(self, min_amount, max_amount):
# raw_amount = self.input_receiver("valid raise range = [%d, %d]" % (min_amount, max_amount))
# try:
# amount = int(raw_amount)
# if min_amount <= amount and amount <= max_amount:
# return amount
# else:
# print("Invalid raise amount %d. Try again.")
# return self.__receive_raise_amount_from_console(min_amount, max_amount)
# except:
# print("Invalid input received. Try again.")
# return self.__receive_raise_amount_from_console(min_amount, max_amount)
. Output only the next line. | 'big_blind_pos': 1, |
Given snippet: <|code_start|>
class CardTest(BaseUnitTest):
def setUp(self):
pass
def test_to_string(self):
self.eq(str(Card(Card.CLUB, 1)), "CA")
self.eq(str(Card(Card.CLUB, 14)), "CA")
self.eq(str(Card(Card.CLUB, 2)), "C2")
self.eq(str(Card(Card.HEART, 10)), "HT")
self.eq(str(Card(Card.SPADE, 11)), "SJ")
self.eq(str(Card(Card.DIAMOND, 12)), "DQ")
self.eq(str(Card(Card.DIAMOND, 13)), "DK")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.card import Card
and context:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
which might include code, classes, or functions. Output only the next line. | def test_to_id(self): |
Given the code snippet: <|code_start|>
class CardTest(BaseUnitTest):
def setUp(self):
pass
<|code_end|>
, generate the next line using the imports in this file:
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.card import Card
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
. Output only the next line. | def test_to_string(self): |
Using the snippet: <|code_start|>
class GameStateUtils(BaseUnitTest):
def test_attach_hole_card_from_deck(self):
game_state = restore_game_state(TwoPlayerSample.round_state)
self.eq(48, game_state["table"].deck.size())
processed1 = attach_hole_card_from_deck(game_state, "tojrbxmkuzrarnniosuhct")
processed2 = attach_hole_card_from_deck(processed1, "pwtwlmfciymjdoljkhagxa")
self.eq(44, processed2["table"].deck.size())
self.eq(48, game_state["table"].deck.size())
def test_replace_community_card_from_deck(self):
origianl = restore_game_state(TwoPlayerSample.round_state)
origianl["street"] = Const.Street.PREFLOP
game_state = replace_community_card_from_deck(origianl)
<|code_end|>
, determine the next line of code. You have imports:
from nose.tools import raises
from tests.base_unittest import BaseUnitTest
from pypokerengine.utils.game_state_utils import restore_game_state,\
attach_hole_card, replace_community_card,\
attach_hole_card_from_deck, replace_community_card_from_deck
from pypokerengine.engine.card import Card
from pypokerengine.engine.poker_constants import PokerConstants as Const
and context (class names, function names, or code) available:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/utils/game_state_utils.py
# def restore_game_state(round_state):
# return {
# "round_count": round_state["round_count"],
# "small_blind_amount": round_state["small_blind_amount"],
# "street": _street_flg_translator[round_state["street"]],
# "next_player": round_state["next_player"],
# "table": _restore_table(round_state)
# }
#
# def attach_hole_card(game_state, uuid, hole_card):
# deepcopy = deepcopy_game_state(game_state)
# target = [player for player in deepcopy["table"].seats.players if uuid==player.uuid]
# if len(target)==0: raise Exception('The player whose uuid is "%s" is not found in passed game_state.' % uuid)
# if len(target)!=1: raise Exception('Multiple players have uuid "%s". So we cannot attach hole card.' % uuid)
# target[0].hole_card = hole_card
# return deepcopy
#
# def replace_community_card(game_state, community_card):
# deepcopy = deepcopy_game_state(game_state)
# deepcopy["table"]._community_card = community_card
# return deepcopy
#
# def attach_hole_card_from_deck(game_state, uuid):
# deepcopy = deepcopy_game_state(game_state)
# hole_card = deepcopy["table"].deck.draw_cards(2)
# return attach_hole_card(deepcopy, uuid, hole_card)
#
# def replace_community_card_from_deck(game_state):
# deepcopy = deepcopy_game_state(game_state)
# card_num = _street_community_card_num[deepcopy["street"]]
# community_card = deepcopy["table"].deck.draw_cards(card_num)
# return replace_community_card(deepcopy, community_card)
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/poker_constants.py
# class PokerConstants:
#
# class Action:
# FOLD = 0
# CALL = 1
# RAISE = 2
# SMALL_BLIND = 3
# BIG_BLIND = 4
# ANTE = 5
#
# class Street:
# PREFLOP = 0
# FLOP = 1
# TURN = 2
# RIVER = 3
# SHOWDOWN = 4
# FINISHED = 5
. Output only the next line. | self.eq(48, game_state["table"].deck.size()) |
Next line prediction: <|code_start|>
class RandomPlayer(BasePokerPlayer):
def __init__(self):
self.fold_ratio = self.call_ratio = raise_ratio = 1.0/3
def set_action_ratio(self, fold_ratio, call_ratio, raise_ratio):
ratio = [fold_ratio, call_ratio, raise_ratio]
scaled_ratio = [ 1.0 * num / sum(ratio) for num in ratio]
self.fold_ratio, self.call_ratio, self.raise_ratio = scaled_ratio
def declare_action(self, valid_actions, hole_card, round_state):
choice = self.__choice_action(valid_actions)
action = choice["action"]
amount = choice["amount"]
if action == "raise":
amount = rand.randrange(amount["min"], max(amount["min"], amount["max"]) + 1)
return action, amount
def __choice_action(self, valid_actions):
r = rand.random()
<|code_end|>
. Use current file imports:
(from pypokerengine.players import BasePokerPlayer
import random as rand)
and context including class names, function names, or small code snippets from other files:
# Path: pypokerengine/players.py
# class BasePokerPlayer(object):
# """Base Poker client implementation
#
# To create poker client, you need to override this class and
# implement following 7 methods.
#
# - declare_action
# - receive_game_start_message
# - receive_round_start_message
# - receive_street_start_message
# - receive_game_update_message
# - receive_round_result_message
# """
#
# def __init__(self):
# pass
#
# def declare_action(self, valid_actions, hole_card, round_state):
# err_msg = self.__build_err_msg("declare_action")
# raise NotImplementedError(err_msg)
#
# def receive_game_start_message(self, game_info):
# err_msg = self.__build_err_msg("receive_game_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# err_msg = self.__build_err_msg("receive_round_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_street_start_message(self, street, round_state):
# err_msg = self.__build_err_msg("receive_street_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_game_update_message(self, new_action, round_state):
# err_msg = self.__build_err_msg("receive_game_update_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# err_msg = self.__build_err_msg("receive_round_result_message")
# raise NotImplementedError(err_msg)
#
# def set_uuid(self, uuid):
# self.uuid = uuid
#
# def respond_to_ask(self, message):
# """Called from Dealer when ask message received from RoundManager"""
# valid_actions, hole_card, round_state = self.__parse_ask_message(message)
# return self.declare_action(valid_actions, hole_card, round_state)
#
# def receive_notification(self, message):
# """Called from Dealer when notification received from RoundManager"""
# msg_type = message["message_type"]
#
# if msg_type == "game_start_message":
# info = self.__parse_game_start_message(message)
# self.receive_game_start_message(info)
#
# elif msg_type == "round_start_message":
# round_count, hole, seats = self.__parse_round_start_message(message)
# self.receive_round_start_message(round_count, hole, seats)
#
# elif msg_type == "street_start_message":
# street, state = self.__parse_street_start_message(message)
# self.receive_street_start_message(street, state)
#
# elif msg_type == "game_update_message":
# new_action, round_state = self.__parse_game_update_message(message)
# self.receive_game_update_message(new_action, round_state)
#
# elif msg_type == "round_result_message":
# winners, hand_info, state = self.__parse_round_result_message(message)
# self.receive_round_result_message(winners, hand_info, state)
#
#
# def __build_err_msg(self, msg):
# return "Your client does not implement [ {0} ] method".format(msg)
#
# def __parse_ask_message(self, message):
# hole_card = message["hole_card"]
# valid_actions = message["valid_actions"]
# round_state = message["round_state"]
# return valid_actions, hole_card, round_state
#
# def __parse_game_start_message(self, message):
# game_info = message["game_information"]
# return game_info
#
# def __parse_round_start_message(self, message):
# round_count = message["round_count"]
# seats = message["seats"]
# hole_card = message["hole_card"]
# return round_count, hole_card, seats
#
# def __parse_street_start_message(self, message):
# street = message["street"]
# round_state = message["round_state"]
# return street, round_state
#
# def __parse_game_update_message(self, message):
# new_action = message["action"]
# round_state = message["round_state"]
# return new_action, round_state
#
# def __parse_round_result_message(self, message):
# winners = message["winners"]
# hand_info = message["hand_info"]
# round_state = message["round_state"]
# return winners, hand_info, round_state
. Output only the next line. | if r <= self.fold_ratio: |
Given snippet: <|code_start|>
class FoldMan(BasePokerPlayer):
def declare_action(self, valid_actions, hole_card, round_state):
return 'fold', 0
def receive_game_start_message(self, game_info):
pass
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pypokerengine.players import BasePokerPlayer
and context:
# Path: pypokerengine/players.py
# class BasePokerPlayer(object):
# """Base Poker client implementation
#
# To create poker client, you need to override this class and
# implement following 7 methods.
#
# - declare_action
# - receive_game_start_message
# - receive_round_start_message
# - receive_street_start_message
# - receive_game_update_message
# - receive_round_result_message
# """
#
# def __init__(self):
# pass
#
# def declare_action(self, valid_actions, hole_card, round_state):
# err_msg = self.__build_err_msg("declare_action")
# raise NotImplementedError(err_msg)
#
# def receive_game_start_message(self, game_info):
# err_msg = self.__build_err_msg("receive_game_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# err_msg = self.__build_err_msg("receive_round_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_street_start_message(self, street, round_state):
# err_msg = self.__build_err_msg("receive_street_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_game_update_message(self, new_action, round_state):
# err_msg = self.__build_err_msg("receive_game_update_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# err_msg = self.__build_err_msg("receive_round_result_message")
# raise NotImplementedError(err_msg)
#
# def set_uuid(self, uuid):
# self.uuid = uuid
#
# def respond_to_ask(self, message):
# """Called from Dealer when ask message received from RoundManager"""
# valid_actions, hole_card, round_state = self.__parse_ask_message(message)
# return self.declare_action(valid_actions, hole_card, round_state)
#
# def receive_notification(self, message):
# """Called from Dealer when notification received from RoundManager"""
# msg_type = message["message_type"]
#
# if msg_type == "game_start_message":
# info = self.__parse_game_start_message(message)
# self.receive_game_start_message(info)
#
# elif msg_type == "round_start_message":
# round_count, hole, seats = self.__parse_round_start_message(message)
# self.receive_round_start_message(round_count, hole, seats)
#
# elif msg_type == "street_start_message":
# street, state = self.__parse_street_start_message(message)
# self.receive_street_start_message(street, state)
#
# elif msg_type == "game_update_message":
# new_action, round_state = self.__parse_game_update_message(message)
# self.receive_game_update_message(new_action, round_state)
#
# elif msg_type == "round_result_message":
# winners, hand_info, state = self.__parse_round_result_message(message)
# self.receive_round_result_message(winners, hand_info, state)
#
#
# def __build_err_msg(self, msg):
# return "Your client does not implement [ {0} ] method".format(msg)
#
# def __parse_ask_message(self, message):
# hole_card = message["hole_card"]
# valid_actions = message["valid_actions"]
# round_state = message["round_state"]
# return valid_actions, hole_card, round_state
#
# def __parse_game_start_message(self, message):
# game_info = message["game_information"]
# return game_info
#
# def __parse_round_start_message(self, message):
# round_count = message["round_count"]
# seats = message["seats"]
# hole_card = message["hole_card"]
# return round_count, hole_card, seats
#
# def __parse_street_start_message(self, message):
# street = message["street"]
# round_state = message["round_state"]
# return street, round_state
#
# def __parse_game_update_message(self, message):
# new_action = message["action"]
# round_state = message["round_state"]
# return new_action, round_state
#
# def __parse_round_result_message(self, message):
# winners = message["winners"]
# hand_info = message["hand_info"]
# round_state = message["round_state"]
# return winners, hand_info, round_state
which might include code, classes, or functions. Output only the next line. | def receive_round_start_message(self, round_count, hole_card, seats): |
Here is a snippet: <|code_start|>
class PayInfoTest(BaseUnitTest):
def setUp(self):
self.info = PayInfo()
def test_update_by_pay(self):
self.info.update_by_pay(10)
self.eq(10, self.info.amount)
self.eq(PayInfo.PAY_TILL_END, self.info.status)
def test_update_by_allin(self):
self.info.update_to_allin()
self.eq(0, self.info.amount)
self.eq(PayInfo.ALLIN, self.info.status)
def test_update_to_fold(self):
self.info.update_to_fold()
<|code_end|>
. Write the next line using the current file imports:
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.pay_info import PayInfo
and context from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/pay_info.py
# class PayInfo:
#
# PAY_TILL_END = 0
# ALLIN = 1
# FOLDED = 2
#
# def __init__(self, amount=0, status=0):
# self.amount = amount
# self.status = status
#
# def update_by_pay(self, amount):
# self.amount += amount
#
# def update_to_fold(self):
# self.status = self.FOLDED
#
# def update_to_allin(self):
# self.status = self.ALLIN
#
# # serialize format : [amount, status]
# def serialize(self):
# return [self.amount, self.status]
#
# @classmethod
# def deserialize(self, serial):
# return self(amount=serial[0], status=serial[1])
, which may include functions, classes, or code. Output only the next line. | self.eq(0, self.info.amount) |
Here is a snippet: <|code_start|>
class PayInfoTest(BaseUnitTest):
def setUp(self):
self.info = PayInfo()
def test_update_by_pay(self):
self.info.update_by_pay(10)
self.eq(10, self.info.amount)
self.eq(PayInfo.PAY_TILL_END, self.info.status)
def test_update_by_allin(self):
self.info.update_to_allin()
self.eq(0, self.info.amount)
self.eq(PayInfo.ALLIN, self.info.status)
def test_update_to_fold(self):
self.info.update_to_fold()
self.eq(0, self.info.amount)
self.eq(PayInfo.FOLDED, self.info.status)
<|code_end|>
. Write the next line using the current file imports:
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.pay_info import PayInfo
and context from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/pay_info.py
# class PayInfo:
#
# PAY_TILL_END = 0
# ALLIN = 1
# FOLDED = 2
#
# def __init__(self, amount=0, status=0):
# self.amount = amount
# self.status = status
#
# def update_by_pay(self, amount):
# self.amount += amount
#
# def update_to_fold(self):
# self.status = self.FOLDED
#
# def update_to_allin(self):
# self.status = self.ALLIN
#
# # serialize format : [amount, status]
# def serialize(self):
# return [self.amount, self.status]
#
# @classmethod
# def deserialize(self, serial):
# return self(amount=serial[0], status=serial[1])
, which may include functions, classes, or code. Output only the next line. | def test_serialization(self): |
Predict the next line for this snippet: <|code_start|>try:
except ImportError:
class MessageSummarizerTest(BaseUnitTest):
def setUp(self):
self.summarizer = MessageSummarizer(verbose=2)
def tearDown(self):
sys.stdout = sys.__stdout__
def test_verbose_silent(self):
summarizer = MessageSummarizer(verbose=0)
self.assertIsNone(summarizer.summarize(game_start_message))
def test_suppress_duplicate_round_start(self):
capture = StringIO()
sys.stdout = capture
msgs = [("uuid1", round_start_message), ("uuid2", round_start_message)]
summarizer = MessageSummarizer(verbose=2)
<|code_end|>
with the help of current file imports:
import sys
from StringIO import StringIO
from io import StringIO
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.dealer import MessageSummarizer
and context from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/dealer.py
# class MessageSummarizer(object):
#
# def __init__(self, verbose):
# self.verbose = verbose
#
# def print_message(self, message):
# print(message)
#
# def summarize_messages(self, raw_messages):
# if self.verbose == 0: return
#
# summaries = [self.summarize(raw_message[1]) for raw_message in raw_messages]
# summaries = [summary for summary in summaries if summary is not None]
# summaries = list(OrderedDict.fromkeys(summaries))
# for summary in summaries: self.print_message(summary)
#
# def summarize(self, message):
# if self.verbose == 0: return None
#
# content = message["message"]
# message_type = content["message_type"]
# if MessageBuilder.GAME_START_MESSAGE == message_type:
# return self.summarize_game_start(content)
# if MessageBuilder.ROUND_START_MESSAGE == message_type:
# return self.summarize_round_start(content)
# if MessageBuilder.STREET_START_MESSAGE == message_type:
# return self.summarize_street_start(content)
# if MessageBuilder.GAME_UPDATE_MESSAGE == message_type:
# return self.summarize_player_action(content)
# if MessageBuilder.ROUND_RESULT_MESSAGE == message_type:
# return self.summarize_round_result(content)
# if MessageBuilder.GAME_RESULT_MESSAGE == message_type:
# return self.summarize_game_result(content)
#
# def summarize_game_start(self, message):
# base = "Started the game with player %s for %d round. (start stack=%s, small blind=%s)"
# names = [player["name"] for player in message["game_information"]["seats"]]
# rule = message["game_information"]["rule"]
# return base % (names, rule["max_round"], rule["initial_stack"], rule["small_blind_amount"])
#
# def summarize_round_start(self, message):
# base = "Started the round %d"
# return base % message["round_count"]
#
# def summarize_street_start(self, message):
# base = 'Street "%s" started. (community card = %s)'
# return base % (message["street"], message["round_state"]["community_card"])
#
# def summarize_player_action(self, message):
# base = '"%s" declared "%s:%s"'
# players = message["round_state"]["seats"]
# action = message["action"]
# player_name = [player["name"] for player in players if player["uuid"] == action["player_uuid"]][0]
# return base % (player_name, action["action"], action["amount"])
#
# def summarize_round_result(self, message):
# base = '"%s" won the round %d (stack = %s)'
# winners = [player["name"] for player in message["winners"]]
# stack = { player["name"]:player["stack"] for player in message["round_state"]["seats"] }
# return base % (winners, message["round_count"], stack)
#
# def summarize_game_result(self, message):
# base = 'Game finished. (stack = %s)'
# stack = { player["name"]:player["stack"] for player in message["game_information"]["seats"] }
# return base % stack
#
# def summairze_blind_level_update(self, round_count, old_ante, new_ante, old_sb_amount, new_sb_amount):
# base = 'Blind level update at round-%d : Ante %s -> %s, SmallBlind %s -> %s'
# return base % (round_count, old_ante, new_ante, old_sb_amount, new_sb_amount)
, which may contain function names, class names, or code. Output only the next line. | summarizer.summarize_messages(msgs) |
Predict the next line for this snippet: <|code_start|> }
street_start_message = {
'message': {
'round_state': {
'dealer_btn': 0, 'street': 'preflop',
'seats': [
{'stack': 95, 'state': 'participating', 'name': 'p1', 'uuid': 'xbwggirmqtqvbpcjzkcdyh'},
{'stack': 90, 'state': 'participating', 'name': 'p2', 'uuid': 'wbjujtrhizogjrliknebeg'}
],
'next_player': 0, 'community_card': [],
'pot': {'main': {'amount': 15}, 'side': []}
},
'street': 'preflop', 'message_type': 'street_start_message'
},
'type': 'notification'
}
game_update_message = {
'message': {
'action': {'player_uuid': 'xbwggirmqtqvbpcjzkcdyh', 'action': 'fold', 'amount': 0},
'round_state': {
'dealer_btn': 0, 'street': 'preflop',
'seats': [
{'stack': 95, 'state': 'folded', 'name': 'p1', 'uuid': 'xbwggirmqtqvbpcjzkcdyh'},
{'stack': 90, 'state': 'participating', 'name': 'p2', 'uuid': 'wbjujtrhizogjrliknebeg'}
],
'next_player': 0, 'community_card': [],
'pot': {'main': {'amount': 15}, 'side': []}
},
<|code_end|>
with the help of current file imports:
import sys
from StringIO import StringIO
from io import StringIO
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.dealer import MessageSummarizer
and context from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/dealer.py
# class MessageSummarizer(object):
#
# def __init__(self, verbose):
# self.verbose = verbose
#
# def print_message(self, message):
# print(message)
#
# def summarize_messages(self, raw_messages):
# if self.verbose == 0: return
#
# summaries = [self.summarize(raw_message[1]) for raw_message in raw_messages]
# summaries = [summary for summary in summaries if summary is not None]
# summaries = list(OrderedDict.fromkeys(summaries))
# for summary in summaries: self.print_message(summary)
#
# def summarize(self, message):
# if self.verbose == 0: return None
#
# content = message["message"]
# message_type = content["message_type"]
# if MessageBuilder.GAME_START_MESSAGE == message_type:
# return self.summarize_game_start(content)
# if MessageBuilder.ROUND_START_MESSAGE == message_type:
# return self.summarize_round_start(content)
# if MessageBuilder.STREET_START_MESSAGE == message_type:
# return self.summarize_street_start(content)
# if MessageBuilder.GAME_UPDATE_MESSAGE == message_type:
# return self.summarize_player_action(content)
# if MessageBuilder.ROUND_RESULT_MESSAGE == message_type:
# return self.summarize_round_result(content)
# if MessageBuilder.GAME_RESULT_MESSAGE == message_type:
# return self.summarize_game_result(content)
#
# def summarize_game_start(self, message):
# base = "Started the game with player %s for %d round. (start stack=%s, small blind=%s)"
# names = [player["name"] for player in message["game_information"]["seats"]]
# rule = message["game_information"]["rule"]
# return base % (names, rule["max_round"], rule["initial_stack"], rule["small_blind_amount"])
#
# def summarize_round_start(self, message):
# base = "Started the round %d"
# return base % message["round_count"]
#
# def summarize_street_start(self, message):
# base = 'Street "%s" started. (community card = %s)'
# return base % (message["street"], message["round_state"]["community_card"])
#
# def summarize_player_action(self, message):
# base = '"%s" declared "%s:%s"'
# players = message["round_state"]["seats"]
# action = message["action"]
# player_name = [player["name"] for player in players if player["uuid"] == action["player_uuid"]][0]
# return base % (player_name, action["action"], action["amount"])
#
# def summarize_round_result(self, message):
# base = '"%s" won the round %d (stack = %s)'
# winners = [player["name"] for player in message["winners"]]
# stack = { player["name"]:player["stack"] for player in message["round_state"]["seats"] }
# return base % (winners, message["round_count"], stack)
#
# def summarize_game_result(self, message):
# base = 'Game finished. (stack = %s)'
# stack = { player["name"]:player["stack"] for player in message["game_information"]["seats"] }
# return base % stack
#
# def summairze_blind_level_update(self, round_count, old_ante, new_ante, old_sb_amount, new_sb_amount):
# base = 'Blind level update at round-%d : Ante %s -> %s, SmallBlind %s -> %s'
# return base % (round_count, old_ante, new_ante, old_sb_amount, new_sb_amount)
, which may contain function names, class names, or code. Output only the next line. | 'message_type': 'game_update_message', |
Next line prediction: <|code_start|>
class Table:
def __init__(self, cheat_deck=None):
self.dealer_btn = 0
self._blind_pos = None
self.seats = Seats()
self.deck = cheat_deck if cheat_deck else Deck()
self._community_card = []
def set_blind_pos(self, sb_pos, bb_pos):
self._blind_pos = [sb_pos, bb_pos]
def sb_pos(self):
if self._blind_pos is None: raise Exception("blind position is not yet set")
return self._blind_pos[0]
def bb_pos(self):
if self._blind_pos is None: raise Exception("blind position is not yet set")
return self._blind_pos[1]
def get_community_card(self):
return self._community_card[::]
def add_community_card(self, card):
if len(self._community_card) == 5:
raise ValueError(self.__exceed_card_size_msg)
<|code_end|>
. Use current file imports:
(from pypokerengine.engine.card import Card
from pypokerengine.engine.seats import Seats
from pypokerengine.engine.deck import Deck)
and context including class names, function names, or small code snippets from other files:
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/seats.py
# class Seats:
#
# def __init__(self):
# self.players = []
#
# def sitdown(self, player):
# self.players.append(player)
#
# def size(self):
# return len(self.players)
#
# def count_active_players(self):
# return len([p for p in self.players if p.is_active()])
#
# def count_ask_wait_players(self):
# return len([p for p in self.players if p.is_waiting_ask()])
#
# def serialize(self):
# return [player.serialize() for player in self.players]
#
# @classmethod
# def deserialize(self, serial):
# seats = self()
# seats.players = [Player.deserialize(s) for s in serial]
# return seats
#
# Path: pypokerengine/engine/deck.py
# class Deck:
#
# def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
# self.cheat = cheat
# self.cheat_card_ids = cheat_card_ids
# self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
#
# def draw_card(self):
# return self.deck.pop()
#
# def draw_cards(self, num):
# return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
#
# def size(self):
# return len(self.deck)
#
# def restore(self):
# self.deck = self.__setup()
#
# def shuffle(self):
# if not self.cheat:
# random.shuffle(self.deck)
#
# # serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
# def serialize(self):
# return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]]
#
# @classmethod
# def deserialize(self, serial):
# cheat, cheat_card_ids, deck_ids = serial
# return self(deck_ids=deck_ids, cheat=cheat, cheat_card_ids=cheat_card_ids)
#
# def __setup(self):
# return self.__setup_cheat_deck() if self.cheat else self.__setup_52_cards()
#
# def __setup_52_cards(self):
# return [Card.from_id(cid) for cid in range(1,53)]
#
# def __setup_cheat_deck(self):
# cards = [Card.from_id(cid) for cid in self.cheat_card_ids]
# return cards[::-1]
. Output only the next line. | self._community_card.append(card) |
Given snippet: <|code_start|>
class Table:
def __init__(self, cheat_deck=None):
self.dealer_btn = 0
self._blind_pos = None
self.seats = Seats()
self.deck = cheat_deck if cheat_deck else Deck()
self._community_card = []
def set_blind_pos(self, sb_pos, bb_pos):
self._blind_pos = [sb_pos, bb_pos]
def sb_pos(self):
if self._blind_pos is None: raise Exception("blind position is not yet set")
return self._blind_pos[0]
def bb_pos(self):
if self._blind_pos is None: raise Exception("blind position is not yet set")
return self._blind_pos[1]
def get_community_card(self):
return self._community_card[::]
def add_community_card(self, card):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pypokerengine.engine.card import Card
from pypokerengine.engine.seats import Seats
from pypokerengine.engine.deck import Deck
and context:
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/seats.py
# class Seats:
#
# def __init__(self):
# self.players = []
#
# def sitdown(self, player):
# self.players.append(player)
#
# def size(self):
# return len(self.players)
#
# def count_active_players(self):
# return len([p for p in self.players if p.is_active()])
#
# def count_ask_wait_players(self):
# return len([p for p in self.players if p.is_waiting_ask()])
#
# def serialize(self):
# return [player.serialize() for player in self.players]
#
# @classmethod
# def deserialize(self, serial):
# seats = self()
# seats.players = [Player.deserialize(s) for s in serial]
# return seats
#
# Path: pypokerengine/engine/deck.py
# class Deck:
#
# def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
# self.cheat = cheat
# self.cheat_card_ids = cheat_card_ids
# self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
#
# def draw_card(self):
# return self.deck.pop()
#
# def draw_cards(self, num):
# return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
#
# def size(self):
# return len(self.deck)
#
# def restore(self):
# self.deck = self.__setup()
#
# def shuffle(self):
# if not self.cheat:
# random.shuffle(self.deck)
#
# # serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
# def serialize(self):
# return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]]
#
# @classmethod
# def deserialize(self, serial):
# cheat, cheat_card_ids, deck_ids = serial
# return self(deck_ids=deck_ids, cheat=cheat, cheat_card_ids=cheat_card_ids)
#
# def __setup(self):
# return self.__setup_cheat_deck() if self.cheat else self.__setup_52_cards()
#
# def __setup_52_cards(self):
# return [Card.from_id(cid) for cid in range(1,53)]
#
# def __setup_cheat_deck(self):
# cards = [Card.from_id(cid) for cid in self.cheat_card_ids]
# return cards[::-1]
which might include code, classes, or functions. Output only the next line. | if len(self._community_card) == 5: |
Given snippet: <|code_start|> self.dealer_btn = 0
self._blind_pos = None
self.seats = Seats()
self.deck = cheat_deck if cheat_deck else Deck()
self._community_card = []
def set_blind_pos(self, sb_pos, bb_pos):
self._blind_pos = [sb_pos, bb_pos]
def sb_pos(self):
if self._blind_pos is None: raise Exception("blind position is not yet set")
return self._blind_pos[0]
def bb_pos(self):
if self._blind_pos is None: raise Exception("blind position is not yet set")
return self._blind_pos[1]
def get_community_card(self):
return self._community_card[::]
def add_community_card(self, card):
if len(self._community_card) == 5:
raise ValueError(self.__exceed_card_size_msg)
self._community_card.append(card)
def reset(self):
self.deck.restore()
self._community_card = []
for player in self.seats.players:
player.clear_holecard()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pypokerengine.engine.card import Card
from pypokerengine.engine.seats import Seats
from pypokerengine.engine.deck import Deck
and context:
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/seats.py
# class Seats:
#
# def __init__(self):
# self.players = []
#
# def sitdown(self, player):
# self.players.append(player)
#
# def size(self):
# return len(self.players)
#
# def count_active_players(self):
# return len([p for p in self.players if p.is_active()])
#
# def count_ask_wait_players(self):
# return len([p for p in self.players if p.is_waiting_ask()])
#
# def serialize(self):
# return [player.serialize() for player in self.players]
#
# @classmethod
# def deserialize(self, serial):
# seats = self()
# seats.players = [Player.deserialize(s) for s in serial]
# return seats
#
# Path: pypokerengine/engine/deck.py
# class Deck:
#
# def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
# self.cheat = cheat
# self.cheat_card_ids = cheat_card_ids
# self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
#
# def draw_card(self):
# return self.deck.pop()
#
# def draw_cards(self, num):
# return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
#
# def size(self):
# return len(self.deck)
#
# def restore(self):
# self.deck = self.__setup()
#
# def shuffle(self):
# if not self.cheat:
# random.shuffle(self.deck)
#
# # serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
# def serialize(self):
# return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]]
#
# @classmethod
# def deserialize(self, serial):
# cheat, cheat_card_ids, deck_ids = serial
# return self(deck_ids=deck_ids, cheat=cheat, cheat_card_ids=cheat_card_ids)
#
# def __setup(self):
# return self.__setup_cheat_deck() if self.cheat else self.__setup_52_cards()
#
# def __setup_52_cards(self):
# return [Card.from_id(cid) for cid in range(1,53)]
#
# def __setup_cheat_deck(self):
# cards = [Card.from_id(cid) for cid in self.cheat_card_ids]
# return cards[::-1]
which might include code, classes, or functions. Output only the next line. | player.clear_action_histories() |
Given the code snippet: <|code_start|>
class HonestPlayer(BasePokerPlayer):
def declare_action(self, valid_actions, hole_card, round_state):
community_card = round_state['community_card']
win_rate = estimate_hole_card_win_rate(
nb_simulation=NB_SIMULATION,
nb_player=self.nb_player,
hole_card=gen_cards(hole_card),
community_card=gen_cards(community_card)
)
if win_rate >= 1.0 / self.nb_player:
action = valid_actions[1] # fetch CALL action info
else:
action = valid_actions[0] # fetch FOLD action info
return action['action'], action['amount']
def receive_game_start_message(self, game_info):
self.nb_player = game_info['player_num']
def receive_round_start_message(self, round_count, hole_card, seats):
pass
def receive_street_start_message(self, street, round_state):
pass
def receive_game_update_message(self, action, round_state):
pass
def receive_round_result_message(self, winners, hand_info, round_state):
<|code_end|>
, generate the next line using the imports in this file:
from pypokerengine.players import BasePokerPlayer
from pypokerengine.utils.card_utils import gen_cards, estimate_hole_card_win_rate
and context (functions, classes, or occasionally code) from other files:
# Path: pypokerengine/players.py
# class BasePokerPlayer(object):
# """Base Poker client implementation
#
# To create poker client, you need to override this class and
# implement following 7 methods.
#
# - declare_action
# - receive_game_start_message
# - receive_round_start_message
# - receive_street_start_message
# - receive_game_update_message
# - receive_round_result_message
# """
#
# def __init__(self):
# pass
#
# def declare_action(self, valid_actions, hole_card, round_state):
# err_msg = self.__build_err_msg("declare_action")
# raise NotImplementedError(err_msg)
#
# def receive_game_start_message(self, game_info):
# err_msg = self.__build_err_msg("receive_game_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# err_msg = self.__build_err_msg("receive_round_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_street_start_message(self, street, round_state):
# err_msg = self.__build_err_msg("receive_street_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_game_update_message(self, new_action, round_state):
# err_msg = self.__build_err_msg("receive_game_update_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# err_msg = self.__build_err_msg("receive_round_result_message")
# raise NotImplementedError(err_msg)
#
# def set_uuid(self, uuid):
# self.uuid = uuid
#
# def respond_to_ask(self, message):
# """Called from Dealer when ask message received from RoundManager"""
# valid_actions, hole_card, round_state = self.__parse_ask_message(message)
# return self.declare_action(valid_actions, hole_card, round_state)
#
# def receive_notification(self, message):
# """Called from Dealer when notification received from RoundManager"""
# msg_type = message["message_type"]
#
# if msg_type == "game_start_message":
# info = self.__parse_game_start_message(message)
# self.receive_game_start_message(info)
#
# elif msg_type == "round_start_message":
# round_count, hole, seats = self.__parse_round_start_message(message)
# self.receive_round_start_message(round_count, hole, seats)
#
# elif msg_type == "street_start_message":
# street, state = self.__parse_street_start_message(message)
# self.receive_street_start_message(street, state)
#
# elif msg_type == "game_update_message":
# new_action, round_state = self.__parse_game_update_message(message)
# self.receive_game_update_message(new_action, round_state)
#
# elif msg_type == "round_result_message":
# winners, hand_info, state = self.__parse_round_result_message(message)
# self.receive_round_result_message(winners, hand_info, state)
#
#
# def __build_err_msg(self, msg):
# return "Your client does not implement [ {0} ] method".format(msg)
#
# def __parse_ask_message(self, message):
# hole_card = message["hole_card"]
# valid_actions = message["valid_actions"]
# round_state = message["round_state"]
# return valid_actions, hole_card, round_state
#
# def __parse_game_start_message(self, message):
# game_info = message["game_information"]
# return game_info
#
# def __parse_round_start_message(self, message):
# round_count = message["round_count"]
# seats = message["seats"]
# hole_card = message["hole_card"]
# return round_count, hole_card, seats
#
# def __parse_street_start_message(self, message):
# street = message["street"]
# round_state = message["round_state"]
# return street, round_state
#
# def __parse_game_update_message(self, message):
# new_action = message["action"]
# round_state = message["round_state"]
# return new_action, round_state
#
# def __parse_round_result_message(self, message):
# winners = message["winners"]
# hand_info = message["hand_info"]
# round_state = message["round_state"]
# return winners, hand_info, round_state
#
# Path: pypokerengine/utils/card_utils.py
# def gen_cards(cards_str):
# return [Card.from_str(s) for s in cards_str]
#
# def estimate_hole_card_win_rate(nb_simulation, nb_player, hole_card, community_card=None):
# if not community_card: community_card = []
# win_count = sum([_montecarlo_simulation(nb_player, hole_card, community_card) for _ in range(nb_simulation)])
# return 1.0 * win_count / nb_simulation
. Output only the next line. | pass |
Predict the next line after this snippet: <|code_start|>
NB_SIMULATION = 1000
class HonestPlayer(BasePokerPlayer):
def declare_action(self, valid_actions, hole_card, round_state):
community_card = round_state['community_card']
win_rate = estimate_hole_card_win_rate(
nb_simulation=NB_SIMULATION,
nb_player=self.nb_player,
hole_card=gen_cards(hole_card),
community_card=gen_cards(community_card)
)
if win_rate >= 1.0 / self.nb_player:
action = valid_actions[1] # fetch CALL action info
else:
action = valid_actions[0] # fetch FOLD action info
return action['action'], action['amount']
def receive_game_start_message(self, game_info):
self.nb_player = game_info['player_num']
def receive_round_start_message(self, round_count, hole_card, seats):
pass
def receive_street_start_message(self, street, round_state):
pass
def receive_game_update_message(self, action, round_state):
<|code_end|>
using the current file's imports:
from pypokerengine.players import BasePokerPlayer
from pypokerengine.utils.card_utils import gen_cards, estimate_hole_card_win_rate
and any relevant context from other files:
# Path: pypokerengine/players.py
# class BasePokerPlayer(object):
# """Base Poker client implementation
#
# To create poker client, you need to override this class and
# implement following 7 methods.
#
# - declare_action
# - receive_game_start_message
# - receive_round_start_message
# - receive_street_start_message
# - receive_game_update_message
# - receive_round_result_message
# """
#
# def __init__(self):
# pass
#
# def declare_action(self, valid_actions, hole_card, round_state):
# err_msg = self.__build_err_msg("declare_action")
# raise NotImplementedError(err_msg)
#
# def receive_game_start_message(self, game_info):
# err_msg = self.__build_err_msg("receive_game_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# err_msg = self.__build_err_msg("receive_round_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_street_start_message(self, street, round_state):
# err_msg = self.__build_err_msg("receive_street_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_game_update_message(self, new_action, round_state):
# err_msg = self.__build_err_msg("receive_game_update_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# err_msg = self.__build_err_msg("receive_round_result_message")
# raise NotImplementedError(err_msg)
#
# def set_uuid(self, uuid):
# self.uuid = uuid
#
# def respond_to_ask(self, message):
# """Called from Dealer when ask message received from RoundManager"""
# valid_actions, hole_card, round_state = self.__parse_ask_message(message)
# return self.declare_action(valid_actions, hole_card, round_state)
#
# def receive_notification(self, message):
# """Called from Dealer when notification received from RoundManager"""
# msg_type = message["message_type"]
#
# if msg_type == "game_start_message":
# info = self.__parse_game_start_message(message)
# self.receive_game_start_message(info)
#
# elif msg_type == "round_start_message":
# round_count, hole, seats = self.__parse_round_start_message(message)
# self.receive_round_start_message(round_count, hole, seats)
#
# elif msg_type == "street_start_message":
# street, state = self.__parse_street_start_message(message)
# self.receive_street_start_message(street, state)
#
# elif msg_type == "game_update_message":
# new_action, round_state = self.__parse_game_update_message(message)
# self.receive_game_update_message(new_action, round_state)
#
# elif msg_type == "round_result_message":
# winners, hand_info, state = self.__parse_round_result_message(message)
# self.receive_round_result_message(winners, hand_info, state)
#
#
# def __build_err_msg(self, msg):
# return "Your client does not implement [ {0} ] method".format(msg)
#
# def __parse_ask_message(self, message):
# hole_card = message["hole_card"]
# valid_actions = message["valid_actions"]
# round_state = message["round_state"]
# return valid_actions, hole_card, round_state
#
# def __parse_game_start_message(self, message):
# game_info = message["game_information"]
# return game_info
#
# def __parse_round_start_message(self, message):
# round_count = message["round_count"]
# seats = message["seats"]
# hole_card = message["hole_card"]
# return round_count, hole_card, seats
#
# def __parse_street_start_message(self, message):
# street = message["street"]
# round_state = message["round_state"]
# return street, round_state
#
# def __parse_game_update_message(self, message):
# new_action = message["action"]
# round_state = message["round_state"]
# return new_action, round_state
#
# def __parse_round_result_message(self, message):
# winners = message["winners"]
# hand_info = message["hand_info"]
# round_state = message["round_state"]
# return winners, hand_info, round_state
#
# Path: pypokerengine/utils/card_utils.py
# def gen_cards(cards_str):
# return [Card.from_str(s) for s in cards_str]
#
# def estimate_hole_card_win_rate(nb_simulation, nb_player, hole_card, community_card=None):
# if not community_card: community_card = []
# win_count = sum([_montecarlo_simulation(nb_player, hole_card, community_card) for _ in range(nb_simulation)])
# return 1.0 * win_count / nb_simulation
. Output only the next line. | pass |
Here is a snippet: <|code_start|>
NB_SIMULATION = 1000
class HonestPlayer(BasePokerPlayer):
def declare_action(self, valid_actions, hole_card, round_state):
community_card = round_state['community_card']
win_rate = estimate_hole_card_win_rate(
nb_simulation=NB_SIMULATION,
nb_player=self.nb_player,
hole_card=gen_cards(hole_card),
community_card=gen_cards(community_card)
)
if win_rate >= 1.0 / self.nb_player:
action = valid_actions[1] # fetch CALL action info
else:
action = valid_actions[0] # fetch FOLD action info
return action['action'], action['amount']
def receive_game_start_message(self, game_info):
self.nb_player = game_info['player_num']
def receive_round_start_message(self, round_count, hole_card, seats):
pass
<|code_end|>
. Write the next line using the current file imports:
from pypokerengine.players import BasePokerPlayer
from pypokerengine.utils.card_utils import gen_cards, estimate_hole_card_win_rate
and context from other files:
# Path: pypokerengine/players.py
# class BasePokerPlayer(object):
# """Base Poker client implementation
#
# To create poker client, you need to override this class and
# implement following 7 methods.
#
# - declare_action
# - receive_game_start_message
# - receive_round_start_message
# - receive_street_start_message
# - receive_game_update_message
# - receive_round_result_message
# """
#
# def __init__(self):
# pass
#
# def declare_action(self, valid_actions, hole_card, round_state):
# err_msg = self.__build_err_msg("declare_action")
# raise NotImplementedError(err_msg)
#
# def receive_game_start_message(self, game_info):
# err_msg = self.__build_err_msg("receive_game_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# err_msg = self.__build_err_msg("receive_round_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_street_start_message(self, street, round_state):
# err_msg = self.__build_err_msg("receive_street_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_game_update_message(self, new_action, round_state):
# err_msg = self.__build_err_msg("receive_game_update_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# err_msg = self.__build_err_msg("receive_round_result_message")
# raise NotImplementedError(err_msg)
#
# def set_uuid(self, uuid):
# self.uuid = uuid
#
# def respond_to_ask(self, message):
# """Called from Dealer when ask message received from RoundManager"""
# valid_actions, hole_card, round_state = self.__parse_ask_message(message)
# return self.declare_action(valid_actions, hole_card, round_state)
#
# def receive_notification(self, message):
# """Called from Dealer when notification received from RoundManager"""
# msg_type = message["message_type"]
#
# if msg_type == "game_start_message":
# info = self.__parse_game_start_message(message)
# self.receive_game_start_message(info)
#
# elif msg_type == "round_start_message":
# round_count, hole, seats = self.__parse_round_start_message(message)
# self.receive_round_start_message(round_count, hole, seats)
#
# elif msg_type == "street_start_message":
# street, state = self.__parse_street_start_message(message)
# self.receive_street_start_message(street, state)
#
# elif msg_type == "game_update_message":
# new_action, round_state = self.__parse_game_update_message(message)
# self.receive_game_update_message(new_action, round_state)
#
# elif msg_type == "round_result_message":
# winners, hand_info, state = self.__parse_round_result_message(message)
# self.receive_round_result_message(winners, hand_info, state)
#
#
# def __build_err_msg(self, msg):
# return "Your client does not implement [ {0} ] method".format(msg)
#
# def __parse_ask_message(self, message):
# hole_card = message["hole_card"]
# valid_actions = message["valid_actions"]
# round_state = message["round_state"]
# return valid_actions, hole_card, round_state
#
# def __parse_game_start_message(self, message):
# game_info = message["game_information"]
# return game_info
#
# def __parse_round_start_message(self, message):
# round_count = message["round_count"]
# seats = message["seats"]
# hole_card = message["hole_card"]
# return round_count, hole_card, seats
#
# def __parse_street_start_message(self, message):
# street = message["street"]
# round_state = message["round_state"]
# return street, round_state
#
# def __parse_game_update_message(self, message):
# new_action = message["action"]
# round_state = message["round_state"]
# return new_action, round_state
#
# def __parse_round_result_message(self, message):
# winners = message["winners"]
# hand_info = message["hand_info"]
# round_state = message["round_state"]
# return winners, hand_info, round_state
#
# Path: pypokerengine/utils/card_utils.py
# def gen_cards(cards_str):
# return [Card.from_str(s) for s in cards_str]
#
# def estimate_hole_card_win_rate(nb_simulation, nb_player, hole_card, community_card=None):
# if not community_card: community_card = []
# win_count = sum([_montecarlo_simulation(nb_player, hole_card, community_card) for _ in range(nb_simulation)])
# return 1.0 * win_count / nb_simulation
, which may include functions, classes, or code. Output only the next line. | def receive_street_start_message(self, street, round_state): |
Continue the code snippet: <|code_start|>
def test_start_poker(self):
config = G.setup_config(1, 100, 10)
config.register_player("p1", FoldMan())
config.register_player("p2", FoldMan())
result = G.start_poker(config)
p1, p2 = [result["players"][i] for i in range(2)]
self.eq("p1", p1["name"])
self.eq(110, p1["stack"])
self.eq("p2", p2["name"])
self.eq(90, p2["stack"])
def test_start_poker_with_ante(self):
config = G.setup_config(1, 100, 10, 15)
config.register_player("p1", FoldMan())
config.register_player("p2", FoldMan())
result = G.start_poker(config)
p1, p2 = [result["players"][i] for i in range(2)]
self.eq("p1", p1["name"])
self.eq(125, p1["stack"])
self.eq("p2", p2["name"])
self.eq(75, p2["stack"])
def test_set_blind_structure(self):
config = G.setup_config(1, 100, 10)
config.register_player("p1", FoldMan())
config.register_player("p2", FoldMan())
config.set_blind_structure({ 1: { "ante":5, "small_blind":10 } })
result = G.start_poker(config)
p1, p2 = [result["players"][i] for i in range(2)]
<|code_end|>
. Use current file imports:
import pypokerengine.api.game as G
from nose.tools import raises
from tests.base_unittest import BaseUnitTest
from examples.players.fold_man import FoldMan
and context (classes, functions, or code) from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: examples/players/fold_man.py
# class FoldMan(BasePokerPlayer):
#
# def declare_action(self, valid_actions, hole_card, round_state):
# return 'fold', 0
#
# def receive_game_start_message(self, game_info):
# pass
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# pass
#
# def receive_street_start_message(self, street, round_state):
# pass
#
# def receive_game_update_message(self, new_action, round_state):
# pass
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# pass
. Output only the next line. | self.eq(115, p1["stack"]) |
Here is a snippet: <|code_start|>
class GameTest(BaseUnitTest):
def test_start_poker(self):
config = G.setup_config(1, 100, 10)
config.register_player("p1", FoldMan())
config.register_player("p2", FoldMan())
result = G.start_poker(config)
p1, p2 = [result["players"][i] for i in range(2)]
self.eq("p1", p1["name"])
self.eq(110, p1["stack"])
self.eq("p2", p2["name"])
self.eq(90, p2["stack"])
<|code_end|>
. Write the next line using the current file imports:
import pypokerengine.api.game as G
from nose.tools import raises
from tests.base_unittest import BaseUnitTest
from examples.players.fold_man import FoldMan
and context from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: examples/players/fold_man.py
# class FoldMan(BasePokerPlayer):
#
# def declare_action(self, valid_actions, hole_card, round_state):
# return 'fold', 0
#
# def receive_game_start_message(self, game_info):
# pass
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# pass
#
# def receive_street_start_message(self, street, round_state):
# pass
#
# def receive_game_update_message(self, new_action, round_state):
# pass
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# pass
, which may include functions, classes, or code. Output only the next line. | def test_start_poker_with_ante(self): |
Here is a snippet: <|code_start|>
def test_gen_deck(self):
deck = U.gen_deck()
self.eq(list(range(1, 53)), [card.to_id() for card in deck.deck])
def test_gen_deck_without_some_card(self):
expected = Deck(deck_ids=range(2, 52))
exclude_obj = [Card.from_id(1), Card.from_id(52)]
exclude_str = [str(card) for card in exclude_obj]
self.eq(expected.serialize(), U.gen_deck(exclude_obj).serialize())
self.eq(expected.serialize(), U.gen_deck(exclude_str).serialize())
def test_evaluate_hand(self):
community = [
Card(Card.CLUB, 3),
Card(Card.CLUB, 7),
Card(Card.CLUB, 10),
Card(Card.DIAMOND, 5),
Card(Card.DIAMOND, 6)
]
hole = [
Card(Card.CLUB, 9),
Card(Card.DIAMOND, 2)
]
expected = {
"hand":"HIGHCARD",
"strength": 37522
}
self.eq(expected, U.evaluate_hand(hole, community))
<|code_end|>
. Write the next line using the current file imports:
import pypokerengine.utils.card_utils as U
from mock import patch
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.card import Card
from pypokerengine.engine.deck import Deck
and context from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/deck.py
# class Deck:
#
# def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
# self.cheat = cheat
# self.cheat_card_ids = cheat_card_ids
# self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
#
# def draw_card(self):
# return self.deck.pop()
#
# def draw_cards(self, num):
# return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
#
# def size(self):
# return len(self.deck)
#
# def restore(self):
# self.deck = self.__setup()
#
# def shuffle(self):
# if not self.cheat:
# random.shuffle(self.deck)
#
# # serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
# def serialize(self):
# return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]]
#
# @classmethod
# def deserialize(self, serial):
# cheat, cheat_card_ids, deck_ids = serial
# return self(deck_ids=deck_ids, cheat=cheat, cheat_card_ids=cheat_card_ids)
#
# def __setup(self):
# return self.__setup_cheat_deck() if self.cheat else self.__setup_52_cards()
#
# def __setup_52_cards(self):
# return [Card.from_id(cid) for cid in range(1,53)]
#
# def __setup_cheat_deck(self):
# cards = [Card.from_id(cid) for cid in self.cheat_card_ids]
# return cards[::-1]
, which may include functions, classes, or code. Output only the next line. | def Any(cls): |
Based on the snippet: <|code_start|>
def test_gen_deck_without_some_card(self):
expected = Deck(deck_ids=range(2, 52))
exclude_obj = [Card.from_id(1), Card.from_id(52)]
exclude_str = [str(card) for card in exclude_obj]
self.eq(expected.serialize(), U.gen_deck(exclude_obj).serialize())
self.eq(expected.serialize(), U.gen_deck(exclude_str).serialize())
def test_evaluate_hand(self):
community = [
Card(Card.CLUB, 3),
Card(Card.CLUB, 7),
Card(Card.CLUB, 10),
Card(Card.DIAMOND, 5),
Card(Card.DIAMOND, 6)
]
hole = [
Card(Card.CLUB, 9),
Card(Card.DIAMOND, 2)
]
expected = {
"hand":"HIGHCARD",
"strength": 37522
}
self.eq(expected, U.evaluate_hand(hole, community))
def Any(cls):
class Any(cls):
def __eq__(self, other):
return True
<|code_end|>
, predict the immediate next line with the help of imports:
import pypokerengine.utils.card_utils as U
from mock import patch
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.card import Card
from pypokerengine.engine.deck import Deck
and context (classes, functions, sometimes code) from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/deck.py
# class Deck:
#
# def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
# self.cheat = cheat
# self.cheat_card_ids = cheat_card_ids
# self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
#
# def draw_card(self):
# return self.deck.pop()
#
# def draw_cards(self, num):
# return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
#
# def size(self):
# return len(self.deck)
#
# def restore(self):
# self.deck = self.__setup()
#
# def shuffle(self):
# if not self.cheat:
# random.shuffle(self.deck)
#
# # serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
# def serialize(self):
# return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]]
#
# @classmethod
# def deserialize(self, serial):
# cheat, cheat_card_ids, deck_ids = serial
# return self(deck_ids=deck_ids, cheat=cheat, cheat_card_ids=cheat_card_ids)
#
# def __setup(self):
# return self.__setup_cheat_deck() if self.cheat else self.__setup_52_cards()
#
# def __setup_52_cards(self):
# return [Card.from_id(cid) for cid in range(1,53)]
#
# def __setup_cheat_deck(self):
# cards = [Card.from_id(cid) for cid in self.cheat_card_ids]
# return cards[::-1]
. Output only the next line. | return Any() |
Here is a snippet: <|code_start|>
class CardUtilsTest(BaseUnitTest):
def test_gen_cards(self):
self.eq([Card(rank=1, suit=2), Card(rank=12, suit=4)], U.gen_cards(["CA", "DQ"]))
self.eq([Card(rank=9, suit=8), Card(rank=10, suit=2)], U.gen_cards(["H9", "CT"]))
self.eq([Card(rank=11, suit=16), Card(rank=13, suit=4)], U.gen_cards(["SJ", "DK"]))
def test_montecarlo_simulation(self):
my_cards = U.gen_cards(["D6", "D2"])
<|code_end|>
. Write the next line using the current file imports:
import pypokerengine.utils.card_utils as U
from mock import patch
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.card import Card
from pypokerengine.engine.deck import Deck
and context from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/deck.py
# class Deck:
#
# def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
# self.cheat = cheat
# self.cheat_card_ids = cheat_card_ids
# self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
#
# def draw_card(self):
# return self.deck.pop()
#
# def draw_cards(self, num):
# return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
#
# def size(self):
# return len(self.deck)
#
# def restore(self):
# self.deck = self.__setup()
#
# def shuffle(self):
# if not self.cheat:
# random.shuffle(self.deck)
#
# # serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
# def serialize(self):
# return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]]
#
# @classmethod
# def deserialize(self, serial):
# cheat, cheat_card_ids, deck_ids = serial
# return self(deck_ids=deck_ids, cheat=cheat, cheat_card_ids=cheat_card_ids)
#
# def __setup(self):
# return self.__setup_cheat_deck() if self.cheat else self.__setup_52_cards()
#
# def __setup_52_cards(self):
# return [Card.from_id(cid) for cid in range(1,53)]
#
# def __setup_cheat_deck(self):
# cards = [Card.from_id(cid) for cid in self.cheat_card_ids]
# return cards[::-1]
, which may include functions, classes, or code. Output only the next line. | community = U.gen_cards(['D5', 'D9', 'H6', 'CK']) |
Predict the next line for this snippet: <|code_start|> def __wait_until_input(self):
raw_input("Enter some key to continue ...")
def __gen_raw_input_wrapper(self):
return lambda msg: raw_input(msg)
def __receive_action_from_console(self, valid_actions):
flg = self.input_receiver('Enter f(fold), c(call), r(raise).\n >> ')
if flg in self.__gen_valid_flg(valid_actions):
if flg == 'f':
return valid_actions[0]['action'], valid_actions[0]['amount']
elif flg == 'c':
return valid_actions[1]['action'], valid_actions[1]['amount']
elif flg == 'r':
valid_amounts = valid_actions[2]['amount']
raise_amount = self.__receive_raise_amount_from_console(valid_amounts['min'], valid_amounts['max'])
return valid_actions[2]['action'], raise_amount
else:
return self.__receive_action_from_console(valid_actions)
def __gen_valid_flg(self, valid_actions):
flgs = ['f', 'c']
is_raise_possible = valid_actions[2]['amount']['min'] != -1
if is_raise_possible:
flgs.append('r')
return flgs
def __receive_raise_amount_from_console(self, min_amount, max_amount):
raw_amount = self.input_receiver("valid raise range = [%d, %d]" % (min_amount, max_amount))
try:
<|code_end|>
with the help of current file imports:
import pypokerengine.utils.visualize_utils as U
from pypokerengine.players import BasePokerPlayer
and context from other files:
# Path: pypokerengine/players.py
# class BasePokerPlayer(object):
# """Base Poker client implementation
#
# To create poker client, you need to override this class and
# implement following 7 methods.
#
# - declare_action
# - receive_game_start_message
# - receive_round_start_message
# - receive_street_start_message
# - receive_game_update_message
# - receive_round_result_message
# """
#
# def __init__(self):
# pass
#
# def declare_action(self, valid_actions, hole_card, round_state):
# err_msg = self.__build_err_msg("declare_action")
# raise NotImplementedError(err_msg)
#
# def receive_game_start_message(self, game_info):
# err_msg = self.__build_err_msg("receive_game_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# err_msg = self.__build_err_msg("receive_round_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_street_start_message(self, street, round_state):
# err_msg = self.__build_err_msg("receive_street_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_game_update_message(self, new_action, round_state):
# err_msg = self.__build_err_msg("receive_game_update_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# err_msg = self.__build_err_msg("receive_round_result_message")
# raise NotImplementedError(err_msg)
#
# def set_uuid(self, uuid):
# self.uuid = uuid
#
# def respond_to_ask(self, message):
# """Called from Dealer when ask message received from RoundManager"""
# valid_actions, hole_card, round_state = self.__parse_ask_message(message)
# return self.declare_action(valid_actions, hole_card, round_state)
#
# def receive_notification(self, message):
# """Called from Dealer when notification received from RoundManager"""
# msg_type = message["message_type"]
#
# if msg_type == "game_start_message":
# info = self.__parse_game_start_message(message)
# self.receive_game_start_message(info)
#
# elif msg_type == "round_start_message":
# round_count, hole, seats = self.__parse_round_start_message(message)
# self.receive_round_start_message(round_count, hole, seats)
#
# elif msg_type == "street_start_message":
# street, state = self.__parse_street_start_message(message)
# self.receive_street_start_message(street, state)
#
# elif msg_type == "game_update_message":
# new_action, round_state = self.__parse_game_update_message(message)
# self.receive_game_update_message(new_action, round_state)
#
# elif msg_type == "round_result_message":
# winners, hand_info, state = self.__parse_round_result_message(message)
# self.receive_round_result_message(winners, hand_info, state)
#
#
# def __build_err_msg(self, msg):
# return "Your client does not implement [ {0} ] method".format(msg)
#
# def __parse_ask_message(self, message):
# hole_card = message["hole_card"]
# valid_actions = message["valid_actions"]
# round_state = message["round_state"]
# return valid_actions, hole_card, round_state
#
# def __parse_game_start_message(self, message):
# game_info = message["game_information"]
# return game_info
#
# def __parse_round_start_message(self, message):
# round_count = message["round_count"]
# seats = message["seats"]
# hole_card = message["hole_card"]
# return round_count, hole_card, seats
#
# def __parse_street_start_message(self, message):
# street = message["street"]
# round_state = message["round_state"]
# return street, round_state
#
# def __parse_game_update_message(self, message):
# new_action = message["action"]
# round_state = message["round_state"]
# return new_action, round_state
#
# def __parse_round_result_message(self, message):
# winners = message["winners"]
# hand_info = message["hand_info"]
# round_state = message["round_state"]
# return winners, hand_info, round_state
, which may contain function names, class names, or code. Output only the next line. | amount = int(raw_amount) |
Using the snippet: <|code_start|>
class FishPlayer(BasePokerPlayer): # Do not forget to make parent class as "BasePokerPlayer"
# we define the logic to make an action through this method. (so this method would be the core of your AI)
def declare_action(self, valid_actions, hole_card, round_state):
# valid_actions format => [raise_action_info, call_action_info, fold_action_info]
call_action_info = valid_actions[1]
action, amount = call_action_info["action"], call_action_info["amount"]
return action, amount # action returned here is sent to the poker engine
def receive_game_start_message(self, game_info):
pass
<|code_end|>
, determine the next line of code. You have imports:
from pypokerengine.players import BasePokerPlayer
and context (class names, function names, or code) available:
# Path: pypokerengine/players.py
# class BasePokerPlayer(object):
# """Base Poker client implementation
#
# To create poker client, you need to override this class and
# implement following 7 methods.
#
# - declare_action
# - receive_game_start_message
# - receive_round_start_message
# - receive_street_start_message
# - receive_game_update_message
# - receive_round_result_message
# """
#
# def __init__(self):
# pass
#
# def declare_action(self, valid_actions, hole_card, round_state):
# err_msg = self.__build_err_msg("declare_action")
# raise NotImplementedError(err_msg)
#
# def receive_game_start_message(self, game_info):
# err_msg = self.__build_err_msg("receive_game_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_start_message(self, round_count, hole_card, seats):
# err_msg = self.__build_err_msg("receive_round_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_street_start_message(self, street, round_state):
# err_msg = self.__build_err_msg("receive_street_start_message")
# raise NotImplementedError(err_msg)
#
# def receive_game_update_message(self, new_action, round_state):
# err_msg = self.__build_err_msg("receive_game_update_message")
# raise NotImplementedError(err_msg)
#
# def receive_round_result_message(self, winners, hand_info, round_state):
# err_msg = self.__build_err_msg("receive_round_result_message")
# raise NotImplementedError(err_msg)
#
# def set_uuid(self, uuid):
# self.uuid = uuid
#
# def respond_to_ask(self, message):
# """Called from Dealer when ask message received from RoundManager"""
# valid_actions, hole_card, round_state = self.__parse_ask_message(message)
# return self.declare_action(valid_actions, hole_card, round_state)
#
# def receive_notification(self, message):
# """Called from Dealer when notification received from RoundManager"""
# msg_type = message["message_type"]
#
# if msg_type == "game_start_message":
# info = self.__parse_game_start_message(message)
# self.receive_game_start_message(info)
#
# elif msg_type == "round_start_message":
# round_count, hole, seats = self.__parse_round_start_message(message)
# self.receive_round_start_message(round_count, hole, seats)
#
# elif msg_type == "street_start_message":
# street, state = self.__parse_street_start_message(message)
# self.receive_street_start_message(street, state)
#
# elif msg_type == "game_update_message":
# new_action, round_state = self.__parse_game_update_message(message)
# self.receive_game_update_message(new_action, round_state)
#
# elif msg_type == "round_result_message":
# winners, hand_info, state = self.__parse_round_result_message(message)
# self.receive_round_result_message(winners, hand_info, state)
#
#
# def __build_err_msg(self, msg):
# return "Your client does not implement [ {0} ] method".format(msg)
#
# def __parse_ask_message(self, message):
# hole_card = message["hole_card"]
# valid_actions = message["valid_actions"]
# round_state = message["round_state"]
# return valid_actions, hole_card, round_state
#
# def __parse_game_start_message(self, message):
# game_info = message["game_information"]
# return game_info
#
# def __parse_round_start_message(self, message):
# round_count = message["round_count"]
# seats = message["seats"]
# hole_card = message["hole_card"]
# return round_count, hole_card, seats
#
# def __parse_street_start_message(self, message):
# street = message["street"]
# round_state = message["round_state"]
# return street, round_state
#
# def __parse_game_update_message(self, message):
# new_action = message["action"]
# round_state = message["round_state"]
# return new_action, round_state
#
# def __parse_round_result_message(self, message):
# winners = message["winners"]
# hand_info = message["hand_info"]
# round_state = message["round_state"]
# return winners, hand_info, round_state
. Output only the next line. | def receive_round_start_message(self, round_count, hole_card, seats): |
Given snippet: <|code_start|>
class Player:
ACTION_FOLD_STR = "FOLD"
ACTION_CALL_STR = "CALL"
ACTION_RAISE_STR = "RAISE"
ACTION_SMALL_BLIND = "SMALLBLIND"
ACTION_BIG_BLIND = "BIGBLIND"
ACTION_ANTE = "ANTE"
def __init__(self, uuid, initial_stack, name="No Name"):
self.name = name
self.uuid = uuid
self.hole_card = []
self.stack = initial_stack
self.round_action_histories = self.__init_round_action_histories()
self.action_histories = []
self.pay_info = PayInfo()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pypokerengine.engine.pay_info import PayInfo
from pypokerengine.engine.card import Card
from pypokerengine.engine.poker_constants import PokerConstants as Const
and context:
# Path: pypokerengine/engine/pay_info.py
# class PayInfo:
#
# PAY_TILL_END = 0
# ALLIN = 1
# FOLDED = 2
#
# def __init__(self, amount=0, status=0):
# self.amount = amount
# self.status = status
#
# def update_by_pay(self, amount):
# self.amount += amount
#
# def update_to_fold(self):
# self.status = self.FOLDED
#
# def update_to_allin(self):
# self.status = self.ALLIN
#
# # serialize format : [amount, status]
# def serialize(self):
# return [self.amount, self.status]
#
# @classmethod
# def deserialize(self, serial):
# return self(amount=serial[0], status=serial[1])
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/poker_constants.py
# class PokerConstants:
#
# class Action:
# FOLD = 0
# CALL = 1
# RAISE = 2
# SMALL_BLIND = 3
# BIG_BLIND = 4
# ANTE = 5
#
# class Street:
# PREFLOP = 0
# FLOP = 1
# TURN = 2
# RIVER = 3
# SHOWDOWN = 4
# FINISHED = 5
which might include code, classes, or functions. Output only the next line. | def add_holecard(self, cards): |
Given the code snippet: <|code_start|> elif kind == Const.Action.RAISE:
history = self.__raise_history(chip_amount, add_amount)
elif kind == Const.Action.SMALL_BLIND:
history = self.__blind_history(True, sb_amount)
elif kind == Const.Action.BIG_BLIND:
history = self.__blind_history(False, sb_amount)
elif kind == Const.Action.ANTE:
history = self.__ante_history(chip_amount)
else:
raise "UnKnown action history is added (kind = %s)" % kind
history = self.__add_uuid_on_history(history)
self.action_histories.append(history)
def save_street_action_histories(self, street_flg):
self.round_action_histories[street_flg] = self.action_histories
self.action_histories = []
def clear_action_histories(self):
self.round_action_histories = self.__init_round_action_histories()
self.action_histories = []
def clear_pay_info(self):
self.pay_info = PayInfo()
def paid_sum(self):
pay_history = [h for h in self.action_histories if h["action"] not in ["FOLD", "ANTE"]]
last_pay_history = pay_history[-1] if len(pay_history)!=0 else None
return last_pay_history["amount"] if last_pay_history else 0
def serialize(self):
<|code_end|>
, generate the next line using the imports in this file:
from pypokerengine.engine.pay_info import PayInfo
from pypokerengine.engine.card import Card
from pypokerengine.engine.poker_constants import PokerConstants as Const
and context (functions, classes, or occasionally code) from other files:
# Path: pypokerengine/engine/pay_info.py
# class PayInfo:
#
# PAY_TILL_END = 0
# ALLIN = 1
# FOLDED = 2
#
# def __init__(self, amount=0, status=0):
# self.amount = amount
# self.status = status
#
# def update_by_pay(self, amount):
# self.amount += amount
#
# def update_to_fold(self):
# self.status = self.FOLDED
#
# def update_to_allin(self):
# self.status = self.ALLIN
#
# # serialize format : [amount, status]
# def serialize(self):
# return [self.amount, self.status]
#
# @classmethod
# def deserialize(self, serial):
# return self(amount=serial[0], status=serial[1])
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/poker_constants.py
# class PokerConstants:
#
# class Action:
# FOLD = 0
# CALL = 1
# RAISE = 2
# SMALL_BLIND = 3
# BIG_BLIND = 4
# ANTE = 5
#
# class Street:
# PREFLOP = 0
# FLOP = 1
# TURN = 2
# RIVER = 3
# SHOWDOWN = 4
# FINISHED = 5
. Output only the next line. | hole = [card.to_id() for card in self.hole_card] |
Using the snippet: <|code_start|>
class Player:
ACTION_FOLD_STR = "FOLD"
ACTION_CALL_STR = "CALL"
ACTION_RAISE_STR = "RAISE"
ACTION_SMALL_BLIND = "SMALLBLIND"
ACTION_BIG_BLIND = "BIGBLIND"
ACTION_ANTE = "ANTE"
def __init__(self, uuid, initial_stack, name="No Name"):
<|code_end|>
, determine the next line of code. You have imports:
from pypokerengine.engine.pay_info import PayInfo
from pypokerengine.engine.card import Card
from pypokerengine.engine.poker_constants import PokerConstants as Const
and context (class names, function names, or code) available:
# Path: pypokerengine/engine/pay_info.py
# class PayInfo:
#
# PAY_TILL_END = 0
# ALLIN = 1
# FOLDED = 2
#
# def __init__(self, amount=0, status=0):
# self.amount = amount
# self.status = status
#
# def update_by_pay(self, amount):
# self.amount += amount
#
# def update_to_fold(self):
# self.status = self.FOLDED
#
# def update_to_allin(self):
# self.status = self.ALLIN
#
# # serialize format : [amount, status]
# def serialize(self):
# return [self.amount, self.status]
#
# @classmethod
# def deserialize(self, serial):
# return self(amount=serial[0], status=serial[1])
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/poker_constants.py
# class PokerConstants:
#
# class Action:
# FOLD = 0
# CALL = 1
# RAISE = 2
# SMALL_BLIND = 3
# BIG_BLIND = 4
# ANTE = 5
#
# class Street:
# PREFLOP = 0
# FLOP = 1
# TURN = 2
# RIVER = 3
# SHOWDOWN = 4
# FINISHED = 5
. Output only the next line. | self.name = name |
Predict the next line for this snippet: <|code_start|> 'turn': [],
}
}
new_action = {
'player_uuid': 'ftwdqkystzsqwjrzvludgi',
'action': 'raise',
'amount': 30
}
winners = [
{'stack': 300, 'state': 'participating', 'name': 'p1', 'uuid': 'ftwdqkystzsqwjrzvludgi'}
]
hand_info = [
{
'uuid': 'ftwdqkystzsqwjrzvludgi',
'hand': {
'hole': {'high': 14, 'low': 13},
'hand': {'high': 6, 'strength': 'ONEPAIR', 'low': 0}
}
},
{
'uuid': 'bbiuvgalrglojvmgggydyt',
'hand': {
'hole': {'high': 12, 'low': 2},
'hand': {'high': 6, 'strength': 'ONEPAIR', 'low': 0}
}
},
{
<|code_end|>
with the help of current file imports:
from StringIO import StringIO
from io import StringIO
from tests.base_unittest import BaseUnitTest
import sys
import pypokerengine.utils.visualize_utils as U
and context from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
, which may contain function names, class names, or code. Output only the next line. | 'uuid': 'zkbpehnazembrxrihzxnmt', |
Given the code snippet: <|code_start|> self.eq("SK", str(card))
self.eq(51, self.deck.size())
def test_draw_cards(self):
cards = self.deck.draw_cards(3)
self.eq("SJ", str(cards[2]))
self.eq(49, self.deck.size())
def test_restore(self):
self.deck.draw_cards(5)
self.deck.restore()
self.eq(52, self.deck.size())
def test_serialization(self):
self.deck.draw_cards(5)
self.deck.shuffle()
serial = self.deck.serialize()
restored = Deck.deserialize(serial)
self.eq(self.deck.cheat, restored.cheat)
self.eq(self.deck.deck, restored.deck)
def test_cheat_draw(self):
cards = [Card.from_id(cid) for cid in [12, 15, 17]]
cheat = Deck(cheat=True, cheat_card_ids=[12, 15, 17])
self.eq(cheat.draw_cards(3), cards)
def test_cheat_restore(self):
cards = [Card.from_id(cid) for cid in [12, 15, 17]]
cheat = Deck(cheat=True, cheat_card_ids=[12, 15, 17])
cheat.draw_cards(2)
<|code_end|>
, generate the next line using the imports in this file:
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.card import Card
from pypokerengine.engine.deck import Deck
and context (functions, classes, or occasionally code) from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/deck.py
# class Deck:
#
# def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
# self.cheat = cheat
# self.cheat_card_ids = cheat_card_ids
# self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
#
# def draw_card(self):
# return self.deck.pop()
#
# def draw_cards(self, num):
# return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
#
# def size(self):
# return len(self.deck)
#
# def restore(self):
# self.deck = self.__setup()
#
# def shuffle(self):
# if not self.cheat:
# random.shuffle(self.deck)
#
# # serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
# def serialize(self):
# return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]]
#
# @classmethod
# def deserialize(self, serial):
# cheat, cheat_card_ids, deck_ids = serial
# return self(deck_ids=deck_ids, cheat=cheat, cheat_card_ids=cheat_card_ids)
#
# def __setup(self):
# return self.__setup_cheat_deck() if self.cheat else self.__setup_52_cards()
#
# def __setup_52_cards(self):
# return [Card.from_id(cid) for cid in range(1,53)]
#
# def __setup_cheat_deck(self):
# cards = [Card.from_id(cid) for cid in self.cheat_card_ids]
# return cards[::-1]
. Output only the next line. | cheat.restore() |
Based on the snippet: <|code_start|>
class DeckTest(BaseUnitTest):
def setUp(self):
self.deck = Deck()
def test_draw_card(self):
card = self.deck.draw_card()
self.eq("SK", str(card))
self.eq(51, self.deck.size())
def test_draw_cards(self):
cards = self.deck.draw_cards(3)
<|code_end|>
, predict the immediate next line with the help of imports:
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.card import Card
from pypokerengine.engine.deck import Deck
and context (classes, functions, sometimes code) from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/deck.py
# class Deck:
#
# def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
# self.cheat = cheat
# self.cheat_card_ids = cheat_card_ids
# self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
#
# def draw_card(self):
# return self.deck.pop()
#
# def draw_cards(self, num):
# return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
#
# def size(self):
# return len(self.deck)
#
# def restore(self):
# self.deck = self.__setup()
#
# def shuffle(self):
# if not self.cheat:
# random.shuffle(self.deck)
#
# # serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
# def serialize(self):
# return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]]
#
# @classmethod
# def deserialize(self, serial):
# cheat, cheat_card_ids, deck_ids = serial
# return self(deck_ids=deck_ids, cheat=cheat, cheat_card_ids=cheat_card_ids)
#
# def __setup(self):
# return self.__setup_cheat_deck() if self.cheat else self.__setup_52_cards()
#
# def __setup_52_cards(self):
# return [Card.from_id(cid) for cid in range(1,53)]
#
# def __setup_cheat_deck(self):
# cards = [Card.from_id(cid) for cid in self.cheat_card_ids]
# return cards[::-1]
. Output only the next line. | self.eq("SJ", str(cards[2])) |
Based on the snippet: <|code_start|>
class DeckTest(BaseUnitTest):
def setUp(self):
self.deck = Deck()
def test_draw_card(self):
card = self.deck.draw_card()
self.eq("SK", str(card))
<|code_end|>
, predict the immediate next line with the help of imports:
from tests.base_unittest import BaseUnitTest
from pypokerengine.engine.card import Card
from pypokerengine.engine.deck import Deck
and context (classes, functions, sometimes code) from other files:
# Path: tests/base_unittest.py
# class BaseUnitTest(unittest.TestCase):
#
# def eq(self, expected, target):
# return self.assertEqual(expected, target)
#
# def neq(self, expected, target):
# return self.assertNotEqual(expected, target)
#
# def true(self, target):
# return self.assertTrue(target)
#
# def false(self, target):
# return self.assertFalse(target)
#
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
#
# Path: pypokerengine/engine/deck.py
# class Deck:
#
# def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
# self.cheat = cheat
# self.cheat_card_ids = cheat_card_ids
# self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
#
# def draw_card(self):
# return self.deck.pop()
#
# def draw_cards(self, num):
# return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
#
# def size(self):
# return len(self.deck)
#
# def restore(self):
# self.deck = self.__setup()
#
# def shuffle(self):
# if not self.cheat:
# random.shuffle(self.deck)
#
# # serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
# def serialize(self):
# return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]]
#
# @classmethod
# def deserialize(self, serial):
# cheat, cheat_card_ids, deck_ids = serial
# return self(deck_ids=deck_ids, cheat=cheat, cheat_card_ids=cheat_card_ids)
#
# def __setup(self):
# return self.__setup_cheat_deck() if self.cheat else self.__setup_52_cards()
#
# def __setup_52_cards(self):
# return [Card.from_id(cid) for cid in range(1,53)]
#
# def __setup_cheat_deck(self):
# cards = [Card.from_id(cid) for cid in self.cheat_card_ids]
# return cards[::-1]
. Output only the next line. | self.eq(51, self.deck.size()) |
Here is a snippet: <|code_start|>
ACTION_CALL = "call"
ACTION_FOLD = "fold"
ACTION_RAISE = "raise"
def generate_legal_actions(players, player_position, sb_amount):
return ActionChecker.legal_actions(players, player_position, sb_amount)
<|code_end|>
. Write the next line using the current file imports:
from pypokerengine.engine.action_checker import ActionChecker
and context from other files:
# Path: pypokerengine/engine/action_checker.py
# class ActionChecker:
#
# @classmethod
# def correct_action(self, players, player_pos, sb_amount, action, amount=None):
# if self.is_allin(players[player_pos], action, amount):
# amount = players[player_pos].stack + players[player_pos].paid_sum()
# elif self.__is_illegal(players, player_pos, sb_amount, action, amount):
# action, amount = "fold", 0
# return action, amount
#
#
# @classmethod
# def is_allin(self, player, action, bet_amount):
# if action == 'call':
# return bet_amount >= player.stack + player.paid_sum()
# elif action == 'raise':
# return bet_amount == player.stack + player.paid_sum()
# else:
# return False
#
#
# @classmethod
# def need_amount_for_action(self, player, amount):
# return amount - player.paid_sum()
#
#
# @classmethod
# def agree_amount(self, players):
# last_raise = self.__fetch_last_raise(players)
# return last_raise["amount"] if last_raise else 0
#
#
# @classmethod
# def legal_actions(self, players, player_pos, sb_amount):
# min_raise = self.__min_raise_amount(players, sb_amount)
# max_raise = players[player_pos].stack + players[player_pos].paid_sum()
# if max_raise < min_raise:
# min_raise = max_raise = -1
# return [
# { "action" : "fold" , "amount" : 0 },
# { "action" : "call" , "amount" : self.agree_amount(players) },
# { "action" : "raise", "amount" : { "min": min_raise, "max": max_raise } }
# ]
#
# @classmethod
# def _is_legal(self, players, player_pos, sb_amount, action, amount=None):
# return not self.__is_illegal(players, player_pos, sb_amount, action, amount)
#
# @classmethod
# def __is_illegal(self, players, player_pos, sb_amount, action, amount=None):
# if action == 'fold':
# return False
# elif action == 'call':
# return self.__is_short_of_money(players[player_pos], amount)\
# or self.__is_illegal_call(players, amount)
# elif action == 'raise':
# return self.__is_short_of_money(players[player_pos], amount) \
# or self.__is_illegal_raise(players, amount, sb_amount)
#
# @classmethod
# def __is_illegal_call(self, players, amount):
# return amount != self.agree_amount(players)
#
# @classmethod
# def __is_illegal_raise(self, players, amount, sb_amount):
# return self.__min_raise_amount(players, sb_amount) > amount
#
# @classmethod
# def __min_raise_amount(self, players, sb_amount):
# raise_ = self.__fetch_last_raise(players)
# return raise_["amount"] + raise_["add_amount"] if raise_ else sb_amount*2
#
# @classmethod
# def __is_short_of_money(self, player, amount):
# return player.stack < amount - player.paid_sum()
#
# @classmethod
# def __fetch_last_raise(self, players):
# all_histories = [p.action_histories for p in players]
# all_histories = reduce(lambda acc, e: acc + e, all_histories) # flatten
# raise_histories = [h for h in all_histories if h["action"] in ["RAISE", "SMALLBLIND", "BIGBLIND"]]
# if len(raise_histories) == 0:
# return None
# else:
# return max(raise_histories, key=lambda h: h["amount"]) # maxby
, which may include functions, classes, or code. Output only the next line. | def is_legal_action(players, player_position, sb_amount, action, amount=None): |
Given the following code snippet before the placeholder: <|code_start|>
class Deck:
def __init__(self, deck_ids=None, cheat=False, cheat_card_ids=[]):
self.cheat = cheat
self.cheat_card_ids = cheat_card_ids
self.deck = [Card.from_id(cid) for cid in deck_ids] if deck_ids else self.__setup()
def draw_card(self):
return self.deck.pop()
def draw_cards(self, num):
return reduce(lambda acc, _: acc + [self.draw_card()], range(num), [])
def size(self):
return len(self.deck)
def restore(self):
self.deck = self.__setup()
def shuffle(self):
if not self.cheat:
random.shuffle(self.deck)
# serialize format : [cheat_flg, chat_card_ids, deck_card_ids]
def serialize(self):
<|code_end|>
, predict the next line using imports from the current file:
from functools import reduce
from pypokerengine.engine.card import Card
import random
and context including class names, function names, and sometimes code from other files:
# Path: pypokerengine/engine/card.py
# class Card:
#
# CLUB = 2
# DIAMOND = 4
# HEART = 8
# SPADE = 16
#
# SUIT_MAP = {
# 2 : 'C',
# 4 : 'D',
# 8 : 'H',
# 16 : 'S'
# }
#
# RANK_MAP = {
# 2 : '2',
# 3 : '3',
# 4 : '4',
# 5 : '5',
# 6 : '6',
# 7 : '7',
# 8 : '8',
# 9 : '9',
# 10 : 'T',
# 11 : 'J',
# 12 : 'Q',
# 13 : 'K',
# 14 : 'A'
# }
#
#
# def __init__(self, suit, rank):
# self.suit = suit
# self.rank = 14 if rank == 1 else rank
#
# def __eq__(self, other):
# return self.suit == other.suit and self.rank == other.rank
#
# def __str__(self):
# suit = self.SUIT_MAP[self.suit]
# rank = self.RANK_MAP[self.rank]
# return "{0}{1}".format(suit, rank)
#
# def to_id(self):
# rank = 1 if self.rank == 14 else self.rank
# num = 0
# tmp = self.suit >> 1
# while tmp&1 != 1:
# num += 1
# tmp >>= 1
#
# return rank + 13 * num
#
# @classmethod
# def from_id(cls, card_id):
# suit, rank = 2, card_id
# while rank > 13:
# suit <<= 1
# rank -= 13
#
# return cls(suit, rank)
#
# @classmethod
# def from_str(cls, str_card):
# assert(len(str_card)==2)
# inverse = lambda hsh: {v:k for k,v in hsh.items()}
# suit = inverse(cls.SUIT_MAP)[str_card[0].upper()]
# rank = inverse(cls.RANK_MAP)[str_card[1]]
# return cls(suit, rank)
. Output only the next line. | return [self.cheat, self.cheat_card_ids, [card.to_id() for card in self.deck]] |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
parser = argparse.ArgumentParser()
parser.add_argument('db', help='path to the user database')
parser.add_argument('--user', help='username')
parser.add_argument('--name', help='real name')
parser.add_argument('--email', help='email address')
parser.add_argument('--level', type=int, default=0,
help='access level (default: 0)')
parser.add_argument('--group', choices=('common', 'admin'), default='common',
help='access group (common|admin)')
parser.add_argument('--affiliation', default='sys',
help="user's affiliation (default: sys)")
<|code_end|>
. Use current file imports:
import sys
import os
import argparse
import sqlite3
from getpass import getpass
from omw.common_login import hash_pass
and context (classes, functions, or code) from other files:
# Path: omw/common_login.py
# def hash_pass(password):
# """ Return the md5 hash of the password+salt """
# salted_password = password + app.secret_key
# return hashlib.md5(salted_password.encode('utf-8')).hexdigest()
. Output only the next line. | args = parser.parse_args() |
Using the snippet: <|code_start|>
def _rem(txt):
return ex_junk(txt, containing=['\n','\r'])
def _zip_top_bot(txt_lst):
cols = len(txt_lst)/2
<|code_end|>
, determine the next line of code. You have imports:
from itertools import chain
from nhlscrapi._tools import (
to_int,
# re_comp_num_pos_name,
exclude_from as ex_junk
)
from nhlscrapi.scrapr.reportloader import ReportLoader
and context (class names, function names, or code) available:
# Path: nhlscrapi/_tools.py
# def to_int(s, default=-1):
# mult = 1
# if s[0] in ['-','+']:
# mult = -1 if '-' in s else 1
# s = s[1:]
# return mult*int(s) if s.isdigit() else 0 if s == '00' else default
#
# def exclude_from(l, containing = [], equal_to = []):
# """Exclude elements in list l containing any elements from list ex.
# Example:
# >>> l = ['bob', 'r', 'rob\r', '\r\nrobert']
# >>> containing = ['\n', '\r']
# >>> equal_to = ['r']
# >>> exclude_from(l, containing, equal_to)
# ['bob']
# """
#
# cont = lambda li: any(c in li for c in containing)
# eq = lambda li: any(e == li for e in equal_to)
# return [li for li in l if not (cont(li) or eq(li))]
#
# Path: nhlscrapi/scrapr/reportloader.py
# class ReportLoader(object):
# """
# Base class for objects that load full reports. Manages html request and extracts match up from banner
#
# :param game_key: unique game identifier of type :py:class:`nhlscrapi.games.game.GameKey`
# :param report_type: str, type of report being loaded. Must be a method of :py:class:`.NHLCn`
# """
#
# __metaclass__ = ABCMeta
# __lx_doc = None
#
# def __init__(self, game_key, report_type=''):
# self.game_key = game_key
# """Game key being retrieved of type :py:class:`nhlscrapi.games.game.GameKey` """
#
# self.report_type = report_type
# """Type of report to be loaded. Valid types correspond to the methods of :py:class:`.NHLCn`"""
#
# self.matchup = { }
# """
# Fame meta information displayed in report banners including team names,
# final score, game date, location, and attendance. Data format is
#
# .. code:: python
#
# {
# 'home': home,
# 'away': away,
# 'final': final,
# 'attendance': att,
# 'date': date,
# 'location': loc
# }
# """
#
# self.req_err = None
# """Error from http request"""
#
#
# def html_doc(self):
# """
# :returns: the lxml processed html document
# :rtype: ``lxml.html.document_fromstring`` output
# """
#
# if self.__lx_doc is None:
# cn = NHLCn()
#
# if hasattr(cn, self.report_type):
# html = getattr(cn, self.report_type)(self.game_key)
# else:
# raise ValueError('Invalid report type: %s' % self.report_type)
#
# if cn.req_err is None:
# self.__lx_doc = fromstring(html)
# else:
# self.req_err = cn.req_err
#
# return self.__lx_doc
#
#
# def parse_matchup(self):
# """
# Parse the banner matchup meta info for the game.
#
# :returns: ``self`` on success or ``None``
# """
# lx_doc = self.html_doc()
# try:
# if not self.matchup:
# self.matchup = self._fill_meta(lx_doc)
# return self
# except:
# return None
#
#
# @abstractmethod
# def parse(self):
# """
# Fully parses html document.
#
# :returns: ``self`` on success, ``None`` otherwise
# """
#
# return self.parse_matchup()
#
#
# def _fill_meta(self, doc):
# def team_scr(doc, t):
# xp = ''.join(['//table[@id="', t, '"]'])
# team = doc.xpath(xp)[0]
# team = [s for s in team.xpath('.//text()') if s.lower() != t.lower() and '\r\n' not in s and 'game' not in s.lower()]
#
# return team
#
# final = { }
# final['away'], at = tuple(team_scr(doc, 'Visitor'))
# final['home'], ht = tuple(team_scr(doc, 'Home'))
#
# # clean team names
# away = TP.team_name_parser(at)
# home = TP.team_name_parser(ht)
#
# game_info = doc.xpath('//table[@id="GameInfo"]')[0].xpath('.//text()')
# game_info = '; '.join(s.strip() for s in game_info if s.strip() != '')
#
# att = re.findall(r'(?<=[aA]ttendance\s)(\d*\,?\d*)', game_info)
# att = int(att[0].replace(',','')) if att else 0
#
# date = re.findall(r'\w+\,?\s\w+\s\d+\,?\s\d+', game_info)
# date = date[0] if date else ''
#
# loc = re.findall(r'(?<=at\W)([^\;]*)', game_info)
# loc = loc[0] if loc else ''
#
# return {
# 'home': home,
# 'away': away,
# 'final': final,
# 'attendance': att,
# 'date': date,
# 'location': loc
# }
. Output only the next line. | return [ (k,v) for k, v in zip(txt_lst[:cols],txt_lst[cols:]) ] |
Continue the code snippet: <|code_start|>
def __get_num(s):
s = s.replace('#', '').strip()
return int(s) if s.isdigit() else -1
<|code_end|>
. Use current file imports:
from nhlscrapi._tools import exclude_from as ex_junk
and context (classes, functions, or code) from other files:
# Path: nhlscrapi/_tools.py
# def exclude_from(l, containing = [], equal_to = []):
# """Exclude elements in list l containing any elements from list ex.
# Example:
# >>> l = ['bob', 'r', 'rob\r', '\r\nrobert']
# >>> containing = ['\n', '\r']
# >>> equal_to = ['r']
# >>> exclude_from(l, containing, equal_to)
# ['bob']
# """
#
# cont = lambda li: any(c in li for c in containing)
# eq = lambda li: any(e == li for e in equal_to)
# return [li for li in l if not (cont(li) or eq(li))]
. Output only the next line. | def __num_name(s): |
Continue the code snippet: <|code_start|>
if skater_ct <= 7 and period > 4 and gt < 3:
return ET.ShootOutGoal
else:
return ET.Goal
def event_type_mapper(event_str, **kwargs):
event_type_map = {
"SHOT": __shot_type,
"SHOT (!)": __shot_type,
"SHOT (*)": __shot_type,
"BLOCK": lambda **kwargs: ET.Block,
"BLOCKED SHOT": lambda **kwargs: ET.Block,
"MISS": lambda **kwargs: ET.Miss,
"MISSED SHOT": lambda **kwargs: ET.Miss,
"GOAL": __goal_type,
"HIT": lambda **kwargs: ET.Hit,
"HIT (!)": lambda **kwargs: ET.Hit,
"HIT (*)": lambda **kwargs: ET.Hit,
"FAC": lambda **kwargs: ET.FaceOff,
"FACE-OFF": lambda **kwargs: ET.FaceOff,
"GIVE": lambda **kwargs: ET.Giveaway,
"GIVEAWAY": lambda **kwargs: ET.Giveaway,
"TAKE": lambda **kwargs: ET.Takeaway,
"TAKEAWAY": lambda **kwargs: ET.Takeaway,
"PENL": lambda **kwargs: ET.Penalty,
"PENALTY": lambda **kwargs: ET.Penalty,
"STOP": lambda **kwargs: ET.Stoppage,
"STOPPAGE": lambda **kwargs: ET.Stoppage,
"PEND": lambda **kwargs: ET.PeriodEnd,
<|code_end|>
. Use current file imports:
from nhlscrapi.games.events import EventType as ET, EventFactory as EF
from nhlscrapi.scrapr import descparser as dp
and context (classes, functions, or code) from other files:
# Path: nhlscrapi/games/events.py
# class Event(object):
# class ShotAttempt(Event):
# class Shot(ShotAttempt):
# class Goal(Shot):
# class Miss(ShotAttempt):
# class Block(ShotAttempt):
# class Hit(Event):
# class FaceOff(Event):
# class Stoppage(Event):
# class PeriodEnd(Stoppage):
# class GameEnd(Stoppage):
# class ShootOutEnd(Stoppage):
# class Penalty(Event):
# class Turnover(Event):
# class TOType:
# class Takeaway(Turnover):
# class Giveaway(Turnover):
# class ShootOutAtt(Event):
# class ShootOutGoal(ShootOutAtt):
# class EventFactory(object):
# def __init__(self, event_type = EventType.Event, desc = ""):
# def __init__(self, event_type = EventType.ShotAttempt):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self, event_type=EventType.Stoppage):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self):
# def __init__(self, to_type = TOType.Takeaway):
# def turnover_type(self):
# def turnover_type(self, value):
# def __init__(self):
# def __init__(self):
# def __init__(self, event_type = EventType.ShootOutAtt):
# def __init__(self):
# def _get_class_hierarchy(base):
# def Create(event_type):
#
# Path: nhlscrapi/scrapr/descparser.py
# def default_desc_parser(event):
# def get_ft(s, def_dist = -1):
# def team_num_name(s):
# def split_and_strip(s, by):
# def rem_penalty_shot_desc(s):
# def parse_shot_desc_08(event):
# def parse_goal_desc_08(event):
# def assist_from(a):
# def parse_miss_08(event):
# def parse_faceoff_08(event):
# def parse_hit_08(event):
# def parse_block_08(event):
# def parse_takeaway_08(event):
# def parse_giveaway_08(event):
# def parse_shootout(event):
. Output only the next line. | "GEND": lambda **kwargs: ET.GameEnd, |
Predict the next line for this snippet: <|code_start|>
event.hit_by = team_num_name(s[0])
event.team = event.hit_by['team']
p_z = s[1].split(",")
event.player_hit = team_num_name(p_z[0])
event.zone = p_z[1].strip() if len(p_z) > 1 else ''
#############################
##
## parse blocked shot - '08 format
##
#############################
# VAN #14 BURROWS BLOCKED BY NYR #27 MCDONAGH, Snap, Def. Zone
def parse_block_08(event):
s = split_and_strip(event.desc, "BLOCKED BY")
event.shooter = team_num_name(s[0])
s = split_and_strip(s[1], ",")
event.blocked_by = team_num_name(s[0])
if len(s) == 3: # Normal number of items found (expected case)
event.shot_type = s[1]
event.zone = s[2]
else: # Something is missing - shot or zone
if 'Zone' in s[1]: # We have zone, not shot.
<|code_end|>
with the help of current file imports:
from nhlscrapi.scrapr.teamnameparser import team_abbr_parser
import re
and context from other files:
# Path: nhlscrapi/scrapr/teamnameparser.py
# def team_abbr_parser(abr):
# abr = abr.replace('.','')
#
# # keep abr if already in good shape
# if abr in ABB:
# return abr
#
# if abr in __abbr_alts:
# return __abbr_alts[abr]
#
# #print 'UNKNOWN ABBREVIATION: %s' % abr
# return abr
, which may contain function names, class names, or code. Output only the next line. | event.shot_type = '' |
Using the snippet: <|code_start|>
class Command(BaseCommand):
help = "Manually confirm a Payment"
def add_arguments(self, parser):
parser.add_argument('id', action='store', type=int, help="Payment ID")
parser.add_argument('--paid-amount', dest='amount', action='store', type=int, help="Paid amount")
parser.add_argument('--extid', dest='extid', action='store', type=str)
parser.add_argument('-n', dest='sim', action='store_true', help="Simulate")
def handle(self, *args, **options):
try:
p = Payment.objects.get(id=options['id'])
except Payment.DoesNotExist:
self.stderr.write("Cannot find payment #%d" % options['id'])
return
print("Payment #%d by %s (amount=%d; paid_amount=%d)" % (p.id, p.user.username, p.amount, p.paid_amount))
if options['amount']:
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_duration
from payments.models import Payment
and context (class names, function names, or code) available:
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
. Output only the next line. | pa = options['amount'] |
Next line prediction: <|code_start|>
class Command(BaseCommand):
help = "Check bitcoin payments status"
def handle(self, *args, **options):
if 'bitcoin' not in ACTIVE_BACKENDS:
raise CommandError("bitcoin backend not active.")
backend = ACTIVE_BACKENDS['bitcoin']
payments = Payment.objects.filter(backend_id='bitcoin', status='new')
self.stdout.write("Found %d active unconfirmed payments." % len(payments))
for p in payments:
self.stdout.write("Checking payment #%d... " % p.id, ending="")
backend.check(p)
if p.status == 'confirmed':
self.stdout.write("OK.")
<|code_end|>
. Use current file imports:
(from django.core.management.base import BaseCommand, CommandError
from payments.models import Payment, ACTIVE_BACKENDS)
and context including class names, function names, or small code snippets from other files:
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
#
# ACTIVE_BACKENDS = {}
. Output only the next line. | else: |
Given snippet: <|code_start|>
class Command(BaseCommand):
help = "Check bitcoin payments status"
def handle(self, *args, **options):
if 'bitcoin' not in ACTIVE_BACKENDS:
raise CommandError("bitcoin backend not active.")
backend = ACTIVE_BACKENDS['bitcoin']
payments = Payment.objects.filter(backend_id='bitcoin', status='new')
self.stdout.write("Found %d active unconfirmed payments." % len(payments))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.management.base import BaseCommand, CommandError
from payments.models import Payment, ACTIVE_BACKENDS
and context:
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
#
# ACTIVE_BACKENDS = {}
which might include code, classes, or functions. Output only the next line. | for p in payments: |
Next line prediction: <|code_start|> months = {
'3m': 3,
'6m': 6,
'12m': 12,
}[rps.period]
ROOT_URL = project_settings.ROOT_URL
params = {
'cmd': '_xclick-subscriptions',
'notify_url': ROOT_URL + reverse('payments:cb_paypal_subscr', args=(rps.id,)),
'item_name': self.title,
'currency_code': self.currency,
'business': self.account_address,
'no_shipping': '1',
'return': ROOT_URL + reverse('payments:return_subscr', args=(rps.id,)),
'cancel_return': ROOT_URL + reverse('account:index'),
'a3': '%.2f' % (rps.period_amount / 100),
'p3': str(months),
't3': 'M',
'src': '1',
}
if self.header_image:
params['cpp_header_image'] = self.header_image
rps.save()
return redirect(self.api_base + '/cgi-bin/webscr?' + urlencode(params))
<|code_end|>
. Use current file imports:
(from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from urllib.parse import urlencode
from urllib.request import urlopen
from django.core.urlresolvers import reverse
from django.conf import settings as project_settings
from .base import BackendBase
from payments.models import Payment)
and context including class names, function names, or small code snippets from other files:
# Path: payments/backends/base.py
# class BackendBase:
# backend_id = None
# backend_verbose_name = ""
# backend_display_name = ""
# backend_enabled = False
# backend_has_recurring = False
#
# def __init__(self, settings):
# pass
#
# def new_payment(self, payment):
# """ Initialize a payment and returns an URL to redirect the user.
# Can return a HTML string that will be sent back to the user in a
# default template (like a form) or a HTTP response (like a redirect).
# """
# raise NotImplementedError()
#
# def callback(self, payment, request):
# """ Handle a callback """
# raise NotImplementedError()
#
# def callback_subscr(self, payment, request):
# """ Handle a callback (recurring payments) """
# raise NotImplementedError()
#
# def cancel_subscription(self, subscr):
# """ Cancel a subscription """
# raise NotImplementedError()
#
# def get_info(self):
# """ Returns some status (key, value) list """
# return ()
#
# def get_ext_url(self, payment):
# """ Returns URL to external payment view, or None """
# return None
#
# def get_subscr_ext_url(self, subscr):
# """ Returns URL to external payment view, or None """
# return None
. Output only the next line. | def handle_verified_callback(self, payment, params): |
Predict the next line after this snippet: <|code_start|>
class PaymentAdmin(admin.ModelAdmin):
model = Payment
list_display = ('user', 'backend', 'status', 'amount', 'paid_amount', 'created')
list_filter = ('backend_id', 'status')
fieldsets = (
(None, {
'fields': ('backend', 'user_link', 'subscription_link', 'time', 'status',
'status_message'),
}),
(_("Payment Data"), {
'fields': ('amount_fmt', 'paid_amount_fmt',
'backend_extid_link', 'backend_data'),
}),
)
readonly_fields = ('backend', 'user_link', 'time', 'status', 'status_message',
'amount_fmt', 'paid_amount_fmt', 'subscription_link',
'backend_extid_link', 'backend_data')
search_fields = ('user__username', 'user__email', 'backend_extid', 'backend_data')
def backend(self, object):
return object.backend.backend_verbose_name
def backend_extid_link(self, object):
ext_url = object.backend.get_ext_url(object)
if ext_url:
return '<a href="%s">%s</a>' % (ext_url, object.backend_extid)
return object.backend_extid
<|code_end|>
using the current file's imports:
from django.shortcuts import resolve_url
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from .models import Payment, Subscription
and any relevant context from other files:
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
#
# class Subscription(models.Model):
# """ Recurring payment subscription. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# created = models.DateTimeField(auto_now_add=True)
# period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
# last_confirmed_payment = models.DateTimeField(blank=True, null=True)
# status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# @property
# def months(self):
# return period_months(self.period)
#
# @property
# def period_amount(self):
# return self.months * get_price()
#
# @property
# def next_renew(self):
# """ Approximate date of the next payment """
# if self.last_confirmed_payment:
# return self.last_confirmed_payment + timedelta(days=self.months * 30)
# return self.created + timedelta(days=self.months * 30)
#
# @property
# def monthly_amount(self):
# return get_price()
#
# def create_payment(self):
# payment = Payment(
# user=self.user,
# backend_id=self.backend_id,
# status='new',
# time=timedelta(days=30 * self.months),
# amount=get_price() * self.months,
# subscription=self,
# )
# return payment
. Output only the next line. | backend_extid_link.allow_tags = True |
Here is a snippet: <|code_start|> return '<a href="%s">%s</a>' % (ext_url, object.backend_extid)
return object.backend_extid
backend_extid_link.allow_tags = True
def amount_fmt(self, object):
return '%.2f %s' % (object.amount / 100, object.currency_name)
amount_fmt.short_description = _("Amount")
def paid_amount_fmt(self, object):
return '%.2f %s' % (object.paid_amount / 100, object.currency_name)
paid_amount_fmt.short_description = _("Paid amount")
def user_link(self, object):
change_url = resolve_url('admin:auth_user_change', object.user.id)
return '<a href="%s">%s</a>' % (change_url, object.user.username)
user_link.allow_tags = True
user_link.short_description = 'User'
def subscription_link(self, object):
change_url = resolve_url('admin:payments_subscription_change',
object.subscription.id)
return '<a href="%s">%s</a>' % (change_url, object.subscription.id)
subscription_link.allow_tags = True
subscription_link.short_description = 'Subscription'
class SubscriptionAdmin(admin.ModelAdmin):
model = Subscription
list_display = ('user', 'created', 'status', 'backend', 'backend_extid')
readonly_fields = ('user_link', 'backend', 'period', 'created', 'status',
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import resolve_url
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from .models import Payment, Subscription
and context from other files:
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
#
# class Subscription(models.Model):
# """ Recurring payment subscription. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# created = models.DateTimeField(auto_now_add=True)
# period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
# last_confirmed_payment = models.DateTimeField(blank=True, null=True)
# status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# @property
# def months(self):
# return period_months(self.period)
#
# @property
# def period_amount(self):
# return self.months * get_price()
#
# @property
# def next_renew(self):
# """ Approximate date of the next payment """
# if self.last_confirmed_payment:
# return self.last_confirmed_payment + timedelta(days=self.months * 30)
# return self.created + timedelta(days=self.months * 30)
#
# @property
# def monthly_amount(self):
# return get_price()
#
# def create_payment(self):
# payment = Payment(
# user=self.user,
# backend_id=self.backend_id,
# status='new',
# time=timedelta(days=30 * self.months),
# amount=get_price() * self.months,
# subscription=self,
# )
# return payment
, which may include functions, classes, or code. Output only the next line. | 'last_confirmed_payment', 'payments_links', |
Predict the next line for this snippet: <|code_start|>
def _get_name(self, request):
for f in self.GET_FIELDS:
if f in request.GET and request.GET[f]:
return request.GET[f]
if 'campaign' in request.COOKIES:
return request.COOKIES['campaign']
return None
def process_request(self, request):
name = self._get_name(request)
if not name:
return
name = name.strip()
if len(name) >= 64 or not re.match('^[a-zA-Z0-9_.:-]+$', name):
return
request.session['campaign'] = name
def process_response(self, request, response):
name = request.session.get('campaign')
if not name:
return response
max_age = 365 * 24 * 60 * 60
expires = (datetime.utcnow() + timedelta(seconds=max_age))
expires = expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
response.set_cookie('campaign', name,
<|code_end|>
with the help of current file imports:
from datetime import datetime, timedelta
from django.conf import settings
from .models import User
import re
and context from other files:
# Path: lambdainst/models.py
# def random_gift_code():
# def is_paid(self):
# def time_left(self):
# def add_paid_time(self, time):
# def give_trial_period(self):
# def can_have_trial(self):
# def remaining_trial_periods(self):
# def on_payment_confirmed(self, payment):
# def get_subscription(self, include_unconfirmed=False):
# def __str__(self):
# def create_vpnuser(sender, instance, created, **kwargs):
# def use_on(self, user):
# def comment_head(self):
# def __str__(self):
# def __str__(self):
# class VPNUser(models.Model):
# class Meta:
# class GiftCode(models.Model):
# class Meta:
# class GiftCodeUser(models.Model):
# class Meta:
, which may contain function names, class names, or code. Output only the next line. | max_age=max_age, |
Here is a snippet: <|code_start|>def close_tickets(modeladmin, request, queryset):
queryset.update(is_open=False, closed=timezone.now())
close_tickets.short_description = _("Close selected tickets")
class TicketMessageAdmin(admin.StackedInline):
model = TicketMessage
fields = ('user_link', 'remote_addr', 'created', 'staff_only', 'message')
readonly_fields = ('user_link', 'created')
extra = 1
def user_link(self, object):
change_url = resolve_url('admin:auth_user_change', object.user.id)
return '<a href="%s">%s</a>' % (change_url, object.user.username)
user_link.allow_tags = True
user_link.short_description = 'User'
class TicketAdmin(admin.ModelAdmin):
fields = ('category', 'subject', 'user_link', 'created', 'status', 'closed')
readonly_fields = ('user_link', 'created', 'status', 'closed')
list_display = ('subject', 'user', 'created', 'category', 'is_open')
list_filter = ('category', 'is_open')
search_fields = ('subject', 'user__username', 'message_set__message')
actions = (close_tickets,)
inlines = (TicketMessageAdmin,)
def user_link(self, object):
change_url = resolve_url('admin:auth_user_change', object.user.id)
return '<a href="%s">%s</a>' % (change_url, object.user.username)
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from django.shortcuts import resolve_url
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils import formats
from .models import Ticket, TicketMessage, TicketNotifyAddress
and context from other files:
# Path: tickets/models.py
# class Ticket(models.Model):
# class Meta:
# ordering = ('-created',)
#
# permissions = (
# ('view_any_ticket', _("Can view any ticket")),
# ('reply_any_ticket', _("Can reply to any ticket")),
# ('view_private_message', _("Can view private messages on tickets")),
# ('post_private_message', _("Can post private messages on tickets")),
# )
#
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# subject = models.CharField(max_length=100)
# created = models.DateTimeField(auto_now_add=True)
# is_open = models.BooleanField(default=True)
# closed = models.DateTimeField(blank=True, null=True)
#
# @property
# def status_text(self):
# if self.closed:
# return _("Closed")
# last_msg = self.message_set.last()
# if last_msg and last_msg.user == self.user:
# return _("Waiting for staff")
# else:
# return _("Open")
#
# def get_contacts(self):
# contacts = TicketNotifyAddress.objects.filter(category=self.category)
# return [c.address for c in contacts]
#
# def notify_new(self, first_message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=first_message, url=url)
# notify(subject, 'tickets/mail_support_new.txt', self.get_contacts(), ctx)
#
# def notify_reply(self, message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=message, url=url)
# if message.user == self.user:
# notify(subject, 'tickets/mail_support_reply.txt', self.get_contacts(), ctx)
# if self.user and self.user.email:
# if message.staff_only and not self.user.has_perm('tickets.view_private_message'):
# return
# notify(subject, 'tickets/mail_user_reply.txt', [self.user.email], ctx)
#
# def __str__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('tickets:view', args=(self.id,))
#
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# class TicketNotifyAddress(models.Model):
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# address = models.EmailField()
, which may include functions, classes, or code. Output only the next line. | user_link.allow_tags = True |
Using the snippet: <|code_start|>
def close_tickets(modeladmin, request, queryset):
queryset.update(is_open=False, closed=timezone.now())
close_tickets.short_description = _("Close selected tickets")
class TicketMessageAdmin(admin.StackedInline):
model = TicketMessage
fields = ('user_link', 'remote_addr', 'created', 'staff_only', 'message')
readonly_fields = ('user_link', 'created')
extra = 1
def user_link(self, object):
change_url = resolve_url('admin:auth_user_change', object.user.id)
return '<a href="%s">%s</a>' % (change_url, object.user.username)
user_link.allow_tags = True
user_link.short_description = 'User'
class TicketAdmin(admin.ModelAdmin):
fields = ('category', 'subject', 'user_link', 'created', 'status', 'closed')
readonly_fields = ('user_link', 'created', 'status', 'closed')
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from django.shortcuts import resolve_url
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils import formats
from .models import Ticket, TicketMessage, TicketNotifyAddress
and context (class names, function names, or code) available:
# Path: tickets/models.py
# class Ticket(models.Model):
# class Meta:
# ordering = ('-created',)
#
# permissions = (
# ('view_any_ticket', _("Can view any ticket")),
# ('reply_any_ticket', _("Can reply to any ticket")),
# ('view_private_message', _("Can view private messages on tickets")),
# ('post_private_message', _("Can post private messages on tickets")),
# )
#
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# subject = models.CharField(max_length=100)
# created = models.DateTimeField(auto_now_add=True)
# is_open = models.BooleanField(default=True)
# closed = models.DateTimeField(blank=True, null=True)
#
# @property
# def status_text(self):
# if self.closed:
# return _("Closed")
# last_msg = self.message_set.last()
# if last_msg and last_msg.user == self.user:
# return _("Waiting for staff")
# else:
# return _("Open")
#
# def get_contacts(self):
# contacts = TicketNotifyAddress.objects.filter(category=self.category)
# return [c.address for c in contacts]
#
# def notify_new(self, first_message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=first_message, url=url)
# notify(subject, 'tickets/mail_support_new.txt', self.get_contacts(), ctx)
#
# def notify_reply(self, message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=message, url=url)
# if message.user == self.user:
# notify(subject, 'tickets/mail_support_reply.txt', self.get_contacts(), ctx)
# if self.user and self.user.email:
# if message.staff_only and not self.user.has_perm('tickets.view_private_message'):
# return
# notify(subject, 'tickets/mail_user_reply.txt', [self.user.email], ctx)
#
# def __str__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('tickets:view', args=(self.id,))
#
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# class TicketNotifyAddress(models.Model):
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# address = models.EmailField()
. Output only the next line. | list_display = ('subject', 'user', 'created', 'category', 'is_open') |
Given the code snippet: <|code_start|>def close_tickets(modeladmin, request, queryset):
queryset.update(is_open=False, closed=timezone.now())
close_tickets.short_description = _("Close selected tickets")
class TicketMessageAdmin(admin.StackedInline):
model = TicketMessage
fields = ('user_link', 'remote_addr', 'created', 'staff_only', 'message')
readonly_fields = ('user_link', 'created')
extra = 1
def user_link(self, object):
change_url = resolve_url('admin:auth_user_change', object.user.id)
return '<a href="%s">%s</a>' % (change_url, object.user.username)
user_link.allow_tags = True
user_link.short_description = 'User'
class TicketAdmin(admin.ModelAdmin):
fields = ('category', 'subject', 'user_link', 'created', 'status', 'closed')
readonly_fields = ('user_link', 'created', 'status', 'closed')
list_display = ('subject', 'user', 'created', 'category', 'is_open')
list_filter = ('category', 'is_open')
search_fields = ('subject', 'user__username', 'message_set__message')
actions = (close_tickets,)
inlines = (TicketMessageAdmin,)
def user_link(self, object):
change_url = resolve_url('admin:auth_user_change', object.user.id)
return '<a href="%s">%s</a>' % (change_url, object.user.username)
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from django.shortcuts import resolve_url
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils import formats
from .models import Ticket, TicketMessage, TicketNotifyAddress
and context (functions, classes, or occasionally code) from other files:
# Path: tickets/models.py
# class Ticket(models.Model):
# class Meta:
# ordering = ('-created',)
#
# permissions = (
# ('view_any_ticket', _("Can view any ticket")),
# ('reply_any_ticket', _("Can reply to any ticket")),
# ('view_private_message', _("Can view private messages on tickets")),
# ('post_private_message', _("Can post private messages on tickets")),
# )
#
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# subject = models.CharField(max_length=100)
# created = models.DateTimeField(auto_now_add=True)
# is_open = models.BooleanField(default=True)
# closed = models.DateTimeField(blank=True, null=True)
#
# @property
# def status_text(self):
# if self.closed:
# return _("Closed")
# last_msg = self.message_set.last()
# if last_msg and last_msg.user == self.user:
# return _("Waiting for staff")
# else:
# return _("Open")
#
# def get_contacts(self):
# contacts = TicketNotifyAddress.objects.filter(category=self.category)
# return [c.address for c in contacts]
#
# def notify_new(self, first_message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=first_message, url=url)
# notify(subject, 'tickets/mail_support_new.txt', self.get_contacts(), ctx)
#
# def notify_reply(self, message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=message, url=url)
# if message.user == self.user:
# notify(subject, 'tickets/mail_support_reply.txt', self.get_contacts(), ctx)
# if self.user and self.user.email:
# if message.staff_only and not self.user.has_perm('tickets.view_private_message'):
# return
# notify(subject, 'tickets/mail_user_reply.txt', [self.user.email], ctx)
#
# def __str__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('tickets:view', args=(self.id,))
#
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# class TicketNotifyAddress(models.Model):
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# address = models.EmailField()
. Output only the next line. | user_link.allow_tags = True |
Given snippet: <|code_start|>
class Command(BaseCommand):
help = "Get bitcoind info"
def handle(self, *args, **options):
if 'bitcoin' not in ACTIVE_BACKENDS:
raise CommandError("bitcoin backend not active.")
backend = ACTIVE_BACKENDS['bitcoin']
for key, value in backend.get_info():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.management.base import BaseCommand, CommandError
from payments.models import ACTIVE_BACKENDS
and context:
# Path: payments/models.py
# ACTIVE_BACKENDS = {}
which might include code, classes, or functions. Output only the next line. | self.stdout.write("%s: %s" % (key, value)) |
Predict the next line after this snippet: <|code_start|>
class Command(BaseCommand):
help = "Get informations about core API"
def handle(self, *args, **options):
for k, v in core_api.info.items():
<|code_end|>
using the current file's imports:
from django.core.management.base import BaseCommand
from lambdainst.core import core_api
and any relevant context from other files:
# Path: lambdainst/core.py
# LCORE_BASE_URL = lcore_settings.get('BASE_URL')
# LCORE_API_KEY = lcore_settings['API_KEY']
# LCORE_API_SECRET = lcore_settings['API_SECRET']
# LCORE_SOURCE_ADDR = lcore_settings.get('SOURCE_ADDRESS')
# LCORE_INST_SECRET = lcore_settings['INST_SECRET']
# LCORE_TIMEOUT = lcore_settings.get('TIMEOUT', 10)
# LCORE_RAISE_ERRORS = bool(lcore_settings.get('RAISE_ERRORS', False))
# LCORE_CACHE_TTL = lcore_settings.get('CACHE_TTL', 60)
# LCORE_CACHE_TTL = timedelta(seconds=LCORE_CACHE_TTL)
# VPN_AUTH_STORAGE = settings.VPN_AUTH_STORAGE
# class APICache:
# def __init__(self, ttl=None, initial=None):
# def query(self, wrapped, *args, **kwargs):
# def __call__(self, wrapped):
# def wrapper(*args, **kwargs):
# def current_active_sessions():
# def get_locations():
# def get_gateway_exit_ips():
# def is_vpn_gateway(ip):
# def create_user(username, cleartext_password):
# def update_user_expiration(user):
# def update_user_password(user, cleartext_password):
# def delete_user(username):
. Output only the next line. | print("%s: %s" % (k, v)) |
Here is a snippet: <|code_start|>
class NewPaymentForm(forms.Form):
TIME_CHOICES = (
('1', '1'),
('3', '3'),
<|code_end|>
. Write the next line using the current file imports:
from django import forms
from .models import BACKEND_CHOICES
and context from other files:
# Path: payments/models.py
# BACKEND_CHOICES = []
, which may include functions, classes, or code. Output only the next line. | ('6', '6'), |
Continue the code snippet: <|code_start|>
if all is False or not request.user.has_perm('tickets.view_any_ticket'):
tickets = tickets.filter(user=request.user)
single_user = True
else:
single_user = False
paginator = Paginator(tickets, 20)
page = request.GET.get('page')
try:
tickets = paginator.page(page)
except PageNotAnInteger:
tickets = paginator.page(1)
except EmptyPage:
tickets = paginator.page(paginator.num_pages)
context = dict(
tickets=tickets,
filter=f,
single_user=single_user,
title=_("Tickets"),
)
context.update(common_context(request))
if not f:
return render(request, 'tickets/index.html', context)
else:
return render(request, 'tickets/list.html', context)
@login_required
<|code_end|>
. Use current file imports:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponseNotFound
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils.translation import ugettext as _
from ccvpn.common import get_client_ip
from .models import Ticket, TicketMessage
from .forms import NewTicketForm, ReplyForm, StaffReplyForm
and context (classes, functions, or code) from other files:
# Path: ccvpn/common.py
# def get_client_ip(request):
# header_name = settings.REAL_IP_HEADER_NAME
#
# if header_name:
# header_name = header_name.replace('-', '_').upper()
# value = request.META.get('HTTP_' + header_name)
# if value:
# return value.split(',', 1)[0]
#
# return request.META.get('REMOTE_ADDR')
#
# Path: tickets/models.py
# class Ticket(models.Model):
# class Meta:
# ordering = ('-created',)
#
# permissions = (
# ('view_any_ticket', _("Can view any ticket")),
# ('reply_any_ticket', _("Can reply to any ticket")),
# ('view_private_message', _("Can view private messages on tickets")),
# ('post_private_message', _("Can post private messages on tickets")),
# )
#
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# subject = models.CharField(max_length=100)
# created = models.DateTimeField(auto_now_add=True)
# is_open = models.BooleanField(default=True)
# closed = models.DateTimeField(blank=True, null=True)
#
# @property
# def status_text(self):
# if self.closed:
# return _("Closed")
# last_msg = self.message_set.last()
# if last_msg and last_msg.user == self.user:
# return _("Waiting for staff")
# else:
# return _("Open")
#
# def get_contacts(self):
# contacts = TicketNotifyAddress.objects.filter(category=self.category)
# return [c.address for c in contacts]
#
# def notify_new(self, first_message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=first_message, url=url)
# notify(subject, 'tickets/mail_support_new.txt', self.get_contacts(), ctx)
#
# def notify_reply(self, message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=message, url=url)
# if message.user == self.user:
# notify(subject, 'tickets/mail_support_reply.txt', self.get_contacts(), ctx)
# if self.user and self.user.email:
# if message.staff_only and not self.user.has_perm('tickets.view_private_message'):
# return
# notify(subject, 'tickets/mail_user_reply.txt', [self.user.email], ctx)
#
# def __str__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('tickets:view', args=(self.id,))
#
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# Path: tickets/forms.py
# class NewTicketForm(forms.Form):
# category = forms.ChoiceField(label=_("Category"), choices=CATEGORY_CHOICES)
# subject = forms.CharField(label=_("Subject"), min_length=1, max_length=100)
# message = forms.CharField(label=_("Message"), widget=forms.Textarea)
#
# class ReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message',)
#
# class StaffReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message', 'staff_only')
#
# staff_only = forms.BooleanField(label=_("Private"), required=False)
. Output only the next line. | def new(request): |
Based on the snippet: <|code_start|> title=_("Ticket:") + " " + ticket.subject,
)
ctx.update(common_context(request))
return render(request, 'tickets/view.html', ctx)
if not reply_any_ticket and ticket.user != request.user:
return HttpResponseNotFound()
if request.POST.get('close') or request.POST.get('button_close'):
ticket.is_open = False
ticket.closed = timezone.now()
ticket.save()
return redirect('tickets:view', id=ticket.id)
if request.POST.get('reopen') or request.POST.get('button_reopen'):
ticket.is_open = True
ticket.save()
return redirect('tickets:view', id=ticket.id)
if request.user.has_perm('tickets.post_private_message'):
form = StaffReplyForm(request.POST)
else:
form = ReplyForm(request.POST)
if not form.is_valid():
ctx = dict(
staff_reply=request.user.has_perm('tickets.post_private_message'),
ticket=ticket,
ticket_messages=messages,
form=form,
<|code_end|>
, predict the immediate next line with the help of imports:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponseNotFound
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils.translation import ugettext as _
from ccvpn.common import get_client_ip
from .models import Ticket, TicketMessage
from .forms import NewTicketForm, ReplyForm, StaffReplyForm
and context (classes, functions, sometimes code) from other files:
# Path: ccvpn/common.py
# def get_client_ip(request):
# header_name = settings.REAL_IP_HEADER_NAME
#
# if header_name:
# header_name = header_name.replace('-', '_').upper()
# value = request.META.get('HTTP_' + header_name)
# if value:
# return value.split(',', 1)[0]
#
# return request.META.get('REMOTE_ADDR')
#
# Path: tickets/models.py
# class Ticket(models.Model):
# class Meta:
# ordering = ('-created',)
#
# permissions = (
# ('view_any_ticket', _("Can view any ticket")),
# ('reply_any_ticket', _("Can reply to any ticket")),
# ('view_private_message', _("Can view private messages on tickets")),
# ('post_private_message', _("Can post private messages on tickets")),
# )
#
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# subject = models.CharField(max_length=100)
# created = models.DateTimeField(auto_now_add=True)
# is_open = models.BooleanField(default=True)
# closed = models.DateTimeField(blank=True, null=True)
#
# @property
# def status_text(self):
# if self.closed:
# return _("Closed")
# last_msg = self.message_set.last()
# if last_msg and last_msg.user == self.user:
# return _("Waiting for staff")
# else:
# return _("Open")
#
# def get_contacts(self):
# contacts = TicketNotifyAddress.objects.filter(category=self.category)
# return [c.address for c in contacts]
#
# def notify_new(self, first_message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=first_message, url=url)
# notify(subject, 'tickets/mail_support_new.txt', self.get_contacts(), ctx)
#
# def notify_reply(self, message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=message, url=url)
# if message.user == self.user:
# notify(subject, 'tickets/mail_support_reply.txt', self.get_contacts(), ctx)
# if self.user and self.user.email:
# if message.staff_only and not self.user.has_perm('tickets.view_private_message'):
# return
# notify(subject, 'tickets/mail_user_reply.txt', [self.user.email], ctx)
#
# def __str__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('tickets:view', args=(self.id,))
#
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# Path: tickets/forms.py
# class NewTicketForm(forms.Form):
# category = forms.ChoiceField(label=_("Category"), choices=CATEGORY_CHOICES)
# subject = forms.CharField(label=_("Subject"), min_length=1, max_length=100)
# message = forms.CharField(label=_("Message"), widget=forms.Textarea)
#
# class ReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message',)
#
# class StaffReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message', 'staff_only')
#
# staff_only = forms.BooleanField(label=_("Private"), required=False)
. Output only the next line. | title=_("Ticket:") + " " + ticket.subject, |
Next line prediction: <|code_start|> form=ReplyForm(),
title=_("Ticket:") + " " + ticket.subject,
)
ctx.update(common_context(request))
return render(request, 'tickets/view.html', ctx)
if not reply_any_ticket and ticket.user != request.user:
return HttpResponseNotFound()
if request.POST.get('close') or request.POST.get('button_close'):
ticket.is_open = False
ticket.closed = timezone.now()
ticket.save()
return redirect('tickets:view', id=ticket.id)
if request.POST.get('reopen') or request.POST.get('button_reopen'):
ticket.is_open = True
ticket.save()
return redirect('tickets:view', id=ticket.id)
if request.user.has_perm('tickets.post_private_message'):
form = StaffReplyForm(request.POST)
else:
form = ReplyForm(request.POST)
if not form.is_valid():
ctx = dict(
staff_reply=request.user.has_perm('tickets.post_private_message'),
ticket=ticket,
ticket_messages=messages,
<|code_end|>
. Use current file imports:
(from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponseNotFound
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils.translation import ugettext as _
from ccvpn.common import get_client_ip
from .models import Ticket, TicketMessage
from .forms import NewTicketForm, ReplyForm, StaffReplyForm)
and context including class names, function names, or small code snippets from other files:
# Path: ccvpn/common.py
# def get_client_ip(request):
# header_name = settings.REAL_IP_HEADER_NAME
#
# if header_name:
# header_name = header_name.replace('-', '_').upper()
# value = request.META.get('HTTP_' + header_name)
# if value:
# return value.split(',', 1)[0]
#
# return request.META.get('REMOTE_ADDR')
#
# Path: tickets/models.py
# class Ticket(models.Model):
# class Meta:
# ordering = ('-created',)
#
# permissions = (
# ('view_any_ticket', _("Can view any ticket")),
# ('reply_any_ticket', _("Can reply to any ticket")),
# ('view_private_message', _("Can view private messages on tickets")),
# ('post_private_message', _("Can post private messages on tickets")),
# )
#
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# subject = models.CharField(max_length=100)
# created = models.DateTimeField(auto_now_add=True)
# is_open = models.BooleanField(default=True)
# closed = models.DateTimeField(blank=True, null=True)
#
# @property
# def status_text(self):
# if self.closed:
# return _("Closed")
# last_msg = self.message_set.last()
# if last_msg and last_msg.user == self.user:
# return _("Waiting for staff")
# else:
# return _("Open")
#
# def get_contacts(self):
# contacts = TicketNotifyAddress.objects.filter(category=self.category)
# return [c.address for c in contacts]
#
# def notify_new(self, first_message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=first_message, url=url)
# notify(subject, 'tickets/mail_support_new.txt', self.get_contacts(), ctx)
#
# def notify_reply(self, message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=message, url=url)
# if message.user == self.user:
# notify(subject, 'tickets/mail_support_reply.txt', self.get_contacts(), ctx)
# if self.user and self.user.email:
# if message.staff_only and not self.user.has_perm('tickets.view_private_message'):
# return
# notify(subject, 'tickets/mail_user_reply.txt', [self.user.email], ctx)
#
# def __str__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('tickets:view', args=(self.id,))
#
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# Path: tickets/forms.py
# class NewTicketForm(forms.Form):
# category = forms.ChoiceField(label=_("Category"), choices=CATEGORY_CHOICES)
# subject = forms.CharField(label=_("Subject"), min_length=1, max_length=100)
# message = forms.CharField(label=_("Message"), widget=forms.Textarea)
#
# class ReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message',)
#
# class StaffReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message', 'staff_only')
#
# staff_only = forms.BooleanField(label=_("Private"), required=False)
. Output only the next line. | form=form, |
Given the following code snippet before the placeholder: <|code_start|> )
context.update(common_context(request))
if not f:
return render(request, 'tickets/index.html', context)
else:
return render(request, 'tickets/list.html', context)
@login_required
def new(request):
context = common_context(request)
context['title'] = _("New Ticket")
if request.method != 'POST':
context['form'] = NewTicketForm()
return render(request, 'tickets/new.html', context)
form = NewTicketForm(request.POST)
if not form.is_valid():
context['form'] = form
return render(request, 'tickets/new.html', context)
ticket = Ticket(category=form.cleaned_data['category'],
subject=form.cleaned_data['subject'],
user=request.user)
ticket.save()
firstmsg = TicketMessage(ticket=ticket, user=request.user,
message=form.cleaned_data['message'])
<|code_end|>
, predict the next line using imports from the current file:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponseNotFound
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils.translation import ugettext as _
from ccvpn.common import get_client_ip
from .models import Ticket, TicketMessage
from .forms import NewTicketForm, ReplyForm, StaffReplyForm
and context including class names, function names, and sometimes code from other files:
# Path: ccvpn/common.py
# def get_client_ip(request):
# header_name = settings.REAL_IP_HEADER_NAME
#
# if header_name:
# header_name = header_name.replace('-', '_').upper()
# value = request.META.get('HTTP_' + header_name)
# if value:
# return value.split(',', 1)[0]
#
# return request.META.get('REMOTE_ADDR')
#
# Path: tickets/models.py
# class Ticket(models.Model):
# class Meta:
# ordering = ('-created',)
#
# permissions = (
# ('view_any_ticket', _("Can view any ticket")),
# ('reply_any_ticket', _("Can reply to any ticket")),
# ('view_private_message', _("Can view private messages on tickets")),
# ('post_private_message', _("Can post private messages on tickets")),
# )
#
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# subject = models.CharField(max_length=100)
# created = models.DateTimeField(auto_now_add=True)
# is_open = models.BooleanField(default=True)
# closed = models.DateTimeField(blank=True, null=True)
#
# @property
# def status_text(self):
# if self.closed:
# return _("Closed")
# last_msg = self.message_set.last()
# if last_msg and last_msg.user == self.user:
# return _("Waiting for staff")
# else:
# return _("Open")
#
# def get_contacts(self):
# contacts = TicketNotifyAddress.objects.filter(category=self.category)
# return [c.address for c in contacts]
#
# def notify_new(self, first_message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=first_message, url=url)
# notify(subject, 'tickets/mail_support_new.txt', self.get_contacts(), ctx)
#
# def notify_reply(self, message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=message, url=url)
# if message.user == self.user:
# notify(subject, 'tickets/mail_support_reply.txt', self.get_contacts(), ctx)
# if self.user and self.user.email:
# if message.staff_only and not self.user.has_perm('tickets.view_private_message'):
# return
# notify(subject, 'tickets/mail_user_reply.txt', [self.user.email], ctx)
#
# def __str__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('tickets:view', args=(self.id,))
#
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# Path: tickets/forms.py
# class NewTicketForm(forms.Form):
# category = forms.ChoiceField(label=_("Category"), choices=CATEGORY_CHOICES)
# subject = forms.CharField(label=_("Subject"), min_length=1, max_length=100)
# message = forms.CharField(label=_("Message"), widget=forms.Textarea)
#
# class ReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message',)
#
# class StaffReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message', 'staff_only')
#
# staff_only = forms.BooleanField(label=_("Private"), required=False)
. Output only the next line. | if not request.user.is_staff: |
Using the snippet: <|code_start|> ticket.save()
firstmsg = TicketMessage(ticket=ticket, user=request.user,
message=form.cleaned_data['message'])
if not request.user.is_staff:
firstmsg.remote_addr = get_client_ip(request)
firstmsg.save()
ticket.notify_new(firstmsg)
return redirect('tickets:view', id=ticket.id)
@login_required
def view(request, id):
ticket = get_object_or_404(Ticket, id=id)
view_any_ticket = request.user.has_perm('tickets.view_any_ticket')
reply_any_ticket = request.user.has_perm('tickets.reply_any_ticket')
if not view_any_ticket and ticket.user != request.user:
return HttpResponseNotFound()
if request.user.has_perm('tickets.view_private_message'):
messages = ticket.message_set.all()
else:
messages = ticket.message_set.filter(staff_only=False)
<|code_end|>
, determine the next line of code. You have imports:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponseNotFound
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils.translation import ugettext as _
from ccvpn.common import get_client_ip
from .models import Ticket, TicketMessage
from .forms import NewTicketForm, ReplyForm, StaffReplyForm
and context (class names, function names, or code) available:
# Path: ccvpn/common.py
# def get_client_ip(request):
# header_name = settings.REAL_IP_HEADER_NAME
#
# if header_name:
# header_name = header_name.replace('-', '_').upper()
# value = request.META.get('HTTP_' + header_name)
# if value:
# return value.split(',', 1)[0]
#
# return request.META.get('REMOTE_ADDR')
#
# Path: tickets/models.py
# class Ticket(models.Model):
# class Meta:
# ordering = ('-created',)
#
# permissions = (
# ('view_any_ticket', _("Can view any ticket")),
# ('reply_any_ticket', _("Can reply to any ticket")),
# ('view_private_message', _("Can view private messages on tickets")),
# ('post_private_message', _("Can post private messages on tickets")),
# )
#
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# subject = models.CharField(max_length=100)
# created = models.DateTimeField(auto_now_add=True)
# is_open = models.BooleanField(default=True)
# closed = models.DateTimeField(blank=True, null=True)
#
# @property
# def status_text(self):
# if self.closed:
# return _("Closed")
# last_msg = self.message_set.last()
# if last_msg and last_msg.user == self.user:
# return _("Waiting for staff")
# else:
# return _("Open")
#
# def get_contacts(self):
# contacts = TicketNotifyAddress.objects.filter(category=self.category)
# return [c.address for c in contacts]
#
# def notify_new(self, first_message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=first_message, url=url)
# notify(subject, 'tickets/mail_support_new.txt', self.get_contacts(), ctx)
#
# def notify_reply(self, message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=message, url=url)
# if message.user == self.user:
# notify(subject, 'tickets/mail_support_reply.txt', self.get_contacts(), ctx)
# if self.user and self.user.email:
# if message.staff_only and not self.user.has_perm('tickets.view_private_message'):
# return
# notify(subject, 'tickets/mail_user_reply.txt', [self.user.email], ctx)
#
# def __str__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('tickets:view', args=(self.id,))
#
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# Path: tickets/forms.py
# class NewTicketForm(forms.Form):
# category = forms.ChoiceField(label=_("Category"), choices=CATEGORY_CHOICES)
# subject = forms.CharField(label=_("Subject"), min_length=1, max_length=100)
# message = forms.CharField(label=_("Message"), widget=forms.Textarea)
#
# class ReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message',)
#
# class StaffReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message', 'staff_only')
#
# staff_only = forms.BooleanField(label=_("Private"), required=False)
. Output only the next line. | if request.method != 'POST': |
Using the snippet: <|code_start|>
@login_required
def new(request):
context = common_context(request)
context['title'] = _("New Ticket")
if request.method != 'POST':
context['form'] = NewTicketForm()
return render(request, 'tickets/new.html', context)
form = NewTicketForm(request.POST)
if not form.is_valid():
context['form'] = form
return render(request, 'tickets/new.html', context)
ticket = Ticket(category=form.cleaned_data['category'],
subject=form.cleaned_data['subject'],
user=request.user)
ticket.save()
firstmsg = TicketMessage(ticket=ticket, user=request.user,
message=form.cleaned_data['message'])
if not request.user.is_staff:
firstmsg.remote_addr = get_client_ip(request)
firstmsg.save()
ticket.notify_new(firstmsg)
<|code_end|>
, determine the next line of code. You have imports:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponseNotFound
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils.translation import ugettext as _
from ccvpn.common import get_client_ip
from .models import Ticket, TicketMessage
from .forms import NewTicketForm, ReplyForm, StaffReplyForm
and context (class names, function names, or code) available:
# Path: ccvpn/common.py
# def get_client_ip(request):
# header_name = settings.REAL_IP_HEADER_NAME
#
# if header_name:
# header_name = header_name.replace('-', '_').upper()
# value = request.META.get('HTTP_' + header_name)
# if value:
# return value.split(',', 1)[0]
#
# return request.META.get('REMOTE_ADDR')
#
# Path: tickets/models.py
# class Ticket(models.Model):
# class Meta:
# ordering = ('-created',)
#
# permissions = (
# ('view_any_ticket', _("Can view any ticket")),
# ('reply_any_ticket', _("Can reply to any ticket")),
# ('view_private_message', _("Can view private messages on tickets")),
# ('post_private_message', _("Can post private messages on tickets")),
# )
#
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# category = models.CharField(max_length=16, choices=CATEGORY_CHOICES)
# subject = models.CharField(max_length=100)
# created = models.DateTimeField(auto_now_add=True)
# is_open = models.BooleanField(default=True)
# closed = models.DateTimeField(blank=True, null=True)
#
# @property
# def status_text(self):
# if self.closed:
# return _("Closed")
# last_msg = self.message_set.last()
# if last_msg and last_msg.user == self.user:
# return _("Waiting for staff")
# else:
# return _("Open")
#
# def get_contacts(self):
# contacts = TicketNotifyAddress.objects.filter(category=self.category)
# return [c.address for c in contacts]
#
# def notify_new(self, first_message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=first_message, url=url)
# notify(subject, 'tickets/mail_support_new.txt', self.get_contacts(), ctx)
#
# def notify_reply(self, message):
# url = ROOT_URL + reverse('tickets:view', args=(self.id,))
# subject = _("Ticket:") + " " + self.subject
# ctx = dict(ticket=self, message=message, url=url)
# if message.user == self.user:
# notify(subject, 'tickets/mail_support_reply.txt', self.get_contacts(), ctx)
# if self.user and self.user.email:
# if message.staff_only and not self.user.has_perm('tickets.view_private_message'):
# return
# notify(subject, 'tickets/mail_user_reply.txt', [self.user.email], ctx)
#
# def __str__(self):
# return self.subject
#
# def get_absolute_url(self):
# return reverse('tickets:view', args=(self.id,))
#
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# Path: tickets/forms.py
# class NewTicketForm(forms.Form):
# category = forms.ChoiceField(label=_("Category"), choices=CATEGORY_CHOICES)
# subject = forms.CharField(label=_("Subject"), min_length=1, max_length=100)
# message = forms.CharField(label=_("Message"), widget=forms.Textarea)
#
# class ReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message',)
#
# class StaffReplyForm(forms.ModelForm):
# class Meta:
# model = TicketMessage
# fields = ('message', 'staff_only')
#
# staff_only = forms.BooleanField(label=_("Private"), required=False)
. Output only the next line. | return redirect('tickets:view', id=ticket.id) |
Using the snippet: <|code_start|>
class Command(BaseCommand):
help = "Cancels expired Payments"
def add_arguments(self, parser):
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_duration
from payments.models import Payment
and context (class names, function names, or code) available:
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
. Output only the next line. | parser.add_argument('-n', dest='sim', action='store_true', help="Simulate") |
Predict the next line after this snippet: <|code_start|>
urlpatterns = [
url(r'^admin/status$', account_views.admin_status, name='admin_status'),
url(r'^admin/referrers$', account_views.admin_ref, name='admin_ref'),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/locations$', account_views.api_locations),
url(r'^api/auth$', account_views.api_auth),
url(r'^$', views.index, name='index'),
url(r'^ca.crt$', account_views.ca_crt),
<|code_end|>
using the current file's imports:
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
from lambdainst import urls as account_urls, views as account_views
from payments import urls as payments_urls
from tickets import urls as tickets_urls
and any relevant context from other files:
# Path: lambdainst/urls.py
#
# Path: lambdainst/views.py
# def get_locations():
# def ca_crt(request):
# def logout(request):
# def signup(request):
# def discourse_login(request):
# def index(request):
# def __getitem__(self, months):
# def captcha_test(grr, request):
# def trial(request):
# def settings(request):
# def gift_code(request):
# def logs(request):
# def config(request):
# def config_dl(request):
# def api_auth(request):
# def api_locations(request):
# def format_loc(cc, l):
# def status(request):
# def admin_status(request):
# def admin_ref(request):
# class price_fn:
#
# Path: payments/urls.py
#
# Path: tickets/urls.py
. Output only the next line. | url(r'^setlang$', views.set_lang, name='set_lang'), |
Predict the next line for this snippet: <|code_start|>
urlpatterns = [
url(r'^admin/status$', account_views.admin_status, name='admin_status'),
url(r'^admin/referrers$', account_views.admin_ref, name='admin_ref'),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/locations$', account_views.api_locations),
url(r'^api/auth$', account_views.api_auth),
url(r'^$', views.index, name='index'),
url(r'^ca.crt$', account_views.ca_crt),
url(r'^setlang$', views.set_lang, name='set_lang'),
url(r'^chat$', views.chat, name='chat'),
url(r'^page/(?P<name>[a-zA-Z0-9_-]+)$', views.page, name='page'),
url(r'^status$', account_views.status),
url(r'^account/forgot$', auth_views.password_reset,
{}, name='password_reset'),
url(r'^account/forgot_done$', auth_views.password_reset_done,
name='password_reset_done'),
url(r'^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.password_reset_confirm, name='password_reset_confirm'),
url(r'^account/reset/done/$', auth_views.password_reset_complete,
name='password_reset_complete'),
<|code_end|>
with the help of current file imports:
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
from lambdainst import urls as account_urls, views as account_views
from payments import urls as payments_urls
from tickets import urls as tickets_urls
and context from other files:
# Path: lambdainst/urls.py
#
# Path: lambdainst/views.py
# def get_locations():
# def ca_crt(request):
# def logout(request):
# def signup(request):
# def discourse_login(request):
# def index(request):
# def __getitem__(self, months):
# def captcha_test(grr, request):
# def trial(request):
# def settings(request):
# def gift_code(request):
# def logs(request):
# def config(request):
# def config_dl(request):
# def api_auth(request):
# def api_locations(request):
# def format_loc(cc, l):
# def status(request):
# def admin_status(request):
# def admin_ref(request):
# class price_fn:
#
# Path: payments/urls.py
#
# Path: tickets/urls.py
, which may contain function names, class names, or code. Output only the next line. | url(r'^account/', include(account_urls, namespace='account')), |
Continue the code snippet: <|code_start|>
urlpatterns = [
url(r'^admin/status$', account_views.admin_status, name='admin_status'),
url(r'^admin/referrers$', account_views.admin_ref, name='admin_ref'),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/locations$', account_views.api_locations),
url(r'^api/auth$', account_views.api_auth),
url(r'^$', views.index, name='index'),
url(r'^ca.crt$', account_views.ca_crt),
url(r'^setlang$', views.set_lang, name='set_lang'),
url(r'^chat$', views.chat, name='chat'),
url(r'^page/(?P<name>[a-zA-Z0-9_-]+)$', views.page, name='page'),
url(r'^status$', account_views.status),
url(r'^account/forgot$', auth_views.password_reset,
{}, name='password_reset'),
url(r'^account/forgot_done$', auth_views.password_reset_done,
name='password_reset_done'),
url(r'^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
<|code_end|>
. Use current file imports:
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
from lambdainst import urls as account_urls, views as account_views
from payments import urls as payments_urls
from tickets import urls as tickets_urls
and context (classes, functions, or code) from other files:
# Path: lambdainst/urls.py
#
# Path: lambdainst/views.py
# def get_locations():
# def ca_crt(request):
# def logout(request):
# def signup(request):
# def discourse_login(request):
# def index(request):
# def __getitem__(self, months):
# def captcha_test(grr, request):
# def trial(request):
# def settings(request):
# def gift_code(request):
# def logs(request):
# def config(request):
# def config_dl(request):
# def api_auth(request):
# def api_locations(request):
# def format_loc(cc, l):
# def status(request):
# def admin_status(request):
# def admin_ref(request):
# class price_fn:
#
# Path: payments/urls.py
#
# Path: tickets/urls.py
. Output only the next line. | auth_views.password_reset_confirm, name='password_reset_confirm'), |
Using the snippet: <|code_start|> src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{pubkey}"
data-image="{img}"
data-name="{name}"
data-currency="{curr}"
data-description="{desc}"
data-amount="{amount}"
data-email="{email}"
data-locale="auto"
data-zip-code="true"
data-alipay="true">
</script>
</form>
'''
return form.format(
post=reverse('payments:cb_stripe', args=(payment.id,)),
pubkey=self.pubkey,
img=self.header_image,
email=payment.user.email or '',
name=self.name,
desc=desc,
amount=payment.amount,
curr=self.currency,
)
def new_subscription(self, subscr):
desc = 'Subscription (' + str(subscr.period) + ') for ' + subscr.user.username
form = '''
<form action="{post}" method="POST">
<script
<|code_end|>
, determine the next line of code. You have imports:
import json
import stripe
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from .base import BackendBase
from payments.models import Subscription, Payment
and context (class names, function names, or code) available:
# Path: payments/backends/base.py
# class BackendBase:
# backend_id = None
# backend_verbose_name = ""
# backend_display_name = ""
# backend_enabled = False
# backend_has_recurring = False
#
# def __init__(self, settings):
# pass
#
# def new_payment(self, payment):
# """ Initialize a payment and returns an URL to redirect the user.
# Can return a HTML string that will be sent back to the user in a
# default template (like a form) or a HTTP response (like a redirect).
# """
# raise NotImplementedError()
#
# def callback(self, payment, request):
# """ Handle a callback """
# raise NotImplementedError()
#
# def callback_subscr(self, payment, request):
# """ Handle a callback (recurring payments) """
# raise NotImplementedError()
#
# def cancel_subscription(self, subscr):
# """ Cancel a subscription """
# raise NotImplementedError()
#
# def get_info(self):
# """ Returns some status (key, value) list """
# return ()
#
# def get_ext_url(self, payment):
# """ Returns URL to external payment view, or None """
# return None
#
# def get_subscr_ext_url(self, subscr):
# """ Returns URL to external payment view, or None """
# return None
. Output only the next line. | src="https://checkout.stripe.com/checkout.js" class="stripe-button" |
Here is a snippet: <|code_start|> def _filter(o):
if period == 'm':
return df(o).year == m.year and df(o).month == m.month and df(o).day == m.day
return df(o).date() <= m and df(o).date() > (m - timedelta(days=1))
if period == 'y':
return df(o).year == m.year and df(o).month == m.month
return (df(o).date().replace(day=1) <= m and
df(o).date().replace(day=1) > (m - timedelta(days=30)))
return _filter
def users_graph(period):
chart = pygal.Line(fill=True, x_label_rotation=75, show_legend=False)
chart.title = 'Users %s' % PERIOD_VERBOSE_NAME[period]
chart.x_labels = []
values = []
gen = last_days(30) if period == 'm' else last_months(12)
users = User.objects.all()
for m in gen:
filter_ = time_filter_future(period, m, lambda o: o.date_joined)
users_filtered = filter(filter_, users)
values.append(len(list(users_filtered)))
chart.x_labels.append('%02d/%02d' % (m.month, m.day))
chart.add('Users', values)
return chart.render()
def payments_paid_graph(period):
<|code_end|>
. Write the next line using the current file imports:
from datetime import timedelta, date
from .models import User
from payments.models import BACKENDS
from payments.models import Payment
import pygal
and context from other files:
# Path: lambdainst/models.py
# def random_gift_code():
# def is_paid(self):
# def time_left(self):
# def add_paid_time(self, time):
# def give_trial_period(self):
# def can_have_trial(self):
# def remaining_trial_periods(self):
# def on_payment_confirmed(self, payment):
# def get_subscription(self, include_unconfirmed=False):
# def __str__(self):
# def create_vpnuser(sender, instance, created, **kwargs):
# def use_on(self, user):
# def comment_head(self):
# def __str__(self):
# def __str__(self):
# class VPNUser(models.Model):
# class Meta:
# class GiftCode(models.Model):
# class Meta:
# class GiftCodeUser(models.Model):
# class Meta:
#
# Path: payments/models.py
# BACKENDS = {}
#
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
, which may include functions, classes, or code. Output only the next line. | chart = pygal.StackedBar(x_label_rotation=75, show_legend=True) |
Given snippet: <|code_start|>
PERIOD_VERBOSE_NAME = {
'y': "per month",
'm': "per day",
}
def monthdelta(date, delta):
m = (date.month + delta) % 12
y = date.year + (date.month + delta - 1) // 12
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import timedelta, date
from .models import User
from payments.models import BACKENDS
from payments.models import Payment
import pygal
and context:
# Path: lambdainst/models.py
# def random_gift_code():
# def is_paid(self):
# def time_left(self):
# def add_paid_time(self, time):
# def give_trial_period(self):
# def can_have_trial(self):
# def remaining_trial_periods(self):
# def on_payment_confirmed(self, payment):
# def get_subscription(self, include_unconfirmed=False):
# def __str__(self):
# def create_vpnuser(sender, instance, created, **kwargs):
# def use_on(self, user):
# def comment_head(self):
# def __str__(self):
# def __str__(self):
# class VPNUser(models.Model):
# class Meta:
# class GiftCode(models.Model):
# class Meta:
# class GiftCodeUser(models.Model):
# class Meta:
#
# Path: payments/models.py
# BACKENDS = {}
#
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
which might include code, classes, or functions. Output only the next line. | if not m: |
Next line prediction: <|code_start|> users = User.objects.all()
for m in gen:
filter_ = time_filter_future(period, m, lambda o: o.date_joined)
users_filtered = filter(filter_, users)
values.append(len(list(users_filtered)))
chart.x_labels.append('%02d/%02d' % (m.month, m.day))
chart.add('Users', values)
return chart.render()
def payments_paid_graph(period):
chart = pygal.StackedBar(x_label_rotation=75, show_legend=True)
chart.x_labels = []
gen = list(last_days(30) if period == 'm' else last_months(12))
chart.title = 'Payments %s in €' % (PERIOD_VERBOSE_NAME[period])
for m in gen:
chart.x_labels.append('%02d/%02d' % (m.month, m.day))
values = dict()
for backend_id, backend in BACKENDS.items():
values = []
payments = list(Payment.objects.filter(status='confirmed', backend_id=backend_id))
for m in gen:
filter_ = time_filter_between(period, m, lambda o: o.created)
filtered = filter(filter_, payments)
<|code_end|>
. Use current file imports:
(from datetime import timedelta, date
from .models import User
from payments.models import BACKENDS
from payments.models import Payment
import pygal)
and context including class names, function names, or small code snippets from other files:
# Path: lambdainst/models.py
# def random_gift_code():
# def is_paid(self):
# def time_left(self):
# def add_paid_time(self, time):
# def give_trial_period(self):
# def can_have_trial(self):
# def remaining_trial_periods(self):
# def on_payment_confirmed(self, payment):
# def get_subscription(self, include_unconfirmed=False):
# def __str__(self):
# def create_vpnuser(sender, instance, created, **kwargs):
# def use_on(self, user):
# def comment_head(self):
# def __str__(self):
# def __str__(self):
# class VPNUser(models.Model):
# class Meta:
# class GiftCode(models.Model):
# class Meta:
# class GiftCodeUser(models.Model):
# class Meta:
#
# Path: payments/models.py
# BACKENDS = {}
#
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
. Output only the next line. | values.append(sum(u.paid_amount for u in filtered) / 100) |
Given snippet: <|code_start|>
class NewTicketForm(forms.Form):
category = forms.ChoiceField(label=_("Category"), choices=CATEGORY_CHOICES)
subject = forms.CharField(label=_("Subject"), min_length=1, max_length=100)
message = forms.CharField(label=_("Message"), widget=forms.Textarea)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from .models import TicketMessage, CATEGORY_CHOICES
from django.utils.translation import ugettext_lazy as _
and context:
# Path: tickets/models.py
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# CATEGORY_CHOICES = (
# ('support', _("Support")),
# ('security', _("Security")),
# ('billing', _("Account / Billing")),
# )
which might include code, classes, or functions. Output only the next line. | class ReplyForm(forms.ModelForm): |
Continue the code snippet: <|code_start|>
class NewTicketForm(forms.Form):
category = forms.ChoiceField(label=_("Category"), choices=CATEGORY_CHOICES)
subject = forms.CharField(label=_("Subject"), min_length=1, max_length=100)
message = forms.CharField(label=_("Message"), widget=forms.Textarea)
class ReplyForm(forms.ModelForm):
class Meta:
model = TicketMessage
fields = ('message',)
class StaffReplyForm(forms.ModelForm):
class Meta:
model = TicketMessage
<|code_end|>
. Use current file imports:
from django import forms
from .models import TicketMessage, CATEGORY_CHOICES
from django.utils.translation import ugettext_lazy as _
and context (classes, functions, or code) from other files:
# Path: tickets/models.py
# class TicketMessage(models.Model):
# ticket = models.ForeignKey(Ticket, related_name='message_set',
# on_delete=models.CASCADE)
# user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True,
# on_delete=models.SET_NULL)
# remote_addr = models.GenericIPAddressField(blank=True, null=True)
# created = models.DateTimeField(auto_now_add=True)
# message = models.TextField()
# staff_only = models.BooleanField(default=False)
#
# class Meta:
# ordering = ('created',)
#
# CATEGORY_CHOICES = (
# ('support', _("Support")),
# ('security', _("Security")),
# ('billing', _("Account / Billing")),
# )
. Output only the next line. | fields = ('message', 'staff_only') |
Based on the snippet: <|code_start|>
prng = random.SystemRandom()
def random_gift_code():
charset = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ"
return ''.join([prng.choice(charset) for n in range(10)])
class VPNUser(models.Model):
<|code_end|>
, predict the immediate next line with the help of imports:
import random
from datetime import timedelta
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.db.models.signals import post_save
from django.dispatch import receiver
from constance import config as site_config
from . import core
from ccvpn.common import get_trial_period_duration
from payments.models import Subscription
and context (classes, functions, sometimes code) from other files:
# Path: ccvpn/common.py
# def get_trial_period_duration():
# return config.TRIAL_PERIOD_HOURS * timedelta(hours=1)
#
# Path: payments/models.py
# class Subscription(models.Model):
# """ Recurring payment subscription. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# created = models.DateTimeField(auto_now_add=True)
# period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
# last_confirmed_payment = models.DateTimeField(blank=True, null=True)
# status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# @property
# def months(self):
# return period_months(self.period)
#
# @property
# def period_amount(self):
# return self.months * get_price()
#
# @property
# def next_renew(self):
# """ Approximate date of the next payment """
# if self.last_confirmed_payment:
# return self.last_confirmed_payment + timedelta(days=self.months * 30)
# return self.created + timedelta(days=self.months * 30)
#
# @property
# def monthly_amount(self):
# return get_price()
#
# def create_payment(self):
# payment = Payment(
# user=self.user,
# backend_id=self.backend_id,
# status='new',
# time=timedelta(days=30 * self.months),
# amount=get_price() * self.months,
# subscription=self,
# )
# return payment
. Output only the next line. | class Meta: |
Using the snippet: <|code_start|> def new_payment(self, payment):
ROOT_URL = project_settings.ROOT_URL
months = int(payment.time.days / 30)
username = payment.user.username
amount_str = '%.2f' % (payment.amount / 100)
name = "%d months for %s" % (months, username)
checkout = self.client.create_checkout(
amount=amount_str,
currency=self.currency,
name=name,
success_url=ROOT_URL + reverse('payments:view', args=(payment.id,)),
cancel_url=ROOT_URL + reverse('payments:cancel', args=(payment.id,)),
metadata={'payment_id': payment.id},
)
embed_id = checkout['embed_code']
payment.backend_data['checkout_id'] = checkout['id']
payment.backend_data['embed_code'] = checkout['embed_code']
return redirect(self.site + 'checkouts/' + embed_id +
'?custom=' + str(payment.id))
def callback(self, Payment, request):
if self.callback_source_ip:
if ('.' in request.META['REMOTE_ADDR']) != ('.' in self.callback_source_ip):
print("source IP version")
print(repr(request.META.get('REMOTE_ADDR')))
print(repr(self.callback_source_ip))
return False # IPv6 TODO
net = IPv4Network(self.callback_source_ip)
<|code_end|>
, determine the next line of code. You have imports:
import json
from ipaddress import IPv4Address, IPv4Network
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings as project_settings
from .base import BackendBase
from coinbase.wallet.client import Client
and context (class names, function names, or code) available:
# Path: payments/backends/base.py
# class BackendBase:
# backend_id = None
# backend_verbose_name = ""
# backend_display_name = ""
# backend_enabled = False
# backend_has_recurring = False
#
# def __init__(self, settings):
# pass
#
# def new_payment(self, payment):
# """ Initialize a payment and returns an URL to redirect the user.
# Can return a HTML string that will be sent back to the user in a
# default template (like a form) or a HTTP response (like a redirect).
# """
# raise NotImplementedError()
#
# def callback(self, payment, request):
# """ Handle a callback """
# raise NotImplementedError()
#
# def callback_subscr(self, payment, request):
# """ Handle a callback (recurring payments) """
# raise NotImplementedError()
#
# def cancel_subscription(self, subscr):
# """ Cancel a subscription """
# raise NotImplementedError()
#
# def get_info(self):
# """ Returns some status (key, value) list """
# return ()
#
# def get_ext_url(self, payment):
# """ Returns URL to external payment view, or None """
# return None
#
# def get_subscr_ext_url(self, subscr):
# """ Returns URL to external payment view, or None """
# return None
. Output only the next line. | if IPv4Address(request.META['REMOTE_ADDR']) not in net: |
Next line prediction: <|code_start|>
def some_settings(request):
client_ip = get_client_ip(request)
return {
'CLIENT_IP': client_ip,
'CLIENT_ON_VPN': is_vpn_gateway(client_ip),
'ROOT_URL': settings.ROOT_URL,
'ADDITIONAL_HTML': settings.ADDITIONAL_HTML,
<|code_end|>
. Use current file imports:
(from django.conf import settings
from ccvpn.common import get_client_ip
from lambdainst.core import is_vpn_gateway)
and context including class names, function names, or small code snippets from other files:
# Path: ccvpn/common.py
# def get_client_ip(request):
# header_name = settings.REAL_IP_HEADER_NAME
#
# if header_name:
# header_name = header_name.replace('-', '_').upper()
# value = request.META.get('HTTP_' + header_name)
# if value:
# return value.split(',', 1)[0]
#
# return request.META.get('REMOTE_ADDR')
#
# Path: lambdainst/core.py
# def is_vpn_gateway(ip):
# addresses = get_gateway_exit_ips()
# return ip in addresses
. Output only the next line. | 'ADDITIONAL_HEADER_HTML': settings.ADDITIONAL_HEADER_HTML, |
Continue the code snippet: <|code_start|>
def some_settings(request):
client_ip = get_client_ip(request)
return {
'CLIENT_IP': client_ip,
'CLIENT_ON_VPN': is_vpn_gateway(client_ip),
'ROOT_URL': settings.ROOT_URL,
'ADDITIONAL_HTML': settings.ADDITIONAL_HTML,
'ADDITIONAL_HEADER_HTML': settings.ADDITIONAL_HEADER_HTML,
<|code_end|>
. Use current file imports:
from django.conf import settings
from ccvpn.common import get_client_ip
from lambdainst.core import is_vpn_gateway
and context (classes, functions, or code) from other files:
# Path: ccvpn/common.py
# def get_client_ip(request):
# header_name = settings.REAL_IP_HEADER_NAME
#
# if header_name:
# header_name = header_name.replace('-', '_').upper()
# value = request.META.get('HTTP_' + header_name)
# if value:
# return value.split(',', 1)[0]
#
# return request.META.get('REMOTE_ADDR')
#
# Path: lambdainst/core.py
# def is_vpn_gateway(ip):
# addresses = get_gateway_exit_ips()
# return ip in addresses
. Output only the next line. | } |
Given the following code snippet before the placeholder: <|code_start|>)
# All known backends (classes)
BACKENDS = {}
BACKEND_CHOICES = []
# All enabled backends (configured instances)
ACTIVE_BACKENDS = {}
ACTIVE_BACKEND_CHOICES = []
for cls in BackendBase.__subclasses__():
name = cls.backend_id
assert isinstance(name, str)
if name not in backends_settings:
continue
backend_settings = backends_settings.get(name, {})
for k, v in backend_settings.items():
if hasattr(v, '__call__'):
backend_settings[k] = v()
obj = cls(backend_settings)
if not obj.backend_enabled:
if name in backends_settings:
raise Exception("Invalid settings for payment backend %r" % name)
BACKENDS[name] = obj
BACKEND_CHOICES.append((name, cls.backend_verbose_name))
<|code_end|>
, predict the next line using imports from the current file:
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
from datetime import timedelta
from ccvpn.common import get_price
from .backends import BackendBase
and context including class names, function names, and sometimes code from other files:
# Path: ccvpn/common.py
# def get_price():
# return config.MONTHLY_PRICE_EUR
#
# Path: payments/backends/base.py
# class BackendBase:
# backend_id = None
# backend_verbose_name = ""
# backend_display_name = ""
# backend_enabled = False
# backend_has_recurring = False
#
# def __init__(self, settings):
# pass
#
# def new_payment(self, payment):
# """ Initialize a payment and returns an URL to redirect the user.
# Can return a HTML string that will be sent back to the user in a
# default template (like a form) or a HTTP response (like a redirect).
# """
# raise NotImplementedError()
#
# def callback(self, payment, request):
# """ Handle a callback """
# raise NotImplementedError()
#
# def callback_subscr(self, payment, request):
# """ Handle a callback (recurring payments) """
# raise NotImplementedError()
#
# def cancel_subscription(self, subscr):
# """ Cancel a subscription """
# raise NotImplementedError()
#
# def get_info(self):
# """ Returns some status (key, value) list """
# return ()
#
# def get_ext_url(self, payment):
# """ Returns URL to external payment view, or None """
# return None
#
# def get_subscr_ext_url(self, subscr):
# """ Returns URL to external payment view, or None """
# return None
. Output only the next line. | if obj.backend_enabled: |
Here is a snippet: <|code_start|>
if name not in backends_settings:
continue
backend_settings = backends_settings.get(name, {})
for k, v in backend_settings.items():
if hasattr(v, '__call__'):
backend_settings[k] = v()
obj = cls(backend_settings)
if not obj.backend_enabled:
if name in backends_settings:
raise Exception("Invalid settings for payment backend %r" % name)
BACKENDS[name] = obj
BACKEND_CHOICES.append((name, cls.backend_verbose_name))
if obj.backend_enabled:
ACTIVE_BACKENDS[name] = obj
ACTIVE_BACKEND_CHOICES.append((name, cls.backend_verbose_name))
BACKEND_CHOICES = sorted(BACKEND_CHOICES, key=lambda x: x[0])
ACTIVE_BACKEND_CHOICES = sorted(ACTIVE_BACKEND_CHOICES, key=lambda x: x[0])
def period_months(p):
return {
'3m': 3,
'6m': 6,
'12m': 12,
<|code_end|>
. Write the next line using the current file imports:
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
from datetime import timedelta
from ccvpn.common import get_price
from .backends import BackendBase
and context from other files:
# Path: ccvpn/common.py
# def get_price():
# return config.MONTHLY_PRICE_EUR
#
# Path: payments/backends/base.py
# class BackendBase:
# backend_id = None
# backend_verbose_name = ""
# backend_display_name = ""
# backend_enabled = False
# backend_has_recurring = False
#
# def __init__(self, settings):
# pass
#
# def new_payment(self, payment):
# """ Initialize a payment and returns an URL to redirect the user.
# Can return a HTML string that will be sent back to the user in a
# default template (like a form) or a HTTP response (like a redirect).
# """
# raise NotImplementedError()
#
# def callback(self, payment, request):
# """ Handle a callback """
# raise NotImplementedError()
#
# def callback_subscr(self, payment, request):
# """ Handle a callback (recurring payments) """
# raise NotImplementedError()
#
# def cancel_subscription(self, subscr):
# """ Cancel a subscription """
# raise NotImplementedError()
#
# def get_info(self):
# """ Returns some status (key, value) list """
# return ()
#
# def get_ext_url(self, payment):
# """ Returns URL to external payment view, or None """
# return None
#
# def get_subscr_ext_url(self, subscr):
# """ Returns URL to external payment view, or None """
# return None
, which may include functions, classes, or code. Output only the next line. | }[p] |
Based on the snippet: <|code_start|>
@login_required
def new(request):
if request.method != 'POST':
return redirect('account:index')
form = NewPaymentForm(request.POST)
if not form.is_valid():
return redirect('account:index')
if request.user.vpnuser.get_subscription() is not None:
return redirect('account:index')
subscr = form.cleaned_data['subscr'] == '1'
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import timedelta
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from .forms import NewPaymentForm
from .models import Payment, Subscription, BACKENDS, ACTIVE_BACKENDS
and context (classes, functions, sometimes code) from other files:
# Path: payments/forms.py
# class NewPaymentForm(forms.Form):
# TIME_CHOICES = (
# ('1', '1'),
# ('3', '3'),
# ('6', '6'),
# ('12', '12'),
# )
#
# subscr = forms.ChoiceField(choices=(('0', 'no'), ('1', 'yes')))
# time = forms.ChoiceField(choices=TIME_CHOICES)
# method = forms.ChoiceField(choices=BACKEND_CHOICES)
#
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
#
# class Subscription(models.Model):
# """ Recurring payment subscription. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# created = models.DateTimeField(auto_now_add=True)
# period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
# last_confirmed_payment = models.DateTimeField(blank=True, null=True)
# status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# @property
# def months(self):
# return period_months(self.period)
#
# @property
# def period_amount(self):
# return self.months * get_price()
#
# @property
# def next_renew(self):
# """ Approximate date of the next payment """
# if self.last_confirmed_payment:
# return self.last_confirmed_payment + timedelta(days=self.months * 30)
# return self.created + timedelta(days=self.months * 30)
#
# @property
# def monthly_amount(self):
# return get_price()
#
# def create_payment(self):
# payment = Payment(
# user=self.user,
# backend_id=self.backend_id,
# status='new',
# time=timedelta(days=30 * self.months),
# amount=get_price() * self.months,
# subscription=self,
# )
# return payment
#
# BACKENDS = {}
#
# ACTIVE_BACKENDS = {}
. Output only the next line. | backend_id = form.cleaned_data['method'] |
Given the code snippet: <|code_start|> return redirect('account:index')
rps = Subscription(
user=request.user,
backend_id=backend_id,
period=str(months) + 'm',
)
rps.save()
r = rps.backend.new_subscription(rps)
else:
payment = Payment.create_payment(backend_id, request.user, months)
payment.save()
r = payment.backend.new_payment(payment)
if not r:
payment.status = 'error'
payment.save()
raise Exception("Failed to initialize payment #%d" % payment.id)
if isinstance(r, str):
return render(request, 'payments/form.html', dict(html=r))
elif r is None:
return redirect('payments:view', payment.id)
return r
<|code_end|>
, generate the next line using the imports in this file:
from datetime import timedelta
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from .forms import NewPaymentForm
from .models import Payment, Subscription, BACKENDS, ACTIVE_BACKENDS
and context (functions, classes, or occasionally code) from other files:
# Path: payments/forms.py
# class NewPaymentForm(forms.Form):
# TIME_CHOICES = (
# ('1', '1'),
# ('3', '3'),
# ('6', '6'),
# ('12', '12'),
# )
#
# subscr = forms.ChoiceField(choices=(('0', 'no'), ('1', 'yes')))
# time = forms.ChoiceField(choices=TIME_CHOICES)
# method = forms.ChoiceField(choices=BACKEND_CHOICES)
#
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
#
# class Subscription(models.Model):
# """ Recurring payment subscription. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# created = models.DateTimeField(auto_now_add=True)
# period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
# last_confirmed_payment = models.DateTimeField(blank=True, null=True)
# status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# @property
# def months(self):
# return period_months(self.period)
#
# @property
# def period_amount(self):
# return self.months * get_price()
#
# @property
# def next_renew(self):
# """ Approximate date of the next payment """
# if self.last_confirmed_payment:
# return self.last_confirmed_payment + timedelta(days=self.months * 30)
# return self.created + timedelta(days=self.months * 30)
#
# @property
# def monthly_amount(self):
# return get_price()
#
# def create_payment(self):
# payment = Payment(
# user=self.user,
# backend_id=self.backend_id,
# status='new',
# time=timedelta(days=30 * self.months),
# amount=get_price() * self.months,
# subscription=self,
# )
# return payment
#
# BACKENDS = {}
#
# ACTIVE_BACKENDS = {}
. Output only the next line. | @csrf_exempt |
Using the snippet: <|code_start|>
@login_required
def new(request):
if request.method != 'POST':
return redirect('account:index')
form = NewPaymentForm(request.POST)
if not form.is_valid():
return redirect('account:index')
if request.user.vpnuser.get_subscription() is not None:
return redirect('account:index')
subscr = form.cleaned_data['subscr'] == '1'
<|code_end|>
, determine the next line of code. You have imports:
from datetime import timedelta
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from .forms import NewPaymentForm
from .models import Payment, Subscription, BACKENDS, ACTIVE_BACKENDS
and context (class names, function names, or code) available:
# Path: payments/forms.py
# class NewPaymentForm(forms.Form):
# TIME_CHOICES = (
# ('1', '1'),
# ('3', '3'),
# ('6', '6'),
# ('12', '12'),
# )
#
# subscr = forms.ChoiceField(choices=(('0', 'no'), ('1', 'yes')))
# time = forms.ChoiceField(choices=TIME_CHOICES)
# method = forms.ChoiceField(choices=BACKEND_CHOICES)
#
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
#
# class Subscription(models.Model):
# """ Recurring payment subscription. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# created = models.DateTimeField(auto_now_add=True)
# period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
# last_confirmed_payment = models.DateTimeField(blank=True, null=True)
# status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# @property
# def months(self):
# return period_months(self.period)
#
# @property
# def period_amount(self):
# return self.months * get_price()
#
# @property
# def next_renew(self):
# """ Approximate date of the next payment """
# if self.last_confirmed_payment:
# return self.last_confirmed_payment + timedelta(days=self.months * 30)
# return self.created + timedelta(days=self.months * 30)
#
# @property
# def monthly_amount(self):
# return get_price()
#
# def create_payment(self):
# payment = Payment(
# user=self.user,
# backend_id=self.backend_id,
# status='new',
# time=timedelta(days=30 * self.months),
# amount=get_price() * self.months,
# subscription=self,
# )
# return payment
#
# BACKENDS = {}
#
# ACTIVE_BACKENDS = {}
. Output only the next line. | backend_id = form.cleaned_data['method'] |
Given the code snippet: <|code_start|> return redirect('account:index')
subscr = form.cleaned_data['subscr'] == '1'
backend_id = form.cleaned_data['method']
months = int(form.cleaned_data['time'])
if backend_id not in ACTIVE_BACKENDS:
return HttpResponseNotFound()
if subscr:
if months not in (3, 6, 12):
return redirect('account:index')
rps = Subscription(
user=request.user,
backend_id=backend_id,
period=str(months) + 'm',
)
rps.save()
r = rps.backend.new_subscription(rps)
else:
payment = Payment.create_payment(backend_id, request.user, months)
payment.save()
r = payment.backend.new_payment(payment)
if not r:
payment.status = 'error'
<|code_end|>
, generate the next line using the imports in this file:
from datetime import timedelta
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from .forms import NewPaymentForm
from .models import Payment, Subscription, BACKENDS, ACTIVE_BACKENDS
and context (functions, classes, or occasionally code) from other files:
# Path: payments/forms.py
# class NewPaymentForm(forms.Form):
# TIME_CHOICES = (
# ('1', '1'),
# ('3', '3'),
# ('6', '6'),
# ('12', '12'),
# )
#
# subscr = forms.ChoiceField(choices=(('0', 'no'), ('1', 'yes')))
# time = forms.ChoiceField(choices=TIME_CHOICES)
# method = forms.ChoiceField(choices=BACKEND_CHOICES)
#
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
#
# class Subscription(models.Model):
# """ Recurring payment subscription. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# created = models.DateTimeField(auto_now_add=True)
# period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
# last_confirmed_payment = models.DateTimeField(blank=True, null=True)
# status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# @property
# def months(self):
# return period_months(self.period)
#
# @property
# def period_amount(self):
# return self.months * get_price()
#
# @property
# def next_renew(self):
# """ Approximate date of the next payment """
# if self.last_confirmed_payment:
# return self.last_confirmed_payment + timedelta(days=self.months * 30)
# return self.created + timedelta(days=self.months * 30)
#
# @property
# def monthly_amount(self):
# return get_price()
#
# def create_payment(self):
# payment = Payment(
# user=self.user,
# backend_id=self.backend_id,
# status='new',
# time=timedelta(days=30 * self.months),
# amount=get_price() * self.months,
# subscription=self,
# )
# return payment
#
# BACKENDS = {}
#
# ACTIVE_BACKENDS = {}
. Output only the next line. | payment.save() |
Given the code snippet: <|code_start|>
@login_required
def new(request):
if request.method != 'POST':
return redirect('account:index')
form = NewPaymentForm(request.POST)
if not form.is_valid():
return redirect('account:index')
if request.user.vpnuser.get_subscription() is not None:
return redirect('account:index')
subscr = form.cleaned_data['subscr'] == '1'
backend_id = form.cleaned_data['method']
months = int(form.cleaned_data['time'])
if backend_id not in ACTIVE_BACKENDS:
return HttpResponseNotFound()
if subscr:
if months not in (3, 6, 12):
return redirect('account:index')
rps = Subscription(
user=request.user,
<|code_end|>
, generate the next line using the imports in this file:
from datetime import timedelta
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from .forms import NewPaymentForm
from .models import Payment, Subscription, BACKENDS, ACTIVE_BACKENDS
and context (functions, classes, or occasionally code) from other files:
# Path: payments/forms.py
# class NewPaymentForm(forms.Form):
# TIME_CHOICES = (
# ('1', '1'),
# ('3', '3'),
# ('6', '6'),
# ('12', '12'),
# )
#
# subscr = forms.ChoiceField(choices=(('0', 'no'), ('1', 'yes')))
# time = forms.ChoiceField(choices=TIME_CHOICES)
# method = forms.ChoiceField(choices=BACKEND_CHOICES)
#
# Path: payments/models.py
# class Payment(models.Model):
# """ Just a payment.
# If subscription is not null, it has been automatically issued.
# backend_extid is the external transaction ID, backend_data is other
# things that should only be used by the associated backend.
# """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
# created = models.DateTimeField(auto_now_add=True)
# modified = models.DateTimeField(auto_now=True)
# confirmed_on = models.DateTimeField(null=True, blank=True)
# amount = models.IntegerField()
# paid_amount = models.IntegerField(default=0)
# time = models.DurationField()
# subscription = models.ForeignKey('Subscription', null=True, blank=True)
# status_message = models.TextField(blank=True, null=True)
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def currency_code(self):
# return CURRENCY_CODE
#
# @property
# def currency_name(self):
# return CURRENCY_NAME
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# def get_amount_display(self):
# return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
#
# @property
# def is_confirmed(self):
# return self.status == 'confirmed'
#
# class Meta:
# ordering = ('-created', )
#
# @classmethod
# def create_payment(self, backend_id, user, months):
# payment = Payment(
# user=user,
# backend_id=backend_id,
# status='new',
# time=timedelta(days=30 * months),
# amount=get_price() * months
# )
# return payment
#
# class Subscription(models.Model):
# """ Recurring payment subscription. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
# created = models.DateTimeField(auto_now_add=True)
# period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
# last_confirmed_payment = models.DateTimeField(blank=True, null=True)
# status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
#
# backend_extid = models.CharField(max_length=64, null=True, blank=True)
# backend_data = JSONField(blank=True)
#
# @property
# def backend(self):
# """ Returns a global instance of the backend
# :rtype: BackendBase
# """
# return BACKENDS[self.backend_id]
#
# @property
# def months(self):
# return period_months(self.period)
#
# @property
# def period_amount(self):
# return self.months * get_price()
#
# @property
# def next_renew(self):
# """ Approximate date of the next payment """
# if self.last_confirmed_payment:
# return self.last_confirmed_payment + timedelta(days=self.months * 30)
# return self.created + timedelta(days=self.months * 30)
#
# @property
# def monthly_amount(self):
# return get_price()
#
# def create_payment(self):
# payment = Payment(
# user=self.user,
# backend_id=self.backend_id,
# status='new',
# time=timedelta(days=30 * self.months),
# amount=get_price() * self.months,
# subscription=self,
# )
# return payment
#
# BACKENDS = {}
#
# ACTIVE_BACKENDS = {}
. Output only the next line. | backend_id=backend_id, |
Here is a snippet: <|code_start|>
CURRENCY_CODE, CURRENCY_NAME = settings.PAYMENTS_CURRENCY
class Command(BaseCommand):
help = "Update Stripe plans"
def add_arguments(self, parser):
parser.add_argument('--force-run', action='store_true',
help="Run even when Stripe backend is disabled")
parser.add_argument('--force-update', action='store_true',
help="Replace plans, including matching ones")
def handle(self, *args, **options):
if 'stripe' not in ACTIVE_BACKENDS and options['force-run'] is False:
raise CommandError("stripe backend not active.")
backend = ACTIVE_BACKENDS['stripe']
<|code_end|>
. Write the next line using the current file imports:
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from ccvpn.common import get_price
from payments.models import ACTIVE_BACKENDS, SUBSCR_PERIOD_CHOICES, period_months
and context from other files:
# Path: ccvpn/common.py
# def get_price():
# return config.MONTHLY_PRICE_EUR
#
# Path: payments/models.py
# ACTIVE_BACKENDS = {}
#
# SUBSCR_PERIOD_CHOICES = (
# ('3m', _("Every 3 months")),
# ('6m', _("Every 6 months")),
# ('12m', _("Every year")),
# )
#
# def period_months(p):
# return {
# '3m': 3,
# '6m': 6,
# '12m': 12,
# }[p]
, which may include functions, classes, or code. Output only the next line. | stripe = backend.stripe |
Given the following code snippet before the placeholder: <|code_start|>
for period_id, period_name in SUBSCR_PERIOD_CHOICES:
plan_id = backend.get_plan_id(period_id)
months = period_months(period_id)
amount = months * get_price()
kwargs = dict(
id=plan_id,
amount=amount,
interval='month',
interval_count=months,
name=backend.name + " (%s)" % period_id,
currency=CURRENCY_CODE,
)
self.stdout.write('Plan %s: %d months for %.2f %s (%s)... ' % (
plan_id, months, amount / 100, CURRENCY_NAME, CURRENCY_CODE), ending='')
self.stdout.flush()
try:
plan = stripe.Plan.retrieve(plan_id)
except stripe.error.InvalidRequestError:
plan = None
def is_valid_plan():
if not plan:
return False
for k, v in kwargs.items():
if getattr(plan, k) != v:
return False
<|code_end|>
, predict the next line using imports from the current file:
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from ccvpn.common import get_price
from payments.models import ACTIVE_BACKENDS, SUBSCR_PERIOD_CHOICES, period_months
and context including class names, function names, and sometimes code from other files:
# Path: ccvpn/common.py
# def get_price():
# return config.MONTHLY_PRICE_EUR
#
# Path: payments/models.py
# ACTIVE_BACKENDS = {}
#
# SUBSCR_PERIOD_CHOICES = (
# ('3m', _("Every 3 months")),
# ('6m', _("Every 6 months")),
# ('12m', _("Every year")),
# )
#
# def period_months(p):
# return {
# '3m': 3,
# '6m': 6,
# '12m': 12,
# }[p]
. Output only the next line. | return True |
Next line prediction: <|code_start|> def handle(self, *args, **options):
if 'stripe' not in ACTIVE_BACKENDS and options['force-run'] is False:
raise CommandError("stripe backend not active.")
backend = ACTIVE_BACKENDS['stripe']
stripe = backend.stripe
for period_id, period_name in SUBSCR_PERIOD_CHOICES:
plan_id = backend.get_plan_id(period_id)
months = period_months(period_id)
amount = months * get_price()
kwargs = dict(
id=plan_id,
amount=amount,
interval='month',
interval_count=months,
name=backend.name + " (%s)" % period_id,
currency=CURRENCY_CODE,
)
self.stdout.write('Plan %s: %d months for %.2f %s (%s)... ' % (
plan_id, months, amount / 100, CURRENCY_NAME, CURRENCY_CODE), ending='')
self.stdout.flush()
try:
plan = stripe.Plan.retrieve(plan_id)
except stripe.error.InvalidRequestError:
plan = None
<|code_end|>
. Use current file imports:
(from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from ccvpn.common import get_price
from payments.models import ACTIVE_BACKENDS, SUBSCR_PERIOD_CHOICES, period_months)
and context including class names, function names, or small code snippets from other files:
# Path: ccvpn/common.py
# def get_price():
# return config.MONTHLY_PRICE_EUR
#
# Path: payments/models.py
# ACTIVE_BACKENDS = {}
#
# SUBSCR_PERIOD_CHOICES = (
# ('3m', _("Every 3 months")),
# ('6m', _("Every 6 months")),
# ('12m', _("Every year")),
# )
#
# def period_months(p):
# return {
# '3m': 3,
# '6m': 6,
# '12m': 12,
# }[p]
. Output only the next line. | def is_valid_plan(): |
Given the following code snippet before the placeholder: <|code_start|> help="Run even when Stripe backend is disabled")
parser.add_argument('--force-update', action='store_true',
help="Replace plans, including matching ones")
def handle(self, *args, **options):
if 'stripe' not in ACTIVE_BACKENDS and options['force-run'] is False:
raise CommandError("stripe backend not active.")
backend = ACTIVE_BACKENDS['stripe']
stripe = backend.stripe
for period_id, period_name in SUBSCR_PERIOD_CHOICES:
plan_id = backend.get_plan_id(period_id)
months = period_months(period_id)
amount = months * get_price()
kwargs = dict(
id=plan_id,
amount=amount,
interval='month',
interval_count=months,
name=backend.name + " (%s)" % period_id,
currency=CURRENCY_CODE,
)
self.stdout.write('Plan %s: %d months for %.2f %s (%s)... ' % (
plan_id, months, amount / 100, CURRENCY_NAME, CURRENCY_CODE), ending='')
self.stdout.flush()
try:
<|code_end|>
, predict the next line using imports from the current file:
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from ccvpn.common import get_price
from payments.models import ACTIVE_BACKENDS, SUBSCR_PERIOD_CHOICES, period_months
and context including class names, function names, and sometimes code from other files:
# Path: ccvpn/common.py
# def get_price():
# return config.MONTHLY_PRICE_EUR
#
# Path: payments/models.py
# ACTIVE_BACKENDS = {}
#
# SUBSCR_PERIOD_CHOICES = (
# ('3m', _("Every 3 months")),
# ('6m', _("Every 6 months")),
# ('12m', _("Every year")),
# )
#
# def period_months(p):
# return {
# '3m': 3,
# '6m': 6,
# '12m': 12,
# }[p]
. Output only the next line. | plan = stripe.Plan.retrieve(plan_id) |
Predict the next line after this snippet: <|code_start|>
def test_calculate_our_hand_cost():
table = Table()
player = table.player
enemy_seat = 2
table.add_called_riichi_step_one(enemy_seat)
table.add_discarded_tile(enemy_seat, string_to_136_tile(pin="9"), True)
tiles = string_to_136_array(sou="234678", pin="23478", man="22")
<|code_end|>
using the current file's imports:
from game.table import Table
from mahjong.constants import FIVE_RED_MAN
from utils.decisions_logger import MeldPrint
from utils.test_helpers import find_discard_option, string_to_136_array, string_to_136_tile
from project.utils.test_helpers import make_meld
and any relevant context from other files:
# Path: project/utils/test_helpers.py
# def make_meld(meld_type, is_open=True, man="", pin="", sou="", honors="", tiles=None):
# if not tiles:
# tiles = string_to_136_array(man=man, pin=pin, sou=sou, honors=honors)
# meld = MeldPrint(
# meld_type=meld_type,
# tiles=tiles,
# opened=is_open,
# called_tile=tiles[0],
# who=0,
# )
# return meld
. Output only the next line. | tile = string_to_136_tile(honors="1") |
Continue the code snippet: <|code_start|> self.assertEqual(get_language(), "nl")
with override("id"):
self.assertEqual(get_language(), "en")
def test_split_translated_fieldname(self):
self.assertEqual(split_translated_fieldname("title_nl"), ("title", "nl"))
self.assertEqual(split_translated_fieldname("full_name_nl"), ("full_name", "nl"))
def test_transform_translatable_fields(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo"}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_without_translations(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo", "i18n": None}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_keep_translations(self):
self.assertEqual(
transform_translatable_fields(
Blog, {"title": "bar", "title_de": "das foo", "i18n": {"title_nl": "foo"}}
),
{"i18n": {"title_nl": "foo", "title_de": "das foo"}, "title": "bar"},
)
<|code_end|>
. Use current file imports:
from django.test import TestCase
from django.utils.translation import override
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (
build_localized_fieldname,
get_instance_field_value,
get_language,
get_model_field,
split_translated_fieldname,
)
from .app.models import Blog, Category
and context (classes, functions, or code) from other files:
# Path: modeltrans/manager.py
# def transform_translatable_fields(model, fields):
# """
# Transform the kwargs for a <Model>.objects.create() or <Model>()
# to allow passing translated field names.
#
# Arguments:
# fields (dict): kwargs to a model __init__ or Model.objects.create() method
# for which the field names need to be translated to values in the i18n field
# """
# # If the current model does have the TranslationField, we must not apply
# # any transformation for it will result in a:
# # TypeError: 'i18n' is an invalid keyword argument for this function
# if not hasattr(model, "i18n"):
# return fields
#
# ret = {"i18n": fields.pop("i18n", None) or {}}
#
# # keep track of translated fields, and do not return an `i18n` key if no
# # translated fields are found.
# has_translated_fields = len(ret["i18n"].items()) > 0
#
# for field_name, value in fields.items():
# try:
# field = model._meta.get_field(field_name)
# except FieldDoesNotExist:
# ret[field_name] = value
# continue
#
# if isinstance(field, TranslatedVirtualField):
# has_translated_fields = True
# if field.get_language() == get_default_language():
# if field.original_name in fields:
# raise ValueError(
# 'Attempted override of "{}" with "{}". '
# "Only one of the two is allowed.".format(field.original_name, field_name)
# )
# ret[field.original_name] = value
# else:
# ret["i18n"][field.name] = value
# else:
# ret[field_name] = value
#
# if not has_translated_fields:
# return fields
#
# return ret
#
# Path: modeltrans/utils.py
# def build_localized_fieldname(field_name, lang, ignore_default=False):
# if lang == "id":
# # The 2-letter Indonesian language code is problematic with the
# # current naming scheme as Django foreign keys also add "id" suffix.
# lang = "ind"
# if ignore_default and lang == get_default_language():
# return field_name
# return "{}_{}".format(field_name, lang.replace("-", "_"))
#
# def get_instance_field_value(instance, path):
# """
# Return the value of a field or related field for a model instance.
# """
# value = instance
# for bit in path.split(LOOKUP_SEP):
# try:
# value = getattr(value, bit)
# except AttributeError:
# return None
#
# return value
#
# def get_language():
# """
# Return an active language code that is guaranteed to be in settings.LANGUAGES
#
# (Django does not seem to guarantee this for us.)
# """
# lang = _get_language()
# if lang in get_available_languages():
# return lang
# return get_default_language()
#
# def get_model_field(model, path):
# """
# Return the django model field for model in context, following relations.
# """
#
# if not hasattr(model, "_meta"):
# raise ValueError("Argument 'Model' must be a django.db.models.Model instance.")
#
# field = None
# for bit in path.split(LOOKUP_SEP):
# try:
# field = model._meta.get_field(bit)
# except FieldDoesNotExist:
# return None
#
# if hasattr(field, "remote_field"):
# rel = getattr(field, "remote_field", None)
# model = getattr(rel, "model", model)
#
# return field
#
# def split_translated_fieldname(field_name):
# _pos = field_name.rfind("_")
# return (field_name[0:_pos], field_name[_pos + 1 :])
#
# Path: tests/app/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=255)
# body = models.TextField(null=True)
#
# category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
# site = models.ForeignKey(Site, null=True, blank=True, on_delete=models.CASCADE)
#
# i18n = TranslationField(fields=("title", "body"), required_languages=("nl",))
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
#
# name = models.CharField(max_length=255)
# title = models.CharField(max_length=255)
#
# i18n = TranslationField(fields=("name", "title"))
#
# objects = CategoryQueryset.as_manager()
#
# def __str__(self):
# return self.name
. Output only the next line. | def test_build_localized_fieldname(self): |
Based on the snippet: <|code_start|> self.assertEqual(get_language(), "en")
with override("nl"):
self.assertEqual(get_language(), "nl")
with override("id"):
self.assertEqual(get_language(), "en")
def test_split_translated_fieldname(self):
self.assertEqual(split_translated_fieldname("title_nl"), ("title", "nl"))
self.assertEqual(split_translated_fieldname("full_name_nl"), ("full_name", "nl"))
def test_transform_translatable_fields(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo"}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_without_translations(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo", "i18n": None}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_keep_translations(self):
self.assertEqual(
transform_translatable_fields(
Blog, {"title": "bar", "title_de": "das foo", "i18n": {"title_nl": "foo"}}
),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase
from django.utils.translation import override
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (
build_localized_fieldname,
get_instance_field_value,
get_language,
get_model_field,
split_translated_fieldname,
)
from .app.models import Blog, Category
and context (classes, functions, sometimes code) from other files:
# Path: modeltrans/manager.py
# def transform_translatable_fields(model, fields):
# """
# Transform the kwargs for a <Model>.objects.create() or <Model>()
# to allow passing translated field names.
#
# Arguments:
# fields (dict): kwargs to a model __init__ or Model.objects.create() method
# for which the field names need to be translated to values in the i18n field
# """
# # If the current model does have the TranslationField, we must not apply
# # any transformation for it will result in a:
# # TypeError: 'i18n' is an invalid keyword argument for this function
# if not hasattr(model, "i18n"):
# return fields
#
# ret = {"i18n": fields.pop("i18n", None) or {}}
#
# # keep track of translated fields, and do not return an `i18n` key if no
# # translated fields are found.
# has_translated_fields = len(ret["i18n"].items()) > 0
#
# for field_name, value in fields.items():
# try:
# field = model._meta.get_field(field_name)
# except FieldDoesNotExist:
# ret[field_name] = value
# continue
#
# if isinstance(field, TranslatedVirtualField):
# has_translated_fields = True
# if field.get_language() == get_default_language():
# if field.original_name in fields:
# raise ValueError(
# 'Attempted override of "{}" with "{}". '
# "Only one of the two is allowed.".format(field.original_name, field_name)
# )
# ret[field.original_name] = value
# else:
# ret["i18n"][field.name] = value
# else:
# ret[field_name] = value
#
# if not has_translated_fields:
# return fields
#
# return ret
#
# Path: modeltrans/utils.py
# def build_localized_fieldname(field_name, lang, ignore_default=False):
# if lang == "id":
# # The 2-letter Indonesian language code is problematic with the
# # current naming scheme as Django foreign keys also add "id" suffix.
# lang = "ind"
# if ignore_default and lang == get_default_language():
# return field_name
# return "{}_{}".format(field_name, lang.replace("-", "_"))
#
# def get_instance_field_value(instance, path):
# """
# Return the value of a field or related field for a model instance.
# """
# value = instance
# for bit in path.split(LOOKUP_SEP):
# try:
# value = getattr(value, bit)
# except AttributeError:
# return None
#
# return value
#
# def get_language():
# """
# Return an active language code that is guaranteed to be in settings.LANGUAGES
#
# (Django does not seem to guarantee this for us.)
# """
# lang = _get_language()
# if lang in get_available_languages():
# return lang
# return get_default_language()
#
# def get_model_field(model, path):
# """
# Return the django model field for model in context, following relations.
# """
#
# if not hasattr(model, "_meta"):
# raise ValueError("Argument 'Model' must be a django.db.models.Model instance.")
#
# field = None
# for bit in path.split(LOOKUP_SEP):
# try:
# field = model._meta.get_field(bit)
# except FieldDoesNotExist:
# return None
#
# if hasattr(field, "remote_field"):
# rel = getattr(field, "remote_field", None)
# model = getattr(rel, "model", model)
#
# return field
#
# def split_translated_fieldname(field_name):
# _pos = field_name.rfind("_")
# return (field_name[0:_pos], field_name[_pos + 1 :])
#
# Path: tests/app/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=255)
# body = models.TextField(null=True)
#
# category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
# site = models.ForeignKey(Site, null=True, blank=True, on_delete=models.CASCADE)
#
# i18n = TranslationField(fields=("title", "body"), required_languages=("nl",))
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
#
# name = models.CharField(max_length=255)
# title = models.CharField(max_length=255)
#
# i18n = TranslationField(fields=("name", "title"))
#
# objects = CategoryQueryset.as_manager()
#
# def __str__(self):
# return self.name
. Output only the next line. | {"i18n": {"title_nl": "foo", "title_de": "das foo"}, "title": "bar"}, |
Given snippet: <|code_start|>
with override("nl"):
self.assertEqual(get_language(), "nl")
with override("id"):
self.assertEqual(get_language(), "en")
def test_split_translated_fieldname(self):
self.assertEqual(split_translated_fieldname("title_nl"), ("title", "nl"))
self.assertEqual(split_translated_fieldname("full_name_nl"), ("full_name", "nl"))
def test_transform_translatable_fields(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo"}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_without_translations(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo", "i18n": None}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_keep_translations(self):
self.assertEqual(
transform_translatable_fields(
Blog, {"title": "bar", "title_de": "das foo", "i18n": {"title_nl": "foo"}}
),
{"i18n": {"title_nl": "foo", "title_de": "das foo"}, "title": "bar"},
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from django.utils.translation import override
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (
build_localized_fieldname,
get_instance_field_value,
get_language,
get_model_field,
split_translated_fieldname,
)
from .app.models import Blog, Category
and context:
# Path: modeltrans/manager.py
# def transform_translatable_fields(model, fields):
# """
# Transform the kwargs for a <Model>.objects.create() or <Model>()
# to allow passing translated field names.
#
# Arguments:
# fields (dict): kwargs to a model __init__ or Model.objects.create() method
# for which the field names need to be translated to values in the i18n field
# """
# # If the current model does have the TranslationField, we must not apply
# # any transformation for it will result in a:
# # TypeError: 'i18n' is an invalid keyword argument for this function
# if not hasattr(model, "i18n"):
# return fields
#
# ret = {"i18n": fields.pop("i18n", None) or {}}
#
# # keep track of translated fields, and do not return an `i18n` key if no
# # translated fields are found.
# has_translated_fields = len(ret["i18n"].items()) > 0
#
# for field_name, value in fields.items():
# try:
# field = model._meta.get_field(field_name)
# except FieldDoesNotExist:
# ret[field_name] = value
# continue
#
# if isinstance(field, TranslatedVirtualField):
# has_translated_fields = True
# if field.get_language() == get_default_language():
# if field.original_name in fields:
# raise ValueError(
# 'Attempted override of "{}" with "{}". '
# "Only one of the two is allowed.".format(field.original_name, field_name)
# )
# ret[field.original_name] = value
# else:
# ret["i18n"][field.name] = value
# else:
# ret[field_name] = value
#
# if not has_translated_fields:
# return fields
#
# return ret
#
# Path: modeltrans/utils.py
# def build_localized_fieldname(field_name, lang, ignore_default=False):
# if lang == "id":
# # The 2-letter Indonesian language code is problematic with the
# # current naming scheme as Django foreign keys also add "id" suffix.
# lang = "ind"
# if ignore_default and lang == get_default_language():
# return field_name
# return "{}_{}".format(field_name, lang.replace("-", "_"))
#
# def get_instance_field_value(instance, path):
# """
# Return the value of a field or related field for a model instance.
# """
# value = instance
# for bit in path.split(LOOKUP_SEP):
# try:
# value = getattr(value, bit)
# except AttributeError:
# return None
#
# return value
#
# def get_language():
# """
# Return an active language code that is guaranteed to be in settings.LANGUAGES
#
# (Django does not seem to guarantee this for us.)
# """
# lang = _get_language()
# if lang in get_available_languages():
# return lang
# return get_default_language()
#
# def get_model_field(model, path):
# """
# Return the django model field for model in context, following relations.
# """
#
# if not hasattr(model, "_meta"):
# raise ValueError("Argument 'Model' must be a django.db.models.Model instance.")
#
# field = None
# for bit in path.split(LOOKUP_SEP):
# try:
# field = model._meta.get_field(bit)
# except FieldDoesNotExist:
# return None
#
# if hasattr(field, "remote_field"):
# rel = getattr(field, "remote_field", None)
# model = getattr(rel, "model", model)
#
# return field
#
# def split_translated_fieldname(field_name):
# _pos = field_name.rfind("_")
# return (field_name[0:_pos], field_name[_pos + 1 :])
#
# Path: tests/app/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=255)
# body = models.TextField(null=True)
#
# category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
# site = models.ForeignKey(Site, null=True, blank=True, on_delete=models.CASCADE)
#
# i18n = TranslationField(fields=("title", "body"), required_languages=("nl",))
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
#
# name = models.CharField(max_length=255)
# title = models.CharField(max_length=255)
#
# i18n = TranslationField(fields=("name", "title"))
#
# objects = CategoryQueryset.as_manager()
#
# def __str__(self):
# return self.name
which might include code, classes, or functions. Output only the next line. | ) |
Predict the next line for this snippet: <|code_start|>
class UtilsTest(TestCase):
def test_get_language(self):
self.assertEqual(get_language(), "en")
with override("nl"):
self.assertEqual(get_language(), "nl")
with override("id"):
self.assertEqual(get_language(), "en")
def test_split_translated_fieldname(self):
self.assertEqual(split_translated_fieldname("title_nl"), ("title", "nl"))
self.assertEqual(split_translated_fieldname("full_name_nl"), ("full_name", "nl"))
def test_transform_translatable_fields(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo"}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_without_translations(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo", "i18n": None}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_keep_translations(self):
<|code_end|>
with the help of current file imports:
from django.test import TestCase
from django.utils.translation import override
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (
build_localized_fieldname,
get_instance_field_value,
get_language,
get_model_field,
split_translated_fieldname,
)
from .app.models import Blog, Category
and context from other files:
# Path: modeltrans/manager.py
# def transform_translatable_fields(model, fields):
# """
# Transform the kwargs for a <Model>.objects.create() or <Model>()
# to allow passing translated field names.
#
# Arguments:
# fields (dict): kwargs to a model __init__ or Model.objects.create() method
# for which the field names need to be translated to values in the i18n field
# """
# # If the current model does have the TranslationField, we must not apply
# # any transformation for it will result in a:
# # TypeError: 'i18n' is an invalid keyword argument for this function
# if not hasattr(model, "i18n"):
# return fields
#
# ret = {"i18n": fields.pop("i18n", None) or {}}
#
# # keep track of translated fields, and do not return an `i18n` key if no
# # translated fields are found.
# has_translated_fields = len(ret["i18n"].items()) > 0
#
# for field_name, value in fields.items():
# try:
# field = model._meta.get_field(field_name)
# except FieldDoesNotExist:
# ret[field_name] = value
# continue
#
# if isinstance(field, TranslatedVirtualField):
# has_translated_fields = True
# if field.get_language() == get_default_language():
# if field.original_name in fields:
# raise ValueError(
# 'Attempted override of "{}" with "{}". '
# "Only one of the two is allowed.".format(field.original_name, field_name)
# )
# ret[field.original_name] = value
# else:
# ret["i18n"][field.name] = value
# else:
# ret[field_name] = value
#
# if not has_translated_fields:
# return fields
#
# return ret
#
# Path: modeltrans/utils.py
# def build_localized_fieldname(field_name, lang, ignore_default=False):
# if lang == "id":
# # The 2-letter Indonesian language code is problematic with the
# # current naming scheme as Django foreign keys also add "id" suffix.
# lang = "ind"
# if ignore_default and lang == get_default_language():
# return field_name
# return "{}_{}".format(field_name, lang.replace("-", "_"))
#
# def get_instance_field_value(instance, path):
# """
# Return the value of a field or related field for a model instance.
# """
# value = instance
# for bit in path.split(LOOKUP_SEP):
# try:
# value = getattr(value, bit)
# except AttributeError:
# return None
#
# return value
#
# def get_language():
# """
# Return an active language code that is guaranteed to be in settings.LANGUAGES
#
# (Django does not seem to guarantee this for us.)
# """
# lang = _get_language()
# if lang in get_available_languages():
# return lang
# return get_default_language()
#
# def get_model_field(model, path):
# """
# Return the django model field for model in context, following relations.
# """
#
# if not hasattr(model, "_meta"):
# raise ValueError("Argument 'Model' must be a django.db.models.Model instance.")
#
# field = None
# for bit in path.split(LOOKUP_SEP):
# try:
# field = model._meta.get_field(bit)
# except FieldDoesNotExist:
# return None
#
# if hasattr(field, "remote_field"):
# rel = getattr(field, "remote_field", None)
# model = getattr(rel, "model", model)
#
# return field
#
# def split_translated_fieldname(field_name):
# _pos = field_name.rfind("_")
# return (field_name[0:_pos], field_name[_pos + 1 :])
#
# Path: tests/app/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=255)
# body = models.TextField(null=True)
#
# category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
# site = models.ForeignKey(Site, null=True, blank=True, on_delete=models.CASCADE)
#
# i18n = TranslationField(fields=("title", "body"), required_languages=("nl",))
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
#
# name = models.CharField(max_length=255)
# title = models.CharField(max_length=255)
#
# i18n = TranslationField(fields=("name", "title"))
#
# objects = CategoryQueryset.as_manager()
#
# def __str__(self):
# return self.name
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual( |
Next line prediction: <|code_start|>
class UtilsTest(TestCase):
def test_get_language(self):
self.assertEqual(get_language(), "en")
<|code_end|>
. Use current file imports:
(from django.test import TestCase
from django.utils.translation import override
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (
build_localized_fieldname,
get_instance_field_value,
get_language,
get_model_field,
split_translated_fieldname,
)
from .app.models import Blog, Category)
and context including class names, function names, or small code snippets from other files:
# Path: modeltrans/manager.py
# def transform_translatable_fields(model, fields):
# """
# Transform the kwargs for a <Model>.objects.create() or <Model>()
# to allow passing translated field names.
#
# Arguments:
# fields (dict): kwargs to a model __init__ or Model.objects.create() method
# for which the field names need to be translated to values in the i18n field
# """
# # If the current model does have the TranslationField, we must not apply
# # any transformation for it will result in a:
# # TypeError: 'i18n' is an invalid keyword argument for this function
# if not hasattr(model, "i18n"):
# return fields
#
# ret = {"i18n": fields.pop("i18n", None) or {}}
#
# # keep track of translated fields, and do not return an `i18n` key if no
# # translated fields are found.
# has_translated_fields = len(ret["i18n"].items()) > 0
#
# for field_name, value in fields.items():
# try:
# field = model._meta.get_field(field_name)
# except FieldDoesNotExist:
# ret[field_name] = value
# continue
#
# if isinstance(field, TranslatedVirtualField):
# has_translated_fields = True
# if field.get_language() == get_default_language():
# if field.original_name in fields:
# raise ValueError(
# 'Attempted override of "{}" with "{}". '
# "Only one of the two is allowed.".format(field.original_name, field_name)
# )
# ret[field.original_name] = value
# else:
# ret["i18n"][field.name] = value
# else:
# ret[field_name] = value
#
# if not has_translated_fields:
# return fields
#
# return ret
#
# Path: modeltrans/utils.py
# def build_localized_fieldname(field_name, lang, ignore_default=False):
# if lang == "id":
# # The 2-letter Indonesian language code is problematic with the
# # current naming scheme as Django foreign keys also add "id" suffix.
# lang = "ind"
# if ignore_default and lang == get_default_language():
# return field_name
# return "{}_{}".format(field_name, lang.replace("-", "_"))
#
# def get_instance_field_value(instance, path):
# """
# Return the value of a field or related field for a model instance.
# """
# value = instance
# for bit in path.split(LOOKUP_SEP):
# try:
# value = getattr(value, bit)
# except AttributeError:
# return None
#
# return value
#
# def get_language():
# """
# Return an active language code that is guaranteed to be in settings.LANGUAGES
#
# (Django does not seem to guarantee this for us.)
# """
# lang = _get_language()
# if lang in get_available_languages():
# return lang
# return get_default_language()
#
# def get_model_field(model, path):
# """
# Return the django model field for model in context, following relations.
# """
#
# if not hasattr(model, "_meta"):
# raise ValueError("Argument 'Model' must be a django.db.models.Model instance.")
#
# field = None
# for bit in path.split(LOOKUP_SEP):
# try:
# field = model._meta.get_field(bit)
# except FieldDoesNotExist:
# return None
#
# if hasattr(field, "remote_field"):
# rel = getattr(field, "remote_field", None)
# model = getattr(rel, "model", model)
#
# return field
#
# def split_translated_fieldname(field_name):
# _pos = field_name.rfind("_")
# return (field_name[0:_pos], field_name[_pos + 1 :])
#
# Path: tests/app/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=255)
# body = models.TextField(null=True)
#
# category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
# site = models.ForeignKey(Site, null=True, blank=True, on_delete=models.CASCADE)
#
# i18n = TranslationField(fields=("title", "body"), required_languages=("nl",))
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
#
# name = models.CharField(max_length=255)
# title = models.CharField(max_length=255)
#
# i18n = TranslationField(fields=("name", "title"))
#
# objects = CategoryQueryset.as_manager()
#
# def __str__(self):
# return self.name
. Output only the next line. | with override("nl"): |
Based on the snippet: <|code_start|>
class UtilsTest(TestCase):
def test_get_language(self):
self.assertEqual(get_language(), "en")
<|code_end|>
, predict the immediate next line with the help of imports:
from django.test import TestCase
from django.utils.translation import override
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (
build_localized_fieldname,
get_instance_field_value,
get_language,
get_model_field,
split_translated_fieldname,
)
from .app.models import Blog, Category
and context (classes, functions, sometimes code) from other files:
# Path: modeltrans/manager.py
# def transform_translatable_fields(model, fields):
# """
# Transform the kwargs for a <Model>.objects.create() or <Model>()
# to allow passing translated field names.
#
# Arguments:
# fields (dict): kwargs to a model __init__ or Model.objects.create() method
# for which the field names need to be translated to values in the i18n field
# """
# # If the current model does have the TranslationField, we must not apply
# # any transformation for it will result in a:
# # TypeError: 'i18n' is an invalid keyword argument for this function
# if not hasattr(model, "i18n"):
# return fields
#
# ret = {"i18n": fields.pop("i18n", None) or {}}
#
# # keep track of translated fields, and do not return an `i18n` key if no
# # translated fields are found.
# has_translated_fields = len(ret["i18n"].items()) > 0
#
# for field_name, value in fields.items():
# try:
# field = model._meta.get_field(field_name)
# except FieldDoesNotExist:
# ret[field_name] = value
# continue
#
# if isinstance(field, TranslatedVirtualField):
# has_translated_fields = True
# if field.get_language() == get_default_language():
# if field.original_name in fields:
# raise ValueError(
# 'Attempted override of "{}" with "{}". '
# "Only one of the two is allowed.".format(field.original_name, field_name)
# )
# ret[field.original_name] = value
# else:
# ret["i18n"][field.name] = value
# else:
# ret[field_name] = value
#
# if not has_translated_fields:
# return fields
#
# return ret
#
# Path: modeltrans/utils.py
# def build_localized_fieldname(field_name, lang, ignore_default=False):
# if lang == "id":
# # The 2-letter Indonesian language code is problematic with the
# # current naming scheme as Django foreign keys also add "id" suffix.
# lang = "ind"
# if ignore_default and lang == get_default_language():
# return field_name
# return "{}_{}".format(field_name, lang.replace("-", "_"))
#
# def get_instance_field_value(instance, path):
# """
# Return the value of a field or related field for a model instance.
# """
# value = instance
# for bit in path.split(LOOKUP_SEP):
# try:
# value = getattr(value, bit)
# except AttributeError:
# return None
#
# return value
#
# def get_language():
# """
# Return an active language code that is guaranteed to be in settings.LANGUAGES
#
# (Django does not seem to guarantee this for us.)
# """
# lang = _get_language()
# if lang in get_available_languages():
# return lang
# return get_default_language()
#
# def get_model_field(model, path):
# """
# Return the django model field for model in context, following relations.
# """
#
# if not hasattr(model, "_meta"):
# raise ValueError("Argument 'Model' must be a django.db.models.Model instance.")
#
# field = None
# for bit in path.split(LOOKUP_SEP):
# try:
# field = model._meta.get_field(bit)
# except FieldDoesNotExist:
# return None
#
# if hasattr(field, "remote_field"):
# rel = getattr(field, "remote_field", None)
# model = getattr(rel, "model", model)
#
# return field
#
# def split_translated_fieldname(field_name):
# _pos = field_name.rfind("_")
# return (field_name[0:_pos], field_name[_pos + 1 :])
#
# Path: tests/app/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=255)
# body = models.TextField(null=True)
#
# category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
# site = models.ForeignKey(Site, null=True, blank=True, on_delete=models.CASCADE)
#
# i18n = TranslationField(fields=("title", "body"), required_languages=("nl",))
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
#
# name = models.CharField(max_length=255)
# title = models.CharField(max_length=255)
#
# i18n = TranslationField(fields=("name", "title"))
#
# objects = CategoryQueryset.as_manager()
#
# def __str__(self):
# return self.name
. Output only the next line. | with override("nl"): |
Using the snippet: <|code_start|>
with override("nl"):
self.assertEqual(get_language(), "nl")
with override("id"):
self.assertEqual(get_language(), "en")
def test_split_translated_fieldname(self):
self.assertEqual(split_translated_fieldname("title_nl"), ("title", "nl"))
self.assertEqual(split_translated_fieldname("full_name_nl"), ("full_name", "nl"))
def test_transform_translatable_fields(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo"}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_without_translations(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo", "i18n": None}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_keep_translations(self):
self.assertEqual(
transform_translatable_fields(
Blog, {"title": "bar", "title_de": "das foo", "i18n": {"title_nl": "foo"}}
),
{"i18n": {"title_nl": "foo", "title_de": "das foo"}, "title": "bar"},
<|code_end|>
, determine the next line of code. You have imports:
from django.test import TestCase
from django.utils.translation import override
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (
build_localized_fieldname,
get_instance_field_value,
get_language,
get_model_field,
split_translated_fieldname,
)
from .app.models import Blog, Category
and context (class names, function names, or code) available:
# Path: modeltrans/manager.py
# def transform_translatable_fields(model, fields):
# """
# Transform the kwargs for a <Model>.objects.create() or <Model>()
# to allow passing translated field names.
#
# Arguments:
# fields (dict): kwargs to a model __init__ or Model.objects.create() method
# for which the field names need to be translated to values in the i18n field
# """
# # If the current model does have the TranslationField, we must not apply
# # any transformation for it will result in a:
# # TypeError: 'i18n' is an invalid keyword argument for this function
# if not hasattr(model, "i18n"):
# return fields
#
# ret = {"i18n": fields.pop("i18n", None) or {}}
#
# # keep track of translated fields, and do not return an `i18n` key if no
# # translated fields are found.
# has_translated_fields = len(ret["i18n"].items()) > 0
#
# for field_name, value in fields.items():
# try:
# field = model._meta.get_field(field_name)
# except FieldDoesNotExist:
# ret[field_name] = value
# continue
#
# if isinstance(field, TranslatedVirtualField):
# has_translated_fields = True
# if field.get_language() == get_default_language():
# if field.original_name in fields:
# raise ValueError(
# 'Attempted override of "{}" with "{}". '
# "Only one of the two is allowed.".format(field.original_name, field_name)
# )
# ret[field.original_name] = value
# else:
# ret["i18n"][field.name] = value
# else:
# ret[field_name] = value
#
# if not has_translated_fields:
# return fields
#
# return ret
#
# Path: modeltrans/utils.py
# def build_localized_fieldname(field_name, lang, ignore_default=False):
# if lang == "id":
# # The 2-letter Indonesian language code is problematic with the
# # current naming scheme as Django foreign keys also add "id" suffix.
# lang = "ind"
# if ignore_default and lang == get_default_language():
# return field_name
# return "{}_{}".format(field_name, lang.replace("-", "_"))
#
# def get_instance_field_value(instance, path):
# """
# Return the value of a field or related field for a model instance.
# """
# value = instance
# for bit in path.split(LOOKUP_SEP):
# try:
# value = getattr(value, bit)
# except AttributeError:
# return None
#
# return value
#
# def get_language():
# """
# Return an active language code that is guaranteed to be in settings.LANGUAGES
#
# (Django does not seem to guarantee this for us.)
# """
# lang = _get_language()
# if lang in get_available_languages():
# return lang
# return get_default_language()
#
# def get_model_field(model, path):
# """
# Return the django model field for model in context, following relations.
# """
#
# if not hasattr(model, "_meta"):
# raise ValueError("Argument 'Model' must be a django.db.models.Model instance.")
#
# field = None
# for bit in path.split(LOOKUP_SEP):
# try:
# field = model._meta.get_field(bit)
# except FieldDoesNotExist:
# return None
#
# if hasattr(field, "remote_field"):
# rel = getattr(field, "remote_field", None)
# model = getattr(rel, "model", model)
#
# return field
#
# def split_translated_fieldname(field_name):
# _pos = field_name.rfind("_")
# return (field_name[0:_pos], field_name[_pos + 1 :])
#
# Path: tests/app/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=255)
# body = models.TextField(null=True)
#
# category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
# site = models.ForeignKey(Site, null=True, blank=True, on_delete=models.CASCADE)
#
# i18n = TranslationField(fields=("title", "body"), required_languages=("nl",))
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
#
# name = models.CharField(max_length=255)
# title = models.CharField(max_length=255)
#
# i18n = TranslationField(fields=("name", "title"))
#
# objects = CategoryQueryset.as_manager()
#
# def __str__(self):
# return self.name
. Output only the next line. | ) |
Continue the code snippet: <|code_start|>
class UtilsTest(TestCase):
def test_get_language(self):
self.assertEqual(get_language(), "en")
with override("nl"):
self.assertEqual(get_language(), "nl")
with override("id"):
self.assertEqual(get_language(), "en")
def test_split_translated_fieldname(self):
self.assertEqual(split_translated_fieldname("title_nl"), ("title", "nl"))
self.assertEqual(split_translated_fieldname("full_name_nl"), ("full_name", "nl"))
def test_transform_translatable_fields(self):
self.assertEqual(
transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo"}),
{"i18n": {"title_nl": "foo"}, "title": "bar"},
)
def test_transform_translatable_fields_without_translations(self):
<|code_end|>
. Use current file imports:
from django.test import TestCase
from django.utils.translation import override
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (
build_localized_fieldname,
get_instance_field_value,
get_language,
get_model_field,
split_translated_fieldname,
)
from .app.models import Blog, Category
and context (classes, functions, or code) from other files:
# Path: modeltrans/manager.py
# def transform_translatable_fields(model, fields):
# """
# Transform the kwargs for a <Model>.objects.create() or <Model>()
# to allow passing translated field names.
#
# Arguments:
# fields (dict): kwargs to a model __init__ or Model.objects.create() method
# for which the field names need to be translated to values in the i18n field
# """
# # If the current model does have the TranslationField, we must not apply
# # any transformation for it will result in a:
# # TypeError: 'i18n' is an invalid keyword argument for this function
# if not hasattr(model, "i18n"):
# return fields
#
# ret = {"i18n": fields.pop("i18n", None) or {}}
#
# # keep track of translated fields, and do not return an `i18n` key if no
# # translated fields are found.
# has_translated_fields = len(ret["i18n"].items()) > 0
#
# for field_name, value in fields.items():
# try:
# field = model._meta.get_field(field_name)
# except FieldDoesNotExist:
# ret[field_name] = value
# continue
#
# if isinstance(field, TranslatedVirtualField):
# has_translated_fields = True
# if field.get_language() == get_default_language():
# if field.original_name in fields:
# raise ValueError(
# 'Attempted override of "{}" with "{}". '
# "Only one of the two is allowed.".format(field.original_name, field_name)
# )
# ret[field.original_name] = value
# else:
# ret["i18n"][field.name] = value
# else:
# ret[field_name] = value
#
# if not has_translated_fields:
# return fields
#
# return ret
#
# Path: modeltrans/utils.py
# def build_localized_fieldname(field_name, lang, ignore_default=False):
# if lang == "id":
# # The 2-letter Indonesian language code is problematic with the
# # current naming scheme as Django foreign keys also add "id" suffix.
# lang = "ind"
# if ignore_default and lang == get_default_language():
# return field_name
# return "{}_{}".format(field_name, lang.replace("-", "_"))
#
# def get_instance_field_value(instance, path):
# """
# Return the value of a field or related field for a model instance.
# """
# value = instance
# for bit in path.split(LOOKUP_SEP):
# try:
# value = getattr(value, bit)
# except AttributeError:
# return None
#
# return value
#
# def get_language():
# """
# Return an active language code that is guaranteed to be in settings.LANGUAGES
#
# (Django does not seem to guarantee this for us.)
# """
# lang = _get_language()
# if lang in get_available_languages():
# return lang
# return get_default_language()
#
# def get_model_field(model, path):
# """
# Return the django model field for model in context, following relations.
# """
#
# if not hasattr(model, "_meta"):
# raise ValueError("Argument 'Model' must be a django.db.models.Model instance.")
#
# field = None
# for bit in path.split(LOOKUP_SEP):
# try:
# field = model._meta.get_field(bit)
# except FieldDoesNotExist:
# return None
#
# if hasattr(field, "remote_field"):
# rel = getattr(field, "remote_field", None)
# model = getattr(rel, "model", model)
#
# return field
#
# def split_translated_fieldname(field_name):
# _pos = field_name.rfind("_")
# return (field_name[0:_pos], field_name[_pos + 1 :])
#
# Path: tests/app/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=255)
# body = models.TextField(null=True)
#
# category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
# site = models.ForeignKey(Site, null=True, blank=True, on_delete=models.CASCADE)
#
# i18n = TranslationField(fields=("title", "body"), required_languages=("nl",))
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
#
# name = models.CharField(max_length=255)
# title = models.CharField(max_length=255)
#
# i18n = TranslationField(fields=("name", "title"))
#
# objects = CategoryQueryset.as_manager()
#
# def __str__(self):
# return self.name
. Output only the next line. | self.assertEqual( |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
list_display = ("title", "category")
@admin.register(Category)
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from .models import Blog, Category
and context (class names, function names, or code) available:
# Path: test_migrations/migrate_test/app/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=255)
# body = models.TextField(null=True, blank=True)
# category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE)
#
# # i18n = TranslationField(fields=("title", "body"), virtual_fields=False)
#
# class Meta:
# # indexes = [GinIndex(fields=["i18n"])]
# verbose_name_plural = "blogs"
#
# def __str__(self):
# return self.title
#
# class Category(models.Model):
# name = models.CharField(max_length=255)
#
# # i18n = TranslationField(fields=("name",), virtual_fields=False)
#
# class Meta:
# # indexes = [GinIndex(fields=["i18n"])]
# verbose_name_plural = "categories"
#
# def __str__(self):
# return self.name
. Output only the next line. | class CategoryAdmin(admin.ModelAdmin): |
Based on the snippet: <|code_start|> self.wikipedia = Category.objects.get(name="Wikipedia")
def test_limited_admin(self):
urls = [
reverse("admin:app_category_changelist"),
reverse("admin:app_category_change", args=(self.wikipedia.pk,)),
]
for url in urls:
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertContains(response, self.wikipedia.name)
with override("nl"):
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertContains(response, self.wikipedia.name)
with override("de"):
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertContains(response, self.wikipedia.name)
def test_non_translated_admin(self):
url = reverse("admin:app_site_change", args=(self.site.pk,))
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_search(self):
def url(q):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.utils.translation import override
from .app.models import Category, Site
from .utils import load_wiki
and context (classes, functions, sometimes code) from other files:
# Path: tests/app/models.py
# class Category(models.Model):
#
# name = models.CharField(max_length=255)
# title = models.CharField(max_length=255)
#
# i18n = TranslationField(fields=("name", "title"))
#
# objects = CategoryQueryset.as_manager()
#
# def __str__(self):
# return self.name
#
# class Site(models.Model):
# name = models.CharField(max_length=255)
#
# objects = MultilingualManager()
#
# def __str__(self):
# return self.name
#
# Path: tests/utils.py
# def load_wiki():
# wiki = Category.objects.create(name="Wikipedia")
# with open(os.path.join("tests", "fixtures", "fulltextsearch.json")) as infile:
# data = json.load(infile)
#
# for article in data:
# kwargs = {}
# for item in article:
# lang = "_" + item["lang"]
#
# kwargs["title" + lang] = item["title"]
# kwargs["body" + lang] = item["body"]
#
# Blog.objects.create(category=wiki, **kwargs)
. Output only the next line. | return "{}?q={}".format(reverse("admin:app_blog_changelist"), q) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.