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': 'repoxplore... | 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': CSVRende... | 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/LIC... | 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 f... | 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, regularizati... | 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 choic... | 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_coup... | } |
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... | '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_... | '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.S... | 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 o... | 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, "tojrbxmkuzrarnniosu... | 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) f... | 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.pla... | 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_... | 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_... | 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 = M... | 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': 'xbwggirmqtqvbpcj... | '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_p... | 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_... | 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 No... | 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=... | 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=N... | 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,
... | 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)]
s... | 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 ... | 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)]
... | 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()... | 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)... | 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(cal... | 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):
# ... | 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 = uui... | 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, s... | 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 li... | 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': '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()
sel... | 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|>
, pred... | 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
... | 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 pypok... | 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_c... | 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... | 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_po... | 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/_tool... | 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 **kwa... | "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 b... | 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 am... | 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']
payment... | 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 = Pay... | 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_subs... | 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_l... | 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_descript... | '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 Non... | 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', ... | 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'... | 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_ad... | 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.g... | 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
fro... | 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
# ... | ('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:
... | 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.PO... | 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 HttpRespons... | 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 = co... | 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(first... | 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)
... | 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... | 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_... | 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_lo... | 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),
... | 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}"
... | 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 d... | 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 impo... | 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))
... | 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|>
, contin... | 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 Rep... | 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 ra... | 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)
ch... | 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... | '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_H... | } |
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 isins... | 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_enab... | }[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:
... | 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 =... | @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:
... | 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:
... | 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:... | 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... | 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... | 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, peri... | 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, *... | 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(so... | 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.ass... | 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(sp... | {"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"))... | ) |
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(), "... | 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_translata... | 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.man... | 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", "n... | ) |
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")
d... | 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... | 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:
... | 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.