Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>
class DashboardView(TemplateView):
template_name = "crumpet/pages/dashboard.html"
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if not request.user.is_authenticated():
return redirect(reverse('account_login... | form_class = forms.UserAccountForm |
Predict the next line after this snippet: <|code_start|>
class DashboardView(TemplateView):
template_name = "crumpet/pages/dashboard.html"
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if not request.user.is_authenticated():
return redirect(re... | user_account = models.UserAccount.objects.filter( |
Continue the code snippet: <|code_start|> ).first()
form.fields["api_key"].initial = user_account.api_key
form.fields["api_secret"].initial = user_account.api_secret
return context
def form_valid(self, form):
context = self.get_context_data()
exchange = form.cleaned... | Order.objects.all().delete() |
Predict the next line after this snippet: <|code_start|>
@python_2_unicode_compatible
class UserAccount(models.Model):
"""User profile"""
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
related_name="user_account"
)
exchange = models.CharField(
verbose_name="Crypto Excha... | choices=constants.CRYPTO_EXCHANGES, |
Predict the next line for this snippet: <|code_start|>"""crumpet URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlp... | if settings.DEBUG: |
Given the code snippet: <|code_start|>
class BacktestingView(FormView):
form_class = forms.ToTheMoonStrategyForm
template_name = "backtests/backtesting.html"
def form_valid(self, form):
context = self.get_context_data()
exchange = form.cleaned_data['exchange']
instrument = form.cl... | bot = Tradebot( |
Given the following code snippet before the placeholder: <|code_start|>
class BacktestingView(FormView):
form_class = forms.ToTheMoonStrategyForm
template_name = "backtests/backtesting.html"
def form_valid(self, form):
context = self.get_context_data()
exchange = form.cleaned_data['exchan... | wallet = Wallet(assets=100, currency=100, instrument=instrument, fee=trading_fee) |
Next line prediction: <|code_start|> return False
return True
@property
def crosses_up(self):
if self.ema[-2] > self.sma[-2] and self.ema[-1] < self.sma[-1]:
return 'sma'
elif self.ema[-2] < self.sma[-2] and self.ema[-1] > self.sma[-1]:
return 'ema'
... | if max_buy_amount >= MINIMUM_AMOUNT: |
Predict the next line for this snippet: <|code_start|>
class BaseStrategy(object):
'''
The base strategy that all strategies inherit from.
'''
def __init__(self):
self.tick = []
@staticmethod
<|code_end|>
with the help of current file imports:
import datetime
import math
import numpy
... | def buy(timer: str, amount: float, price: float, wallet: Wallet): |
Based on the snippet: <|code_start|>Author: Derek Stegelman
"""
from __future__ import unicode_literals
@python_2_unicode_compatible
class Category(models.Model):
"""
Category model
"""
name = models.CharField(max_length=250, blank=True)
slug = models.SlugField(blank=True, null=True, editabl... | unique_slugify(self, self.name) |
Given the code snippet: <|code_start|> and update the feeds.
"""
if force or not force and self.last_update < datetime.date.today():
self._update_processor()
return True
@models.permalink
def get_absolute_url(self):
"""
Feed permalink
:ret... | objects = FeedItemManager() |
Predict the next line for this snippet: <|code_start|>"""
Django Feedme
Forms.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
class AddFeedForm(forms.ModelForm):
"""
Simple add feed form
"""
class Meta:
<|code_end|>
with the help of current file imports:
from django import... | model = Feed |
Given the code snippet: <|code_start|>"""
Django Feedme
Forms.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
class AddFeedForm(forms.ModelForm):
"""
Simple add feed form
"""
class Meta:
model = Feed
exclude = ('user', 'title')
class ImportFeedForm(forms.Fo... | self.fields['category'].queryset = Category.objects.filter(user=user) |
Continue the code snippet: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
<|code_end|>
. Use current file imports:
from django.conf.urls import url
from .views import FeedList, ImportView, AddView, mark_all_as_read, mark_as_read
and con... | url(r'^$', FeedList.as_view(), name="feedme-feed-list"), |
Given snippet: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', FeedList.as_view(), name="feedme-feed-list"),
url(r'^by_category/(?P<category>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-category'),
url(r... | url(r'^import/$', ImportView.as_view(), name='feedme-import-google-takeout'), |
Given the following code snippet before the placeholder: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', FeedList.as_view(), name="feedme-feed-list"),
url(r'^by_category/(?P<category>[-\w]+)/$', FeedList.as_view(), name=... | url(r'^ajax/add/$', AddView.as_view(), name='feedme-add-ajax'), |
Predict the next line for this snippet: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', FeedList.as_view(), name="feedme-feed-list"),
url(r'^by_category/(?P<category>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list... | url(r'^mark_all_as_read/$', mark_all_as_read, name='feedme-mark-all-as-read'), |
Here is a snippet: <|code_start|>"""
Django Feedme
Urls.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
urlpatterns = [
url(r'^$', FeedList.as_view(), name="feedme-feed-list"),
url(r'^by_category/(?P<category>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-category'),
u... | url(r'^ajax/mark_as_read/$', mark_as_read, name='feedme-mark-as-read-ajax'), |
Using the snippet: <|code_start|>"""
Django Feedme
Digest.py
Author: Derek Stegelman
"""
from __future__ import unicode_literals
def send_digest():
"""
Send the daily digest for all users. This sends
both a .txt and .html version of the email.
:return:
"""
text_template = loader.get_templa... | items = FeedItem.objects.my_feed_items(user).yesterday() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class Command(BaseCommand):
"""
Update all feed objects manually.
"""
help = 'Update all feeds'
def handle(self, *args, **options):
count = 0
<|code_end|>
, determine the next line of code. You have imports:
from django.core.mana... | for feed in Feed.objects.all(): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class Command(BaseCommand):
"""
Management command to send the daily digest. Typically
called by Celery.
"""
help = 'Send Digest'
def handle(self, *args, **options):
<|code_end|>
, determine the next line of code. You have imports:
... | digest.send_digest() |
Here is a snippet: <|code_start|>from __future__ import unicode_literals
class FeedMeTestCase(TestCase):
def test_update_feed(self):
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.test import TestCa... | feed = Feed(url='http://rss.cnn.com/rss/cnn_topstories.rss') |
Based on the snippet: <|code_start|>from __future__ import unicode_literals
class FeedMeTestCase(TestCase):
def test_update_feed(self):
feed = Feed(url='http://rss.cnn.com/rss/cnn_topstories.rss')
feed.save()
feed.update(force=True)
<|code_end|>
, predict the immediate next line with the... | self.assertEqual(FeedItem.objects.all().count(), 10) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# TODO: can be simplified into, after merging https://github.com/divio/django-cms/pull/5898
# from blogit.urls import get_urls
# def get_urls(self, page=None, language=None, **kwarg... | if bs.SINGLE_APPHOOK: |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
except ImportError:
USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
@python_2_unicode_compatible
class Category(MPTTModel, TranslatableModel):
"""
Cat... | active = models.BooleanField(_('Active'), default=True, help_text=bs.ACTIVE_FIELD_HELP_TEXT) |
Given snippet: <|code_start|> date_added = models.DateTimeField(_('Date added'), auto_now_add=True)
last_modified = models.DateTimeField(_('Last modified'), auto_now=True)
status = models.IntegerField(_('Status'), choices=STATUS_CODES, default=DRAFT, help_text=_(
'When draft post is visible to staff... | objects = PostManager() |
Here is a snippet: <|code_start|> 'slug': self.safe_translation_getter('slug'),
})
return reverse('blogit_post_detail', kwargs={
'slug': self.safe_translation_getter('slug')})
def get_search_data(self, language=None, request=None):
"""
... | bits.append(get_text_from_placeholder(self.body, language, request)) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_numgrad"]
def f1(x):
return -0.5 * np.sum(x**2)
def dfdx1(x):
return -x
def f2(x):
return np.sum(x)
def dfdx2(x):
return np.ones(len(x))
@pytest.mark.parametrize("... | [numerical_gradient_1, numerical_gradient_2], |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_numgrad"]
def f1(x):
return -0.5 * np.sum(x**2)
def dfdx1(x):
return -x
def f2(x):
return np.sum(x)
def dfdx2(x):
return np.ones(len(x))
@pytest.mark.parametrize("... | [numerical_gradient_1, numerical_gradient_2], |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
try:
except ImportError:
gaussian_kde = None
__all__ = ["KDEMove"]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from scipy.stats import gaussian_... | class KDEMove(RedBlueMove): |
Next line prediction: <|code_start|>
def get_log_probability(self, **kwargs):
"""Get the chain of log probabilities evaluated at the MCMC samples.
Args:
flat (Optional[bool]): Flatten the chain across the ensemble.
(default: ``False``)
thin (Optional[int]): T... | return integrated_time(np.mean(self.get_value("coords"), axis=1), |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_simple"]
def test_simple():
<|code_end|>
, generate the next line using the imports in this file:
from ..common import UniformWalker
and context (functions, classes, or occasionally code... | UniformWalker() |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_dtype", "test_serialization", "test_repr"]
def test_dtype(seed=1234):
np.random.seed(seed)
dtype = [
("coords", np.float64, (4, )),
("log_prior", np.float64),
... | state = State(coords) |
Given the code snippet: <|code_start|>
class Ensemble(object):
"""The state of the ensemble of walkers.
Args:
model (callable or Model): The model specification. This can be a
callable, an instance of :class:`SimpleModel`, or another instance
that quacks like a :class:`Model`. ... | self.pool = DefaultPool() if pool is None else pool |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["Ensemble"]
class Ensemble(object):
"""The state of the ensemble of walkers.
Args:
model (callable or Model): The model specification. This can be a
... | if is_model(model): |
Predict the next line after this snippet: <|code_start|>__all__ = ["Ensemble"]
class Ensemble(object):
"""The state of the ensemble of walkers.
Args:
model (callable or Model): The model specification. This can be a
callable, an instance of :class:`SimpleModel`, or another instance
... | self.model = SimpleModel(model) |
Given the following code snippet before the placeholder: <|code_start|>
def __init__(self, random, model, cov, epsilon, nsteps=None):
self.random = random
self.model = model
self.nsteps = nsteps
self.epsilon = epsilon
if len(np.atleast_1d(cov).shape) == 2:
self.co... | state = self.model.compute_grad_log_probability(State(q)) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_nd", "test_too_short"]
def get_chain(seed=1234, ndim=3, N=100000):
np.random.seed(seed)
a = 0.9
x = np.empty((N, ndim))
x[0] = np.zeros(ndim)
for i in r... | tau, M = integrated_time(x, c=c, full_output=True) |
Here is a snippet: <|code_start|>
__all__ = ["test_nd", "test_too_short"]
def get_chain(seed=1234, ndim=3, N=100000):
np.random.seed(seed)
a = 0.9
x = np.empty((N, ndim))
x[0] = np.zeros(ndim)
for i in range(1, N):
x[i] = x[i-1] * a + np.random.rand(ndim)
return x
def test_1d(seed=1... | with pytest.raises(AutocorrError): |
Predict the next line for this snippet: <|code_start|>sys.path.insert(0, '/Users/nick/dev/conversation')
parser = optparse.OptionParser()
parser.add_option('-s', '--start',
action="store", dest="start_date",
help="start date", default="today")
options, args = parser.parse_args()
if options.start_date ... | count = postsdb.get_post_count_for_range(start_date, end_date) |
Based on the snippet: <|code_start|>try:
sys.path.insert(0, '/Users/nick/dev/theconversation')
except:
print "could not import -- must be running on heroku"
cio = CustomerIO(settings.get('customer_io_site_id'), settings.get('customer_io_api_key'))
<|code_end|>
, predict the immediate next line with the help of imp... | users = userdb.get_all() |
Predict the next line after this snippet: <|code_start|> userdb.save_user(user)
self.redirect("/user/%s/settings?msg=updated" % user['user']['screen_name'])
###########################
### LOG USER OUT OF ACCOUNT
### /auth/logout
###########################
class LogOut(app.basic.BaseHandler):
def ... | posts = mentionsdb.get_mentions_by_user(screen_name.lower(), per_page, page) |
Continue the code snippet: <|code_start|> email = self.get_argument('email', '')
subscribe_to = self.get_argument('subscribe_to', '')
error = ''
status = ''
slug = ''
if close_popup != '':
status = 'close_popup'
# get the current user's email value
... | post = postsdb.get_post_by_slug(subscribe_to) |
Predict the next line for this snippet: <|code_start|> self.clear_all_cookies()
self.redirect(self.get_argument('next', '/'))
##########################
### USER PROFILE
### /user/(.+)
##########################
class Profile(app.basic.BaseHandler):
def get(self, screen_name, section="shares"):
... | tags = tagsdb.get_user_tags(screen_name) |
Next line prediction: <|code_start|>
###########################
### EMAIL SETTINGS
### /auth/email/?
###########################
class EmailSettings(app.basic.BaseHandler):
@tornado.web.authenticated
def get(self):
next_page = self.get_argument('next', '')
subscribe_to = self.get_argument('sub... | user = userdb.get_user_by_screen_name(self.current_user) |
Using the snippet: <|code_start|> auth_url = auth.get_authorization_url(True)
self.set_secure_cookie("request_token_key", auth.request_token.key)
self.set_secure_cookie("request_token_secret", auth.request_token.secret)
redirect = self.get_argument('next', '/')
self.set_secure_coo... | user = userdb.get_user_by_screen_name(screen_name) |
Here is a snippet: <|code_start|>
class BaseHandler(tornado.web.RequestHandler):
def __init__(self, *args, **kwargs):
super(BaseHandler, self).__init__(*args, **kwargs)
#user = self.get_current_user()
#css_file = "%s/css/threatvector.css" % settings.tornado_config['static_path']
#cs... | kwargs['user_obj'] = userdb.get_user_by_screen_name(self.current_user) |
Predict the next line for this snippet: <|code_start|>
#########################
### Alerting to share owner (and other subscribers) on new Disqus comments
### /api/incr_comment_count
#########################
class DisqusCallback(app.basic.BaseHandler):
def get(self):
comment = self.get_argument('comment'... | post = postsdb.get_post_by_slug(post_slug) |
Given the code snippet: <|code_start|>
#########################
### Alerting to share owner (and other subscribers) on new Disqus comments
### /api/incr_comment_count
#########################
class DisqusCallback(app.basic.BaseHandler):
def get(self):
comment = self.get_argument('comment', '')
po... | author = userdb.get_user_by_screen_name(self.current_user) |
Here is a snippet: <|code_start|>
######################
### WEEKLY STATS
### /stats/shares/weekly
######################
class WeeklyShareStats(app.basic.BaseHandler):
def get(self):
# get the stats based on the past 7 days
today = datetime.today()
week_ago = today + timedelta(days=-7)
... | unique_posters = postsdb.get_unique_posters(week_ago, today) |
Based on the snippet: <|code_start|>
# track emails sent to users
"""
{
_id: ...,
timestamp: Date(),
subject: "",
body: "",
recipients: []
}
"""
db.user_info.ensure_index('wants_daily_email')
#
# Construct a daily email
#
def construct_daily_email(slugs):
from_email = "w... | post = postsdb.get_post_by_slug(slug) |
Given the code snippet: <|code_start|> body_html += "<p>discussion: <a href='http://%s/posts/%s'>http://%s/posts/%s</a></p>" % (settings.get('base_url'), post['slug'], settings.get('base_url'), post['slug'])
body_html += "<hr />"
body_html += "Want to unsubscribe? Visit http://%s/user/settings" % set... | recipients = userdb.get_newsletter_recipients() |
Here is a snippet: <|code_start|> def get(self):
if not self.current_user_can('delete_users'):
self.redirect('/')
else:
msg = self.get_argument('msg', '')
self.render('admin/delete_user.html', msg=msg)
@tornado.web.authenticated
def post(self):
if ... | hackpads = hackpad.create_hackpad() |
Given snippet: <|code_start|>
############################
# ADMIN NEWSLETTER
# /admin/newsletter
############################
class DailyEmail(app.basic.BaseHandler):
def get(self):
posts = postsdb.get_hot_posts()
has_previewed = self.get_argument("preview", False)
<|code_end|>
, continue by predi... | recipients = userdb.get_newsletter_recipients() |
Given the code snippet: <|code_start|>
############################
# ADMIN NEWSLETTER
# /admin/newsletter
############################
class DailyEmail(app.basic.BaseHandler):
def get(self):
posts = postsdb.get_hot_posts()
has_previewed = self.get_argument("preview", False)
recipients = us... | response1 = emailsdb.construct_daily_email(slugs) |
Using the snippet: <|code_start|> post['muted'] = False
post['comment_count'] = 0
post['disqus_thread_id_str'] = ''
post['sort_score'] = 0.0
post['downvotes'] = 0
post['hackpad_url'] = ''
post['date_created'] ... | mentionsdb.add_mention(mention.lower(), post['slug']) |
Using the snippet: <|code_start|>#-*- coding:utf-8 -*-
###############
### New Post
### /posts
###############
class NewPost(app.basic.BaseHandler):
@tornado.web.authenticated
def get(self):
post = {}
post['title'] = self.get_argument('title', '')
post['url'] = self.get_argument('url'... | post = postsdb.get_post_by_slug(slug) |
Given the code snippet: <|code_start|> post['title'] = self.get_argument('title', '')
post['url'] = self.get_argument('url', '')
is_bookmarklet = False
if self.request.path.find('/bookmarklet') == 0:
is_bookmarklet = True
self.render('post/new_post.html', post=post, i... | tags_alpha = tagsdb.get_all_tags(sort="alpha") |
Given snippet: <|code_start|> # check if there is an existing URL
if post['url'] != '':
url = urlparse(post['url'])
netloc = url.netloc.split('.')
if netloc[0] == 'www':
del netloc[0]
path = url.path
... | userdb.add_tags_to_user(self.current_user, post['tags']) |
Predict the next line for this snippet: <|code_start|> def get(self, slug):
# nothing to see here
return
def post(self, slug):
# user must be logged in
msg = {}
if not self.current_user:
msg = {'error': 'You must be logged in to bump.', 'redirect': True}
... | text = "Woo!\n\n%s" % template_helpers.post_permalink(post) |
Using the snippet: <|code_start|># Run by Heroku scheduler every night
# If running locally, uncomment below imports
sys.path.insert(0, '/Users/nick/dev/usv/usv.com')
# 1) get 5 slugs
posts = postsdb.get_hot_posts_by_day(datetime.today())
slugs = []
for i, post in enumerate(posts):
if i < 5:
slugs.append(... | request3 = emailsdb.add_list_to_email() |
Continue the code snippet: <|code_start|>
def opendap_metadata(opendap_url):
response = urllib.urlopen(opendap_url + ".das")
return response.read()
def load(url, frm, name):
if url.split(".")[-1] != "gz":
url = url + "gz"
if frm == "ASCII":
<|code_end|>
. Use current file imports:
from pydap.... | urllib.urlretrieve ("{0}.ascii".format(url), "{0}{1}".format(MEDIA_ROOT + MEDIA_URL, "{0}.ascii".format(name))) |
Continue the code snippet: <|code_start|>
def opendap_metadata(opendap_url):
response = urllib.urlopen(opendap_url + ".das")
return response.read()
def load(url, frm, name):
if url.split(".")[-1] != "gz":
url = url + "gz"
if frm == "ASCII":
<|code_end|>
. Use current file imports:
from pydap.... | urllib.urlretrieve ("{0}.ascii".format(url), "{0}{1}".format(MEDIA_ROOT + MEDIA_URL, "{0}.ascii".format(name))) |
Given snippet: <|code_start|>
@dajaxice_register(method='GET')
def opendap_getdata(request, opendap_url, frm, opendap_out_name):
if frm == "nc3" or frm == "nc4":
check_frm = "nc"
else:
check_frm = frm
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import o... | if os.path.isfile('{0}{1}{2}'.format(MEDIA_ROOT, MEDIA_URL, '{0}.{1}'.format(opendap_out_name, check_frm))): |
Predict the next line for this snippet: <|code_start|>
@dajaxice_register(method='GET')
def opendap_getdata(request, opendap_url, frm, opendap_out_name):
if frm == "nc3" or frm == "nc4":
check_frm = "nc"
else:
check_frm = frm
<|code_end|>
with the help of current file imports:
import os, shu... | if os.path.isfile('{0}{1}{2}'.format(MEDIA_ROOT, MEDIA_URL, '{0}.{1}'.format(opendap_out_name, check_frm))): |
Continue the code snippet: <|code_start|>
class BackendTests(TestCase):
"""
Tests for LazySignupBackend
"""
def setUp(self):
<|code_end|>
. Use current file imports:
from django.contrib.auth import get_user_model
from django.test import TestCase
from lazysignup.backends import LazySignupBackend
and c... | self.backend = LazySignupBackend() |
Using the snippet: <|code_start|>
@allow_lazy_user
def convert(request, form_class=None,
redirect_field_name='redirect_to',
anonymous_redirect=settings.LOGIN_URL,
template_name='lazysignup/convert.html',
ajax_template_name='lazysignup/convert_ajax.html'):
""" Conver... | except NotLazyError: |
Given the following code snippet before the placeholder: <|code_start|>
@allow_lazy_user
def convert(request, form_class=None,
redirect_field_name='redirect_to',
anonymous_redirect=settings.LOGIN_URL,
template_name='lazysignup/convert.html',
ajax_template_name='lazysign... | LazyUser.objects.convert(form) |
Predict the next line after this snippet: <|code_start|>
@allow_lazy_user
def convert(request, form_class=None,
redirect_field_name='redirect_to',
anonymous_redirect=settings.LOGIN_URL,
template_name='lazysignup/convert.html',
ajax_template_name='lazysignup/convert_ajax... | form_class = UserCreationForm |
Given the code snippet: <|code_start|>
@allow_lazy_user
def convert(request, form_class=None,
redirect_field_name='redirect_to',
anonymous_redirect=settings.LOGIN_URL,
template_name='lazysignup/convert.html',
ajax_template_name='lazysignup/convert_ajax.html'):
""" C... | if constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM is not None: |
Next line prediction: <|code_start|>
class LazyUserManagerTests(TestCase):
"""
Tests for LazyUserManager
"""
def test_generate_username_no_method(self):
"""
Tests auto generated UUID username
"""
mock_user_class = Mock(generate_username=1)
del mock_user_class.ge... | username = LazyUser.objects.generate_username(mock_user_class) |
Given the code snippet: <|code_start|>
class Command(BaseCommand):
help = u"""Remove all users whose sessions have expired and who haven't
set a password. This assumes you are using database sessions"""
def handle(self, **options):
# Delete each of these users. We don't use the querys... | return LazyUser.objects.filter( |
Continue the code snippet: <|code_start|>
def view(request):
r = HttpResponse()
try:
if request.user.is_authenticated():
r.status_code = 500
except TypeError:
if request.user.is_authenticated:
r.status_code = 500
return r
<|code_end|>
. Use current file import... | @allow_lazy_user |
Based on the snippet: <|code_start|>
def view(request):
r = HttpResponse()
try:
if request.user.is_authenticated():
r.status_code = 500
except TypeError:
if request.user.is_authenticated:
r.status_code = 500
return r
@allow_lazy_user
def lazy_view(request):
... | @require_lazy_user("view-for-nonlazy-users") |
Given the following code snippet before the placeholder: <|code_start|>
def view(request):
r = HttpResponse()
try:
if request.user.is_authenticated():
r.status_code = 500
except TypeError:
if request.user.is_authenticated:
r.status_code = 500
return r
@allow_l... | @require_nonlazy_user("view-for-lazy-users") |
Given the following code snippet before the placeholder: <|code_start|> """ Hardcoded credentials to demonstrate that the get_credentials method
is being used
"""
error_messages = {
'duplicate_username': _("A user with that username already exists."),
'password_mismatch': _("The two passw... | model = CustomUser |
Given the code snippet: <|code_start|>
class CustomUserModelTests(TestCase):
"""
Test for custom user model
"""
def setUp(self):
super(CustomUserModelTests, self).setUp()
self.request = HttpRequest()
SessionMiddleware().process_request(self.request)
# We have to save t... | self.assertFalse(is_lazy_user(user)) |
Predict the next line for this snippet: <|code_start|>
class LazyUserModelTests(TestCase):
"""
Tests for LazyUser Model
"""
def setUp(self):
super(LazyUserModelTests, self).setUp()
def test_str(self):
"""
Tests str method on LazyUser
"""
<|code_end|>
with the help... | user, username = LazyUser.objects.create_lazy_user() |
Here is a snippet: <|code_start|>
if settings.AUTH_USER_MODEL is 'auth.User': # pragma: no cover
else: # pragma: no cover
admin.autodiscover()
# URL test patterns for lazysignup. Use this file to ensure a consistent
# set of URL patterns are used when running unit tests.
urlpatterns = [
url(r'^admin/?', a... | url(r'^custom_convert/', views.convert, { |
Using the snippet: <|code_start|>
if settings.AUTH_USER_MODEL is 'auth.User': # pragma: no cover
else: # pragma: no cover
admin.autodiscover()
# URL test patterns for lazysignup. Use this file to ensure a consistent
# set of URL patterns are used when running unit tests.
urlpatterns = [
url(r'^admin/?', a... | url(r'^nolazy/$', test_views.view, name='test_view'), |
Given the code snippet: <|code_start|>
DEFAULT_BLACKLIST = (
'slurp',
'googlebot',
'yandex',
'msnbot',
'baiduspider',
)
for user_agent in getattr(settings, 'LAZYSIGNUP_USER_AGENT_BLACKLIST', DEFAULT_BLACKLIST):
<|code_end|>
, generate the next line using the imports in this file:
import re
import... | USER_AGENT_BLACKLIST.append(re.compile(user_agent, re.I)) |
Predict the next line for this snippet: <|code_start|>class LazyUserManager(models.Manager):
def __hash__(self):
"""
Implemented so signal can be sent in .convert() for Django 1.8
"""
return hash(str(self))
username_field = get_user_model().USERNAME_FIELD
def create_lazy_u... | raise NotLazyError('You cannot convert a non-lazy user') |
Here is a snippet: <|code_start|>
class LazyUserManager(models.Manager):
def __hash__(self):
"""
Implemented so signal can be sent in .convert() for Django 1.8
"""
return hash(str(self))
username_field = get_user_model().USERNAME_FIELD
def create_lazy_user(self):
"... | if not is_lazy_user(form.instance): |
Given the code snippet: <|code_start|>
username_field = get_user_model().USERNAME_FIELD
def create_lazy_user(self):
""" Create a lazy user. Returns a 2-tuple of the underlying User
object (which may be of a custom class), and the username.
"""
user_class = self.model.get_user_cl... | converted.send(self, user=user) |
Given the code snippet: <|code_start|>
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy.
"""
if not is_lazy_user(form.instance):
raise NotLazyError('You cannot convert a non-lazy user')
user = form.save()
# We need to re... | user = models.OneToOneField(constants.LAZYSIGNUP_USER_MODEL, on_delete=models.CASCADE) |
Using the snippet: <|code_start|>
ALLOW_LAZY_REGISTRY = {}
def allow_lazy_user(func):
def wrapped(request, *args, **kwargs):
assert hasattr(request, 'session'), ("You need to have the session "
"app installed")
if getattr(settings, 'LAZYSIGNUP_ENABLE'... | for user_agent in USER_AGENT_BLACKLIST: |
Based on the snippet: <|code_start|> for user_agent in USER_AGENT_BLACKLIST:
if user_agent.search(request_user_agent):
ignore = True
break
# If there's already a key in the session for a valid user, then
# we don't need to do an... | if is_lazy_user(request.user): |
Next line prediction: <|code_start|>
urlpatterns = patterns(
'',
url(r'^game/update/(?P<pk>\w+)/$',
<|code_end|>
. Use current file imports:
(from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from hubcave.game import views)
and context including class names,... | login_required(views.GameUpdate.as_view(), login_url='/'), |
Predict the next line for this snippet: <|code_start|>
urlpatterns = patterns(
'',
url(r'^profile/(?P<pk>\w+)/$',
<|code_end|>
with the help of current file imports:
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from hubcave.userprofile.views import Prof... | login_required(ProfileDetail.as_view(), login_url='/'), |
Given the code snippet: <|code_start|>
socketio.sdjango.autodiscover()
admin.autodiscover()
urlpatterns = patterns(
'',
<|code_end|>
, generate the next line using the imports in this file:
from django.contrib import admin
from django.conf.urls import patterns, include, url
from django.views.generic import Temp... | url(r'^$', views.Index.as_view(), name='index'), |
Next line prediction: <|code_start|>
# Create your views here.
class ProfileDetail(DetailView):
model = User
def dispatch(self, request, *args, **kwargs):
return super(ProfileDetail, self).dispatch(request, *args, **kwargs)
def get_template_names(self):
return ['userprofile/profile_detail.... | profile = UserProfile.objects.get_or_create(user=self.object) |
Here is a snippet: <|code_start|>
# Create your views here.
class ProfileDetail(DetailView):
model = User
def dispatch(self, request, *args, **kwargs):
return super(ProfileDetail, self).dispatch(request, *args, **kwargs)
def get_template_names(self):
return ['userprofile/profile_detail.htm... | context['users_games'] = Game.objects.filter(user=self.object) |
Given the following code snippet before the placeholder: <|code_start|>"""
This is a hacky way of having items do arbitrary things
"""
def add_to_inventory(ns, item):
def check_size():
<|code_end|>
, predict the next line using imports from the current file:
from hubcave.game.models import InventoryItem, Stackabl... | if len(InventoryItem.objects.filter(inventory=ns.inventory)) > 9: |
Given snippet: <|code_start|>"""
This is a hacky way of having items do arbitrary things
"""
def add_to_inventory(ns, item):
def check_size():
if len(InventoryItem.objects.filter(inventory=ns.inventory)) > 9:
raise Exception("Can't add any more")
if not item.item.stackable:
check_... | new_item = StackableInventoryItem.objects.get( |
Using the snippet: <|code_start|>
# Add the project to the python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
sys.stdout = sys.stderr
# Configure the application (Logan)
configure()
<|code_end|>
, determine the next line of code. You have imports:
import os
import os.path
import sy... | start_new_thread(run_socket_server, ("0.0.0.0", "8018")) |
Here is a snippet: <|code_start|>
# Create your models here.
class Dashboard(models.Model):
user = models.ForeignKey(User)
@property
def token(self):
return self.user.social_auth.get(provider='github').extra_data['access_token']
def get_or_update_games(self):
"""
Update the g... | all_games = Game.objects.filter(user=self.user) |
Continue the code snippet: <|code_start|>
urlpatterns = patterns(
'',
url(r'^dashboard/$',
<|code_end|>
. Use current file imports:
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from hubcave.dashboard.views import DashboardView
and context (classes, func... | login_required(DashboardView.as_view(), login_url='/'), |
Based on the snippet: <|code_start|>
def user_choices():
yield (None, '--------')
for u in User.objects.all():
yield (u.username, u.username)
class UserSwitchForm(forms.Form):
username = forms.ChoiceField(label='Select user',
choices=user_choices)
class UserPoli... | policy = forms.ModelChoiceField(queryset=Policy.objects.all(), |
Predict the next line after this snippet: <|code_start|>
def user_choices():
yield (None, '--------')
for u in User.objects.all():
yield (u.username, u.username)
class UserSwitchForm(forms.Form):
username = forms.ChoiceField(label='Select user',
choices=user_choic... | queryset=Organisation.objects.all(), empty_label='*', required=False |
Predict the next line after this snippet: <|code_start|>
def user_choices():
yield (None, '--------')
for u in User.objects.all():
yield (u.username, u.username)
class UserSwitchForm(forms.Form):
username = forms.ChoiceField(label='Select user',
choices=user_choic... | queryset=Project.objects.all(), empty_label='*', required=False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.